diff --git a/.gitattributes b/.gitattributes index 3773b56307..bbb518d608 100644 --- a/.gitattributes +++ b/.gitattributes @@ -2,3 +2,6 @@ # Windows checkout (core.autocrlf): a CRLF shebang line does not start. *.sh text eol=lf port/android/gradlew text eol=lf + +# Preserve the pinned upstream decoder byte-for-byte, including its whitespace. +port/third_party/bcdec/bcdec.h -text -whitespace diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index e9810afbea..75281925ed 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,12 +1,13 @@ name: Build -# Debug and release builds of the native ports (Linux, Windows, Android) and -# the web port for every pushed commit, uploaded as artifacts. +# Debug builds of the native ports (Linux, Windows, Android) and the web +# port for every pushed commit. Release builds and their artifacts +# run only on main, including manually dispatched runs. # tools/ci_build.py does each build; see it for the options. # # Kept cheap: -# - one job per platform builds both configurations, so its set-up (tools, -# downloads, caches) is paid once; +# - one job per platform builds debug, plus release on main, so its set-up +# (tools, downloads, caches) is paid once; # - compiles go through ccache, whose cache carries over from run to run, so # a commit only recompiles what it changed; downloads (SDL, musl, Gradle, # the Linux build's system root) are cached too; @@ -18,8 +19,7 @@ name: Build # A successful build of main is also published as a GitHub release, the # newest marked latest, so that # https://github.com//releases/latest/download/ always -# gives the latest build; the last five are kept. Its web build is then the -# site on GitHub Pages (https://halocombatevolved.com/, port/web/README.md). +# gives the latest build; the last five are kept. on: push: paths-ignore: @@ -45,7 +45,49 @@ env: CCACHE_MAXSIZE: 1G jobs: + changelog: + # Generate once so every platform embeds exactly the same player notes. + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Find the last published build + id: previous + if: github.ref == 'refs/heads/main' + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + run: python3 tools/changelog_release_base.py --head "$GITHUB_SHA" --current-tag "build-$GITHUB_RUN_NUMBER" --output "$GITHUB_OUTPUT" --archive-output build/previous-changelog.json + + - name: Collect player notes + env: + PREVIOUS: ${{ steps.previous.outputs.base }} + run: | + args=() + if [ "$GITHUB_REF" = refs/heads/main ]; then + args+=(--build-number "$GITHUB_RUN_NUMBER" --require-notes) + else + args+=(--preview) + fi + if [ -n "$PREVIOUS" ]; then args+=(--base "$PREVIOUS"); fi + if [ -f build/previous-changelog.json ]; then args+=(--previous build/previous-changelog.json); fi + python3 tools/player_notes.py --head "$GITHUB_SHA" "${args[@]}" --output build/changelog + python3 tools/changelog_menu.py --notes build/changelog/changelog.json --text-only + cp port/assets/menus/ce/main_menu.changelog.port.xml build/changelog/ + + - uses: actions/upload-artifact@v4 + with: + name: player-changelog + path: build/changelog + if-no-files-found: error + overwrite: true + retention-days: 3 + linux: + needs: [changelog] # Arch Linux has what the build needs as packages: clang 22 (for the # profile-guided optimisation in pgo/), and CMake, pkg-config and # wayland-scanner for the SDL 3 that the portable build brings. The build @@ -59,11 +101,21 @@ jobs: - name: Install the toolchain run: | printf '\n[multilib]\nInclude = /etc/pacman.d/mirrorlist\n' >> /etc/pacman.conf - pacman -Syu --noconfirm --needed git zstd python python-pytest python-pillow python-numpy python-scipy ninja ccache \ + pacman -Syu --noconfirm --needed git zstd python python-pytest python-pillow python-numpy python-scipy python-fonttools ninja ccache \ clang lld gcc lib32-glibc lib32-gcc-libs cmake pkgconf wayland - uses: actions/checkout@v4 + - uses: actions/download-artifact@v4 + with: + name: player-changelog + path: build/changelog + + - name: Install player notes + run: | + cp build/changelog/main_menu.changelog.port.xml port/assets/menus/ce/ + cp build/changelog/changelog.json port/assets/changelog/notes.json + - uses: actions/cache@v4 with: path: .ccache @@ -87,20 +139,28 @@ jobs: run: python tools/ci_build.py linux profile - name: Release + if: github.ref == 'refs/heads/main' run: python tools/ci_build.py linux release - name: Test run: | - python -m pytest -q tools/test_loading_widescreen.py tools/test_loading_chant.py - python -m pytest -q tools/test_linux_port.py tools/test_android_asm_convert.py tools/test_android_mirror_uploads.py tools/test_android_frame_fences.py tools/test_android_static_geometry.py tools/test_android_render_policy.py tools/test_android_ce_texture_cache.py tools/test_host_watch_hash.py tools/test_touch_menu.py tools/harness tools/test_profile.py tools/stagekit/tests tools/test_net_compare.py tools/test_server_sim.py tools/test_egg.py tools/test_deploy_gametypes.py + python -m pytest -q tools/test_dualsense.py + python -m pytest -q tools/test_p2p_shutdown.py tools/test_network_test_sampling.py tools/test_network_test_startup.py + python -m pytest -q tools/test_loading_widescreen.py tools/test_loading_chant.py tools/test_reversed_depth.py + python -m pytest -q tools/test_linux_port.py tools/test_android_asm_convert.py tools/test_android_mirror_uploads.py tools/test_android_static_geometry.py tools/test_android_render_policy.py tools/test_android_ce_texture_cache.py tools/test_host_watch_hash.py tools/test_touch_menu.py tools/test_bots_menu.py tools/harness tools/test_profile.py tools/stagekit/tests tools/test_net_compare.py tools/test_visibility_readback_contract.py tools/test_server_sim.py tools/test_egg.py tools/test_deploy_gametypes.py + python -m pytest -q tools/test_shadow_setup.py tools/test_hud_shield_tick.py tools/test_render_target_binding.py + python -m pytest -q tools/test_android_mcc_memory.py tools/test_mcc_memory.py tools/test_android_dynamic_lighting.py tools/test_android_shader_logs.py tools/test_android_frame_fences.py + python -m pytest -q tools/test_changelog_layout.py tools/test_changelog_menu.py tools/test_gulch_build_label.py tools/test_player_notes.py tools/test_changelog_release_base.py + python -m pytest -q tools/test_third_person.py tools/test_camera_policy.py tools/test_camera_wire.py tools/test_camera_protocol.py tools/test_third_person_director.py tools/test_coop_checkpoint.py tools/test_coop_checkpoint_recovery.py tools/test_scripted_player_pose.py tools/test_checkpoint_epoch.py tools/test_join_protocol.py + python tools/test_checkpoint_timing.py # the dedicated server: --version, and --server without maps refused (exit code 2); its cases with # clients need the retail maps, and are skipped - python -m pytest -q tools/test_dedicated_server.py + python -m pytest -q tools/test_dedicated_server.py tools/test_king_network_state.py python tools/test_light_storage.py python -m pytest -q \ tools/test_mcc_cache_format.py tools/test_mcc_projectiles.py tools/test_mcc_tag_validation.py \ tools/test_mcc_share.py tools/test_mcc_share_rules.py tools/test_mcc_share_stage.py \ - tools/test_mcc_share_storage.py tools/test_mcc_share_metadata.py tools/test_mcc_load_network.py \ + tools/test_mcc_share_storage.py tools/test_mcc_share_metadata.py tools/test_mcc_load_network.py tools/test_mcc_loading_progress.py \ tools/test_checkpoint_epoch.py tools/test_coop_checkpoint.py tools/test_coop_checkpoint_recovery.py \ tools/test_mcc_checkpoint.py python -m pytest -q tools/test_keyboard_glyphs.py tools/test_menu_button_glyphs.py tools/test_mcc_keyboard_glyphs.py tools/test_controller_buttons.py tools/test_controller_remap.py tools/test_controller_remap_context.py tools/test_hud_button_style.py tools/test_hud_corrections.py @@ -115,12 +175,14 @@ jobs: retention-days: 3 - uses: actions/upload-artifact@v4 + if: github.ref == 'refs/heads/main' with: name: halo-linux-release path: dist/halo-linux-release retention-days: 3 android: + needs: [changelog] # The runner image has the Android SDK and NDK, a JDK and CMake. runs-on: ubuntu-24.04 timeout-minutes: 40 @@ -141,6 +203,16 @@ jobs: - uses: actions/checkout@v4 + - uses: actions/download-artifact@v4 + with: + name: player-changelog + path: build/changelog + + - name: Install player notes + run: | + cp build/changelog/main_menu.changelog.port.xml port/assets/menus/ce/ + cp build/changelog/changelog.json port/assets/changelog/notes.json + - uses: actions/cache@v4 with: path: .ccache @@ -164,17 +236,15 @@ jobs: # keystore, base64) and ANDROID_KEYSTORE_PASSWORD (its password, and # the key's, alias halo): every build signed with it installs over the # one before, as the app's self-updater (Updater.java) needs. Without - # them each build is signed with the runner's own debug key. + # them main must fail; other branches may use the runner's debug key. - name: Signing key env: KEYSTORE: ${{ secrets.ANDROID_KEYSTORE_BASE64 }} - run: | - if [ -n "$KEYSTORE" ]; then - printf '%s' "$KEYSTORE" | base64 -d > "$RUNNER_TEMP/halo.keystore" - echo "HALO_ANDROID_KEYSTORE=$RUNNER_TEMP/halo.keystore" >> "$GITHUB_ENV" - else - echo "::warning::no ANDROID_KEYSTORE_BASE64 secret: the Android builds cannot update over each other" - fi + HALO_ANDROID_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }} + run: python3 tools/android_signing.py + + - name: Test signing requirements + run: python3 tools/test_android_signing.py - name: Debug env: @@ -182,6 +252,7 @@ jobs: run: python3 tools/ci_build.py android debug - name: Release + if: github.ref == 'refs/heads/main' env: HALO_ANDROID_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }} run: python3 tools/ci_build.py android release @@ -192,6 +263,11 @@ jobs: python3 tools/test_touch_layout.py python3 tools/test_mcc_metadata_importer.py + - name: Test the MCC package importer + run: | + python3 -m pip install pytest + python3 -m pytest -q tools/test_mcc_android_importer.py + - name: Compile cache run: ccache --show-stats @@ -202,12 +278,14 @@ jobs: retention-days: 3 - uses: actions/upload-artifact@v4 + if: github.ref == 'refs/heads/main' with: name: halo-android-release path: dist/halo-android-release retention-days: 3 windows: + needs: [changelog] # The runner image has LLVM, Python and Visual Studio's x86 libraries and # Windows SDK. runs-on: windows-2025 @@ -232,6 +310,16 @@ jobs: - uses: actions/checkout@v4 + - uses: actions/download-artifact@v4 + with: + name: player-changelog + path: build/changelog + + - name: Install player notes + run: | + cp build/changelog/main_menu.changelog.port.xml port/assets/menus/ce/ + cp build/changelog/changelog.json port/assets/changelog/notes.json + - uses: actions/cache@v4 with: path: .ccache @@ -248,6 +336,7 @@ jobs: run: python tools/ci_build.py windows debug - name: Release + if: github.ref == 'refs/heads/main' run: python tools/ci_build.py windows release - name: Test MCC model geometry @@ -260,6 +349,17 @@ jobs: - name: Test light storage run: python tools/test_light_storage.py + - name: Test shared runtime regressions + shell: cmd + run: | + python -m pip install pytest + if errorlevel 1 exit /b 1 + for /f "usebackq tokens=*" %%i in (`"%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath`) do set "SHUTDOWN_VS_INSTALL=%%i" + if not defined SHUTDOWN_VS_INSTALL exit /b 1 + call "%SHUTDOWN_VS_INSTALL%\Common7\Tools\VsDevCmd.bat" -host_arch=x64 -arch=x86 + if errorlevel 1 exit /b 1 + python -m pytest -q tools/test_p2p_shutdown.py tools/test_network_test_sampling.py tools/test_network_test_startup.py tools/test_render_target_binding.py + - name: Compile cache run: ccache --show-stats @@ -270,6 +370,7 @@ jobs: retention-days: 3 - uses: actions/upload-artifact@v4 + if: github.ref == 'refs/heads/main' with: name: halo-windows-release path: dist/halo-windows-release @@ -283,12 +384,14 @@ jobs: retention-days: 3 - uses: actions/upload-artifact@v4 + if: github.ref == 'refs/heads/main' with: name: halo-windows-release-symbols path: dist/halo-windows-release-symbols retention-days: 3 web: + needs: [changelog] # Emscripten (emsdk, the version below, cached) builds the web port's # site (port/web/README.md); the tests check its graph, the page's # importer and service worker, its sockets, that it starts in a @@ -301,6 +404,16 @@ jobs: steps: - uses: actions/checkout@v4 + - uses: actions/download-artifact@v4 + with: + name: player-changelog + path: build/changelog + + - name: Install player notes + run: | + cp build/changelog/main_menu.changelog.port.xml port/assets/menus/ce/ + cp build/changelog/changelog.json port/assets/changelog/notes.json + - uses: actions/cache@v4 with: path: ~/emsdk @@ -315,7 +428,7 @@ jobs: fi ~/emsdk/emsdk activate "$EMSDK_VERSION" sudo apt-get update -q - sudo apt-get install -y -q ninja-build ccache python3-pytest mosquitto + sudo apt-get install -y -q ninja-build ccache clang python3-pytest mosquitto - uses: actions/cache@v4 with: @@ -329,6 +442,7 @@ jobs: python3 tools/ci_build.py web debug - name: Release + if: github.ref == 'refs/heads/main' run: | source ~/emsdk/emsdk_env.sh python3 tools/ci_build.py web release @@ -339,14 +453,20 @@ jobs: node --test "port/web/tests/*.test.js" # (the dedicated server's admin page, port/assets/server_ui, against tools/server_sim.py) node --test tools/server_ui_tests/ - python3 -m pytest -q tools/test_web_build.py + python3 -m pytest -q tools/test_web_build.py tools/test_web_map_memory.py tools/test_mcc_web_storage.py - name: Test in Chromium and Firefox + env: + WEB_BUILD: ${{ github.ref == 'refs/heads/main' && 'dist/halo-web-release' || 'dist/halo-web-debug' }} run: | + source ~/emsdk/emsdk_env.sh npm install --no-save --prefix "$RUNNER_TEMP/playwright" playwright@1.58 "$RUNNER_TEMP/playwright/node_modules/.bin/playwright" install --with-deps chromium firefox - NODE_PATH="$RUNNER_TEMP/playwright/node_modules" node port/web/tests/smoke.mjs dist/halo-web-release - NODE_PATH="$RUNNER_TEMP/playwright/node_modules" node port/web/tests/rooms.mjs dist/halo-web-release + NODE_PATH="$RUNNER_TEMP/playwright/node_modules" node port/web/tests/map_memory.mjs chromium firefox + NODE_PATH="$RUNNER_TEMP/playwright/node_modules" node port/web/tests/map_import.mjs chromium firefox + NODE_PATH="$RUNNER_TEMP/playwright/node_modules" node port/web/tests/mcc_storage.mjs chromium firefox + NODE_PATH="$RUNNER_TEMP/playwright/node_modules" node port/web/tests/smoke.mjs "$WEB_BUILD" + NODE_PATH="$RUNNER_TEMP/playwright/node_modules" node port/web/tests/rooms.mjs "$WEB_BUILD" # (the native builds' WebRTC, port/linux/src/p2p_webrtc.c, with both) NODE_PATH="$RUNNER_TEMP/playwright/node_modules" node port/web/tests/webrtc_native.mjs chromium firefox source ~/emsdk/emsdk_env.sh @@ -363,6 +483,7 @@ jobs: retention-days: 3 - uses: actions/upload-artifact@v4 + if: github.ref == 'refs/heads/main' with: name: halo-web-release path: dist/halo-web-release @@ -406,6 +527,11 @@ jobs: pattern: halo-* path: artifacts + - uses: actions/download-artifact@v4 + with: + name: player-changelog + path: changelog + - name: Package run: | mkdir release @@ -434,18 +560,15 @@ jobs: - name: Publish id: publish env: - MESSAGE: ${{ github.event.head_commit.message }} COMMIT_URL: ${{ github.server_url }}/${{ github.repository }}/commit/${{ github.sha }} RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} run: | tag="build-$GITHUB_RUN_NUMBER" - subject="$(printf '%s' "${MESSAGE:-manual run}" | head -n 1)" - # (the network version, which a dedicated server's server.auto_update - # reads: a new one is started once the game being played is over) network_version="$(sed -n 's/^#define HALO_PORT_NETWORK_VERSION \([0-9]*\).*/\1/p' port/linux/include/halo_port_limits.h)" - printf '%s\n\nCommit: %s\nBuild: %s\nNetwork version: %s\n\nThe release builds are for playing; the debug builds stop at the first failed assertion and log it.\n' \ - "$subject" "$COMMIT_URL" "$RUN_URL" "$network_version" > notes.md - gh release create "$tag" release/* --target "$GITHUB_SHA" --latest \ + cp changelog/notes.md notes.md + printf '\nCommit: %s\nBuild: %s\nNetwork version: %s\n\nThe release builds are for playing; the debug builds stop at the first failed assertion and log it.\n' \ + "$COMMIT_URL" "$RUN_URL" "$network_version" >> notes.md + gh release create "$tag" release/* changelog/changelog.json --target "$GITHUB_SHA" --latest \ --title "Build $GITHUB_RUN_NUMBER (${GITHUB_SHA:0:7})" --notes-file notes.md echo "tag=$tag" >> "$GITHUB_OUTPUT" @@ -487,86 +610,12 @@ jobs: gh release delete "$tag" --cleanup-tag --yes done - pages: - # The release's web build to GitHub Pages, which serves it at - # https://halocombatevolved.com/ (port/web/README.md, "Hosting"). Only - # main, only once every platform built and the release is out (the site - # and the release are one build), and a deployment is never cancelled - # halfway. The repository's Pages source must be GitHub Actions. - needs: [release] - if: ${{ github.ref == 'refs/heads/main' }} - runs-on: ubuntu-24.04 - timeout-minutes: 10 - permissions: - contents: write - pages: write - id-token: write - concurrency: - group: pages - cancel-in-progress: false - environment: - name: github-pages - url: ${{ steps.deploy.outputs.page_url }} - steps: - - uses: actions/download-artifact@v4 - with: - name: halo-web-release - path: site - - # The game's wasm, most of a build, from jsDelivr rather than GitHub - # Pages, which serves 100 GB a month: the wasm alone in a commit of the - # web-wasm branch (pushed over the last, so the repository keeps one), - # which jsDelivr serves by its hash (with CORS; GitHub's release - # downloads have none, so a page cannot fetch them), and version.json - # names that copy and its SHA-256. The site's service worker takes the - # wasm from there, checked, and from the site only when it cannot - # (port/web/site/sw.js). A failure here leaves the site serving it. - - name: The wasm on jsDelivr - continue-on-error: true - env: - GH_TOKEN: ${{ github.token }} - run: | - sha256="$(sha256sum site/halo.wasm | cut -d' ' -f1)" - mkdir wasm - cp site/halo.wasm wasm/ - cd wasm - git init -q -b web-wasm - git -c user.name="github-actions[bot]" -c user.email="41898282+github-actions[bot]@users.noreply.github.com" \ - add halo.wasm - git -c user.name="github-actions[bot]" -c user.email="41898282+github-actions[bot]@users.noreply.github.com" \ - commit -q -m "The web build's wasm (build $GITHUB_RUN_NUMBER, $GITHUB_SHA)" - git push -q --force "https://x-access-token:${GH_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" HEAD:refs/heads/web-wasm - url="https://cdn.jsdelivr.net/gh/${GITHUB_REPOSITORY}@$(git rev-parse HEAD)/halo.wasm" - # (jsDelivr fetches it now, and it must be the same file: it serves - # files of at most 20 MB from GitHub) - curl -fsSL --retry 6 --retry-delay 10 --retry-all-errors -o served.wasm "$url" - echo "$sha256 served.wasm" | sha256sum -c - - cd .. - python3 - "$url" "$sha256" <<'EOF' - import json, sys - with open("site/version.json") as file: - stamp = json.load(file) - stamp["wasm"] = {"url": sys.argv[1], "sha256": sys.argv[2]} - with open("site/version.json", "w") as file: - json.dump(stamp, file, indent=1) - EOF - echo "the wasm from $url" - - - uses: actions/configure-pages@v5 - - - uses: actions/upload-pages-artifact@v3 - with: - path: site - - - id: deploy - uses: actions/deploy-pages@v4 - notify: # A Discord embed for the run, to the DISCORD_WEBHOOK secret (nothing # without it): green when every platform built, red when one did not, # with each platform's result, this run's release (main only), and links - # to the latest release's builds and the site. - needs: [linux, android, windows, web, release, pages] + # to the latest release's builds. + needs: [linux, android, windows, web, release] if: ${{ !cancelled() }} runs-on: ubuntu-24.04 timeout-minutes: 5 @@ -578,8 +627,6 @@ jobs: ANDROID: ${{ needs.android.result }} WINDOWS: ${{ needs.windows.result }} WEB: ${{ needs.web.result }} - PAGES: ${{ needs.pages.result }} - SITE_URL: https://halocombatevolved.com/ RELEASE_TAG: ${{ needs.release.outputs.tag }} SERVER: ${{ github.server_url }} REPOSITORY: ${{ github.repository }} @@ -608,12 +655,9 @@ jobs: title="Build failed"; color=15548997 fi latest="$SERVER/$REPOSITORY/releases/latest" - downloads="[Linux]($latest/download/halo-linux-release.zip) · [Windows]($latest/download/halo-windows-release.zip) · [Android]($latest/download/halo-android-release.zip) · [Web]($SITE_URL) ([all builds]($latest))" + downloads="[Linux]($latest/download/halo-linux-release.zip) · [Windows]($latest/download/halo-windows-release.zip) · [Android]($latest/download/halo-android-release.zip) · [Web]($latest/download/halo-web-release.zip) ([all builds]($latest))" if [ -n "$RELEASE_TAG" ]; then release="[$RELEASE_TAG]($SERVER/$REPOSITORY/releases/tag/$RELEASE_TAG)" - if [ "$PAGES" = success ]; then - release="$release, on [the site]($SITE_URL)" - fi else release="None (only a successful build of main makes one)" fi diff --git a/.github/workflows/mcc.yml b/.github/workflows/mcc.yml new file mode 100644 index 0000000000..4e4b3b83ca --- /dev/null +++ b/.github/workflows/mcc.yml @@ -0,0 +1,218 @@ +name: MCC map validation + +# Asset-free checks only. Real map files remain outside the repository and +# require explicit MCC_TEST_MAP/HALO_CUSTOM_EDITION_MAPS locally. +on: + push: + paths: + - "port/linux/game/**" + - "port/linux/src/**" + - "port/linux/include/**" + - "port/include/xdk/**" + - "port/windows/src/win32_steam_workshop.c" + - "port/windows/src/win32_posix.c" + - "port/windows/include/posix/sys/mman.h" + - "port/tools/**" + - "port/third_party/bcdec/**" + - "source/**" + - "tools/test_mcc_*.py" + - "tools/test_checkpoint_epoch.py" + - "tools/test_join_protocol.py" + - "tools/test_windows_mcc_startup.py" + - "tools/test_hud_ammo_thresholds.py" + - "tools/hud_assets.py" + - "tools/linux_sysroot.py" + - "tools/windows_build.py" + - "port/assets/hud/**" + - "tools/tests/mcc_share_*.c" + - "tools/test_steam_workshop.py" + - "tools/test_frontend_*.py" + - "tools/frontend_*.py" + - "tools/mcc_xbox_menu.py" + - "tools/requirements-frontend.txt" + - "tools/port_settings.py" + - "port/assets/menus/**" + - "tools/tests/MccPackageImporterTest.java" + - "port/android/app/src/main/java/com/halo/decomp/Mcc*.java" + - "tools/mcc_native_smoke.py" + - "tools/test_cache_file_formats.py" + - "tools/harness/**" + - ".github/workflows/mcc.yml" + - ".github/workflows/build.yml" + pull_request: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: mcc-validation-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + reader-and-validator: + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + - name: Install native test dependencies + run: | + sudo apt-get update + sudo apt-get install -y clang lld gcc-multilib python3-pytest python3-numpy python3-pil python3-yaml + python3 -m pip install --only-binary=:all: --target "$RUNNER_TEMP/frontend-python" -r tools/requirements-frontend.txt + echo "PYTHONPATH=$RUNNER_TEMP/frontend-python" >> "$GITHUB_ENV" + - name: Check MCC parsing, validation, codecs and existing CE parsing + run: >- + python3 -m pytest -q -rP + tools/test_mcc_ci.py + tools/test_mcc_avoidance.py + tools/test_mcc_cameras.py + tools/test_mcc_chicago.py + tools/test_mcc_damage_tags.py + tools/test_mcc_environment_shader.py + tools/test_mcc_hud_layout.py + tools/test_mcc_hud_mask.py + tools/test_mcc_hud_view.py + tools/test_mcc_hud_normalization.py + tools/test_mcc_movement.py + tools/test_mcc_particles.py + tools/test_mcc_seats.py + tools/test_mcc_cache_format.py + tools/test_mcc_tag_validation.py + tools/test_mcc_media.py + tools/test_mcc_resources.py + tools/test_mcc_validation.py + tools/test_mcc_share_rules.py + tools/test_mcc_share.py + tools/test_mcc_share_stage.py + tools/test_mcc_share_metadata.py + tools/test_mcc_share_storage.py + tools/test_mcc_share_menu.py + tools/test_mcc_share_game.py + tools/test_mcc_identity.py + tools/test_mcc_admission.py + tools/test_mcc_workshop.py + tools/test_steam_workshop.py + tools/test_mcc_android_importer.py + tools/test_mcc_metadata_importer.py + tools/test_frontend_menu.py + tools/test_frontend_multiplayer.py + tools/test_frontend_navigation.py + tools/test_frontend_presentation.py + tools/test_mcc_metadata_importer.py + tools/test_mcc_loading.py + tools/test_mcc_load_network.py tools/test_mcc_loading_progress.py + tools/test_mcc_precache.py + tools/test_mcc_protocol.py + tools/test_checkpoint_epoch.py + tools/test_join_protocol.py + tools/test_mcc_bitmap_flags.py + tools/test_mcc_shader_channels.py + tools/test_mcc_hud.py + tools/test_mcc_vorbis.py + tools/test_mcc_texture_bridge.py + tools/test_mcc_maps.py + tools/test_mcc_previews.py + tools/test_mcc_preview_menu.py + tools/test_mcc_xbox_menu.py + tools/test_mcc_progress.py + tools/test_mcc_menu.py + tools/test_mcc_pause.py + tools/test_mcc_pause_runtime.py + tools/test_mcc_ui.py + tools/test_mcc_ui_teams.py + tools/test_mcc_ui_network.py + tools/test_mcc_lifecycle.py + tools/test_mcc_weapon_camera.py tools/test_mcc_projectiles.py + tools/test_mcc_native_smoke.py + tools/test_mcc_recordings.py + tools/test_mcc_saved_games.py + tools/test_mcc_network.py + tools/test_mcc_checkpoint.py + tools/test_mcc_object_names.py + tools/test_mcc_effects_gain.py + tools/test_mcc_sprites.py + tools/test_mcc_change_colors.py + tools/test_mcc_grenades.py + tools/test_cache_file_formats.py + + - name: Check MCC preview reader with address and undefined-behavior sanitizers + env: + MCC_PREVIEW_SANITIZE: "1" + CC: clang + run: python3 -m pytest -q tools/test_mcc_previews.py + + - name: Check MCC sharing metadata and receipts with address and undefined-behavior sanitizers + env: + MCC_SHARE_METADATA_SANITIZE: "1" + MCC_SHARE_STORAGE_SANITIZE: "1" + CC: clang + run: python3 -m pytest -q tools/test_mcc_share_metadata.py tools/test_mcc_share_storage.py + + hud-meter-render: + runs-on: ubuntu-24.04 + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + - name: Install hidden software-GL test dependencies + run: | + sudo apt-get update + sudo apt-get install -y clang lld cmake ninja-build pkg-config xvfb xauth \ + libgl1-mesa-dev libgl1-mesa-dri libx11-dev libxext-dev libxcursor-dev \ + libxi-dev libxfixes-dev libxrandr-dev libxss-dev libxtst-dev python3-numpy python3-pil python3-scipy + - name: Build the project's pinned SDL3 for the test host + run: | + python3 - <<'PY' + import io + import os + from pathlib import Path + import tarfile + from tools.linux_sysroot import SDL_URLS, SDL_SHA256, SDL_VERSION, download + stage = Path(os.environ['RUNNER_TEMP']) / 'mcc-sdl-source' + stage.mkdir() + with tarfile.open(fileobj=io.BytesIO(download(SDL_URLS, SDL_SHA256))) as archive: + archive.extractall(stage, filter='data') + with open(os.environ['GITHUB_ENV'], 'a') as output: + output.write(f'MCC_SDL_SOURCE={stage / ("SDL3-" + SDL_VERSION)}\n') + PY + - name: Install SDL3 + run: | + cmake -S "$MCC_SDL_SOURCE" -B "$RUNNER_TEMP/mcc-sdl-build" -G Ninja \ + -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX="$RUNNER_TEMP/mcc-sdl" \ + -DCMAKE_INSTALL_LIBDIR=lib -DSDL_SHARED=ON -DSDL_STATIC=OFF \ + -DSDL_TEST_LIBRARY=OFF -DSDL_TESTS=OFF -DSDL_WAYLAND=OFF + cmake --build "$RUNNER_TEMP/mcc-sdl-build" --parallel 2 + cmake --install "$RUNNER_TEMP/mcc-sdl-build" + - name: Check MCC coverage and fill thresholds through the production shader + env: + SDL_VIDEO_DRIVER: x11 + LIBGL_ALWAYS_SOFTWARE: "1" + run: | + export PKG_CONFIG_PATH="$RUNNER_TEMP/mcc-sdl/lib/pkgconfig" + export LD_LIBRARY_PATH="$RUNNER_TEMP/mcc-sdl/lib" + # This is a direct runner: pytest would collect no render checks. + xvfb-run -a python3 tools/test_mcc_hud_meter_render.py + + windows-adapters: + runs-on: windows-2025 + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + - name: Install Python test dependencies + run: | + python -m pip install pytest numpy pyyaml --only-binary=:all: -r tools/requirements-frontend.txt + - name: Check native x86 MCC adapters and legacy isolation + shell: cmd + run: | + for /f "usebackq tokens=*" %%i in (`"%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath`) do set "MCC_VS_INSTALL=%%i" + if not defined MCC_VS_INSTALL exit /b 1 + call "%MCC_VS_INSTALL%\Common7\Tools\VsDevCmd.bat" -host_arch=x64 -arch=x86 + if errorlevel 1 exit /b 1 + clang --version + python -m pytest -q tools/test_mcc_ci.py tools/test_mcc_avoidance.py tools/test_mcc_cameras.py tools/test_mcc_chicago.py tools/test_mcc_damage_tags.py tools/test_mcc_environment_shader.py tools/test_mcc_hud_layout.py tools/test_mcc_hud_normalization.py tools/test_mcc_movement.py tools/test_mcc_particles.py tools/test_mcc_seats.py tools/test_mcc_memory.py tools/test_windows_mcc_startup.py + if errorlevel 1 exit /b 1 + python -m pytest -q tools/test_mcc_previews.py tools/test_mcc_preview_menu.py tools/test_mcc_xbox_menu.py tools/test_mcc_progress.py + if errorlevel 1 exit /b 1 + python -m pytest -q tools/test_mcc_recordings.py tools/test_mcc_native_smoke.py tools/test_mcc_cache_format.py tools/test_mcc_tag_validation.py tools/test_mcc_media.py tools/test_mcc_resources.py tools/test_mcc_validation.py tools/test_mcc_share_rules.py tools/test_mcc_share.py tools/test_mcc_share_stage.py tools/test_mcc_share_metadata.py tools/test_mcc_share_storage.py tools/test_mcc_share_menu.py tools/test_mcc_share_game.py tools/test_mcc_identity.py tools/test_mcc_admission.py tools/test_mcc_workshop.py tools/test_steam_workshop.py tools/test_mcc_loading.py tools/test_mcc_load_network.py tools/test_mcc_loading_progress.py tools/test_mcc_precache.py tools/test_mcc_protocol.py tools/test_checkpoint_epoch.py tools/test_join_protocol.py tools/test_mcc_bitmap_flags.py tools/test_mcc_shader_channels.py tools/test_mcc_hud.py tools/test_mcc_hud_mask.py tools/test_mcc_hud_view.py tools/test_mcc_vorbis.py tools/test_mcc_texture_bridge.py tools/test_mcc_geometry.py tools/test_mcc_scripts.py tools/test_mcc_campaign.py tools/test_mcc_parameters.py tools/test_mcc_syntax.py tools/test_mcc_maps.py tools/test_mcc_menu.py tools/test_mcc_pause.py tools/test_mcc_pause_runtime.py tools/test_mcc_ui.py tools/test_mcc_ui_network.py tools/test_mcc_ui_teams.py tools/test_mcc_lifecycle.py tools/test_mcc_weapon_camera.py tools/test_mcc_projectiles.py tools/test_mcc_saved_games.py tools/test_mcc_network.py tools/test_mcc_checkpoint.py tools/test_mcc_object_names.py tools/test_mcc_effects_gain.py tools/test_mcc_sprites.py tools/test_mcc_change_colors.py tools/test_mcc_grenades.py tools/test_cache_file_formats.py + if errorlevel 1 exit /b 1 + python -m pytest -q tools/test_frontend_menu.py tools/test_frontend_multiplayer.py tools/test_frontend_navigation.py tools/test_frontend_presentation.py diff --git a/.gitignore b/.gitignore index e04521b7d5..60270e7d47 100644 --- a/.gitignore +++ b/.gitignore @@ -30,3 +30,6 @@ original/ # CI build outputs (tools/ci_build.py) dist/ + +# User-supplied Halo 1 MCC maps and resources +mcc_maps/ diff --git a/AGENTS.md b/AGENTS.md index 05d48102dc..66e2e80cb1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,6 +10,264 @@ maps, touch controls). The project is published as OpenCE. Start with [README.md](README.md). The other documents are listed at the end. +## GulchCE instructions for every assignment + +Read this file before starting each assignment and explicitly confirm your +understanding of its requirements. Then review the isolation rules below +and explicitly confirm your understanding of them before proceeding. +Read [CODINGSTANDARDS.md](CODINGSTANDARDS.md) for supplementary working and +review guidance. Those standards do not relax the isolation rules. + +### Applying these requirements + +- The common project requirements apply to every assignment, including + building, testing, networking, licensing, source provenance and Git + conventions. +- Before implementation, identify whether the assignment adds a general + feature, implements MCC compatibility, fixes existing behavior, merges + upstream changes or combines these activities. Briefly state which + isolation requirements apply. +- General feature work must follow the general feature isolation rules. + MCC compatibility work must additionally follow the MCC isolation rules; + the general rules do not relax the stricter MCC boundaries. +- For mixed assignments, apply the relevant rules to each affected part. + Classify work by what it changes, not merely by the assignment's title. + A general feature request does not authorize unrelated MCC compatibility + changes or changes to map-family boundaries. +- When shared-engine work can affect multiple map families, inspect and + validate the affected Xbox, Custom Edition and MCC paths. Incidental use + of a shared engine service by MCC does not make all general engine work + MCC-specific, but existing MCC guards, ownership and cleanup must remain + intact. +- These rules provide standing permission for necessary integration that + meets their conditions within an authorized assignment. Explain the + rationale and perform the required validation without requesting separate + approval for routine compliant changes. If a specific change conflicts + with an isolation rule, stop only the affected part, explain the conflict, + and continue independent work that remains within scope. A general + request to complete a feature does not itself waive an isolation rule. + +### General feature isolation + +- Preserve the established Halo 1 Xbox and Custom Edition implementations. + Do not replace, rename, remove, obscure or repurpose their code, scripts, + variables or loading paths to implement a new feature. The narrowly + scoped additive integration described below is allowed. +- Keep feature logic in dedicated feature modules, extending an existing + feature-owned module where appropriate. Use existing engine interfaces + where possible. Minimal registration and wiring in build files, settings, + menus and declarations are allowed when necessary for the authorized + feature and must follow the applicable project rules. This does not + authorize moving feature logic into established engine implementations. + Keep MCC-specific compatibility logic in MCC-owned modules. +- Optional features must preserve established behavior when disabled. + They must default to off or stock behavior unless the user explicitly + authorizes a different default. When enabled, changes must remain limited + to the authorized feature; unrelated behavior and map-family boundaries + must be preserved. Follow the Settings requirements below for features + that depart from the stock game's look or behavior. +- Existing implementations may be analysed for reference. This does not + authorize replacing or repurposing them for new feature compatibility. + Follow the third-party licensing, source-provenance and Xbox SDK rules + in this file and the coding standards. +- Minimal additive shared-engine hooks, declarations or extension points + are allowed only when strictly necessary for authorized functionality + that cannot be implemented through existing interfaces in feature + modules. Keep feature logic in feature-owned modules and shared additions + as small as possible. Guard feature-specific execution and state with + the appropriate activation conditions. +- Handle initialization and cleanup at the feature's relevant lifecycle + boundaries. These may include enabling or disabling the feature, map + loading and unloading, failed loads, session changes and shutdown. + Feature state must not leak into later sessions or unaffected paths. +- For each shared addition, explain why a feature-module-only solution is + insufficient, identify the affected engine paths, and mark changes to + `source/` with `port:` as required below. Verify established behavior + with the feature disabled, the intended behavior with it enabled, and + relevant lifecycle and map-family transitions. +- This permission covers necessary integration, not replacing, renaming + or refactoring established implementations for convenience or code + reduction. Existing hooks are not blanket permission for broader + changes. Refactoring, deduplication, cleanup and line-count targets are + not exceptions. +- If a feature cannot fit within these constraints, explain the specific + conflict and stop that part of the work. Do not proceed unless the user + explicitly changes the applicable constraint. +- Report the actual validation performed and its limits. Scale checks to + the affected behavior without waiving required platform or networking + checks. A successful load or green test suite is not proof of full + compatibility. + +### MCC isolation + +- Preserve the established Halo 1 Xbox and Custom Edition implementations + and functionality. Do not change, rename, remove, obscure or repurpose + their code, scripts, variables or loading paths to implement MCC support. + The narrowly scoped shared-engine additions described below are allowed; + they must preserve the existing Xbox and Custom Edition logic and behavior. +- MCC support must remain independently implemented in dedicated MCC + modules. Xbox maps use `maps`, Custom Edition maps use `custom_maps`, and + MCC maps and their package folders use `mcc_maps`. +- Existing Xbox and Custom Edition code may be analysed for reference; + this does not authorize editing or hijacking it for MCC compatibility. + Do not copy proprietary MCC code or prohibited SDK material. Follow the + third-party licensing and source-provenance rules below and in the + coding standards. +- Minimal additive shared-engine hooks, declarations or extension points + are allowed only when strictly necessary for authorized MCC functionality + that cannot be implemented through existing interfaces in MCC modules. + Keep MCC compatibility logic in MCC-owned modules and shared additions + as small as possible. Guard MCC-specific execution and state so Xbox and + Custom Edition retain their existing paths, behavior and limits. Handle + MCC discovery before loading and cleanup after unloading explicitly. +- For each shared addition, explain why an MCC-module-only solution is + insufficient, identify the affected engine paths, mark source additions + with `port:` as required below, and verify legacy behavior and map-family + transitions. This permission covers necessary integration, not replacing, + renaming or refactoring established Xbox or Custom Edition implementations + for convenience or code reduction. Existing hooks are not blanket + permission for broader changes. See `CODINGSTANDARDS.md` for the MCC + boundary inventory. If a feature cannot fit within these constraints, + explain the specific conflict and stop that part of the work. Do not + proceed unless the user explicitly changes the applicable constraint. +- The general permission below for minimal changes to `source/` does not + override these stricter rules for MCC work. Refactoring, deduplication, + cleanup and line-count targets are not exceptions. +- Explicitly requested upstream merges and general engine fixes have their + own scope, as described below. They do not authorize unrelated changes + to Xbox or Custom Edition support or relax the rules for implementing + MCC compatibility. +- Check preservation of Xbox and Custom Edition behavior as well as MCC + compatibility. Report the actual validation performed and its limits; + a successful load or green test suite is not proof of full compatibility. + +### Existing behavior fixes and upstream merges + +- Authorized fixes to existing behavior may modify the responsible + implementation directly; they do not require a separate feature module + merely because code changes are needed. Keep the fix focused, explain + the intended behavior change, and preserve unrelated functionality. + Retain the required `port:` markers for changes to `source/`. +- MCC compatibility fixes remain subject to MCC isolation. Calling work + a bug fix or general engine fix does not authorize repurposing Xbox or + Custom Edition implementations for MCC. +- Base the distinction between a general engine defect and an MCC + compatibility requirement on evidence about the existing engine contract, + accepted inputs and intended behavior. An MCC map exposing a failure does + not by itself establish either classification. Document why a proposed + shared fix corrects existing engine behavior rather than adapting it to + MCC-specific data or semantics. If the distinction remains unresolved and + affects whether a change is permitted, explain the uncertainty and stop + that part of the work. +- For explicitly requested upstream merges, retain authoritative OpenCE + changes and preserve MCC and other feature integration. Do not use the + merge to introduce unrelated changes to Xbox or Custom Edition support. + Identify and validate behavior affected by conflict resolution. +- Apply the required platform, networking and regression checks to the + affected paths. Report what was verified and any remaining limits. + +### Systemic fixes and content-specific exceptions + +- Fix the underlying engine or format behavior for the affected class of + inputs. A valid new map using the same semantics should benefit without + requiring registration by name, checksum, tag path or asset fingerprint. + Do not use content identity as a substitute for diagnosing a defect. +- Establish whether the problem is an engine defect, a map-family format + difference, unsupported or malformed content, or a dependency on historical + behavior. State the intended behavior and supporting evidence before + choosing the implementation boundary. +- Systemic does not mean globally identical. Correct general engine defects + in the responsible implementation; implement format-specific semantics + in the corresponding compatibility modules. Preserve the established + Xbox, Custom Edition and MCC boundaries, loading paths and lifecycle. + These requirements do not relax the isolation rules. +- Prefer validated format information, authored flags, tag structure and + usage context when selecting behavior. Do not replace a map whitelist + with an unexplained texture-name check, dimensional threshold or pixel + heuristic. A selector must have a demonstrated connection to the required + semantics and checks against false matches. +- A content-specific compatibility exception is permitted only when evidence + explains why the general engine or format rules cannot safely determine + the required behavior. Keep it narrowly scoped in the owning compatibility + module. Record the affected content, rationale, evidence, activation and + cleanup, regression coverage, and what would permit its removal or why it + remains necessary. Convenience or one successful map test is insufficient. +- Existing exception tables are compatibility evidence to investigate, not + authority for adding more exceptions or removing them wholesale. Replace + an exception only after verifying its intended behavior through the new + implementation and checking relevant unaffected cases. Preserve provenance + and meaningful regression coverage. +- Correct interpretation of supported content must not require a player to + enable an accessibility or cosmetic option. Keep those optional departures + separate, with stock defaults under the Settings requirements. +- Apply this policy within the authorized assignment. It does not authorize + a repository-wide rewrite, changes to original map files, expanded format + support or unrelated removal of existing compatibility behavior. Follow + CODINGSTANDARDS.md for investigation, regression checks and reporting. + +### Implementation reviews and completion + +- Review design and maintainability before substantial implementation and + during each meaningful implementation phase. Check module boundaries, + interfaces, state ownership, lifecycle, testability and complexity before + more code depends on them. Resolve identified structural problems within + scope as they arise; do not defer known necessary refactoring to the end. +- At the end of each agreed feature, change, fix or addition, perform a + final pass over the combined implementation before running the final + required regression checks. Include all code, integration, documentation + and tests produced or modified for the assignment, across its commits + and phases. Review the resulting state, consulting history where needed, + rather than auditing every intermediate version or only the latest diff. +- Complete necessary simplification, refactoring and justified optimisation + within the authorised scope. Remove demonstrably redundant code, obsolete + stubs, abandoned approaches, temporary scaffolding and stale documentation + or tests. Preserve meaningful regression coverage, required platform stubs, + diagnostics, bounds checks, compatibility behavior and supporting evidence. + Review is mandatory; changes without a demonstrated benefit are not. +- Follow the detailed review criteria in [CODINGSTANDARDS.md](CODINGSTANDARDS.md). + These reviews do not relax isolation, provenance, networking or platform + requirements, authorize unrelated refactoring, or permit combining Xbox, + Custom Edition and MCC implementations across their established boundaries. +- Run final required checks on the resulting implementation. If validation + leads to further changes, review those changes and rerun affected checks + and required integration checks before completion. Continue testing during + development; the final pass is not a reason to delay earlier checks. +- Briefly report the review outcome, improvements made or why none were + needed, actual validation and unresolved limitations. Scale review effort + to the change; documentation-only work needs document checks, not game + regression runs. + +### Project preferences + +- Use descriptive branch names without a `codex/` prefix. +- Do not write or update PR descriptions unless the user explicitly asks; + the user handles them. This does not remove the requirement to record + rationale and validation in commit messages. +- Run at most two game instances concurrently during automated testing. + A two-instance co-op test within an authorized task needs no additional + permission. Use isolated data/save folders and hidden windows or a + virtual display; stop only the processes you started. +- Keep temporary test maps bounded and clean up only your own verified + fixtures after testing. Preserve the user's original maps, saves and + useful diagnostic logs. +- Clean up after each test run and before finishing an assignment, including + failed runs once useful diagnostics have been retained. Remove generated + game caches (such as `saves/z/cacheNNN.map`), temporary test builds and + binaries, duplicate packages, disposable fixtures and any other outputs + no longer strictly necessary for ongoing work or delivery. Do not leave + repeated test sessions accumulating gigabytes of disposable data. +- Preserve useful logs and diagnostic evidence, original maps and all saves; + `savegame.bin` is a save, not a disposable map cache. Large inactive test + saves or captures may be archived losslessly, with original paths recorded + and archive contents verified before removing loose copies. Keep active + saves usable in place, along with required builds and installed toolchains. +- Limit routine cleanup to verified outputs of your assignment. Check resolved + paths before deletion, do not follow junctions or symlinks into original + data, and preserve source, Git worktrees and other ongoing work. A folder + being ignored by Git or named `build` does not make all its contents + disposable. Check the size of retained test outputs and briefly report + cleanup and any large artifacts that still need to remain. + ## Layout | Path | Contents | @@ -124,6 +382,34 @@ Running the game without a person at it: ## Rules of the project +### Documentation for code readers + +- The [reader's guide](docs/reading/README.md) connects visible behaviour + to the implementation. Update an affected guide in the same change when + its described behaviour, named functions or reading route changes. +- For a substantial feature whose flow or constraints need explanation, + add or extend a focused walkthrough under `docs/reading/`. Scale this to + the change; small fixes do not require a new walkthrough. Explain the + visible behaviour, prerequisites, reading order, one concrete example, + important state and lifecycle rules, and relevant checks and limits. +- Link to source files with relative paths and name the functions to read. + Keep copied code short and avoid fragile line-number references. Link + to existing technical references rather than duplicating their details. +- Explain unfamiliar terms at first use; add reusable definitions to the + [glossary](docs/reading/glossary.md). Distinguish inherited engine + behaviour, OpenCE additions and GulchCE-specific choices where relevant. +- Separate facts established by the code, documented rationale, inferences + and unresolved questions. Distinguish source inspection, automated tests + and runtime observations; suggested checks are not completed validation. +- Keep comments beside non-obvious constraints, ownership, ordering and + workarounds. Follow the existing comment style and `port:` rules for + `source/`; use the guide for extended teaching rather than narrating + every statement. Documentation work does not authorize implementation + changes or relax the isolation rules. +- Before completing documentation changes, review them against the current + code and check local links and named symbols. Documentation-only changes + require document checks, not artificial tests or game builds. + ### The game's sources - Change `source/` as little as possible, and mark each change from the @@ -271,6 +557,13 @@ The decompilation's upstream, punpckhdq/halo, is AGPL 3.0 from 17 October - Commit subjects are plain sentences saying what changed; the body says why and what was checked. +- For player-visible changes, add a `Player-Note: Short plain-language sentence.` + line in the commit body (at most 100 printable ASCII characters after the + prefix). An optional `[CATEGORY]` after the prefix assigns a menu section; + it is excluded from the note's 100-character limit. See `docs/changelog.md` + for category syntax. Multiple lines are allowed; keep them focused on what + players notice. Internal-only changes need no note. These lines supply the menu + and release changelogs when testing reaches main; see `docs/changelog.md`. - A pull request is merged with a merge commit (`Merge pull request #N from /`), and follow-up changes go in separate commits whose subject ends with `(#N)`. @@ -282,6 +575,8 @@ The decompilation's upstream, punpckhdq/halo, is AGPL 3.0 from 17 October | Document | About | | --- | --- | | [README.md](README.md) | Downloads, game data, building, build options, profiling builds | +| [docs/reading/README.md](docs/reading/README.md) | GulchCE subsystem walkthroughs, branch-specific rendering notes, testing guidance, glossary and FOV example | +| [CODINGSTANDARDS.md](CODINGSTANDARDS.md) | Supplementary coding, MCC boundaries, evidence and review standards | | [port/linux/README.md](port/linux/README.md) | The Linux build, controls, menus, every setting, updates, frame rate, field of view, system link, internet play, voice chat, the server browser, map sharing, security, map checks, how the port operates, the game source changes | | [port/linux/NETCODE.md](port/linux/NETCODE.md) | The distributed netcode, network versions, joining a game in progress, map sharing, transport, testing | | [port/windows/README.md](port/windows/README.md) | The Windows build, its headers, inline functions, crash reports | diff --git a/AUTHORS.md b/AUTHORS.md index b087b0773e..3ac63810d7 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -5,7 +5,8 @@ - **The game's icon** (the Android app's launcher icon, `halo.exe`'s icon and the desktop windows' icon): by ORION (`port/assets/icon`). - **The controller's A, B, X and Y buttons** (the menus' button icons and - the HUD messages'): redraws by saulob (`port/assets/buttons`). + the HUD messages'): redraws by saulob (`port/assets/buttons`). The MCC + black/white button variants reuse that oval artwork with neutral gradients. - **The high-res HUD** (its meters, icons, scopes and messages, and the weapons' reticles): redraws by MrBruh (`port/assets/hud`), based on reference photos by Aerocatia. The corrected rocket/sniper reticles and diff --git a/CODINGSTANDARDS.md b/CODINGSTANDARDS.md new file mode 100644 index 0000000000..1d88d749f8 --- /dev/null +++ b/CODINGSTANDARDS.md @@ -0,0 +1,306 @@ +# GulchCE coding standards + +These standards supplement [AGENTS.md](AGENTS.md). Read that file first, +then confirm its requirements and the applicable general feature and MCC +isolation rules in the order it specifies. These standards do not authorize +changes prohibited by those rules. They guide future work; they are not an +instruction to reformat or rewrite existing code across the repository. + +## Scope and implementation boundaries + +Before changing behavior, inspect the actual code and relevant map data or +runtime state. Check data layouts, ownership, bounds, lifetime, failure +paths and host/client responsibilities, rather than only signatures. +Separate observed facts from assumptions and record unresolved questions. + +The following inventory identifies existing MCC modules at shared engine +boundaries. It is a navigation aid, not blanket permission to change shared +code. Necessary additive integration is permitted under the narrow rules +in `AGENTS.md`. Inspect the actual callers for the task and update this +inventory when an authorized change makes it inaccurate. + +| Boundary | Existing MCC-owned modules in `port/linux/game/` | +| --- | --- | +| Map selection, loading, packages and resources | `mcc_main`, `mcc_maps`, `mcc_cache`, `mcc_loading`, `mcc_errors`, `mcc_precache`, `mcc_validation.inl`, `mcc_identity`, `mcc_sha256`, `mcc_cache_format`, `mcc_package`, `mcc_resources`, `mcc_tags`, `mcc_tag_validate` | +| Script interpretation, parameters and object names | `mcc_scripts`, `mcc_syntax`, `mcc_script_parameters`, `mcc_script_runtime.inl`, `mcc_script_threads.inl`, `mcc_object_names`, `mcc_game_speed` | +| Checkpoints and campaign state | `mcc_checkpoint`, `mcc_campaign`, `mcc_script_effects`, `mcc_progress` | +| Explicit campaign packages and progression | `mcc_maps`, `mcc_main`, with `port/linux/src/mcc_manifest.c`; Android imports in `MccPackageImporter` and `MccImportActivity` | +| Weapon-authored camera selection | `mcc_camera` | +| Camera-relative player projectile rays | `mcc_projectiles` | +| Networking and named-object synchronization | `mcc_network`, `mcc_object_names_network`, `mcc_admission`, `mcc_admission_game`, `mcc_load_network`, `mcc_load_network_game`, `mcc_workshop`, `mcc_share`, `mcc_share_package`, `mcc_share_session`, `mcc_share_stage`, `mcc_share_storage`, `mcc_share_list`, `mcc_share_rules`; metadata planning/validation in `port/linux/src/mcc_share_metadata.c`, native contained publication in `posix_mcc_share.c` | +| Player inventory, objects, movement penalties, damage impulses, seats and recordings | `mcc_player`, `mcc_first_person.inl`, `mcc_grenades`, `mcc_objects`, `mcc_movement`, `mcc_damage`, `mcc_seats`, `mcc_recordings` | +| Rendering, HUD and audio conversion | `mcc_geometry`, `mcc_bitmaps`, `mcc_texture_cache`, `mcc_environment_shader` (with `port/linux/src/mcc_environment_shader_gl.c`), `mcc_chicago.inl`, `mcc_hud`, `mcc_hud_draw`, `mcc_sprites`, `mcc_particles`, `mcc_audio`, `mcc_vorbis` | +| Menus and pause UI | `mcc_ui`, `mcc_ui_teams`, `mcc_pause`, `mcc_pause_runtime`, `mcc_menu_preview`, `mcc_menu_text`, `mcc_xbox_menu.inl` | + +Preserve established activation guards, legacy fallbacks and cleanup on +map unload or failed load. Do not route Xbox or Custom Edition maps through +MCC adapters. Reusing a common engine service through its existing interface +does not authorize repurposing its implementation for MCC. Shared-code +refactoring and deduplication remain subject to the isolation rules. + +When existing interfaces cannot support authorized MCC functionality, a +minimal additive shared-engine hook, declaration or extension point is +allowed. Document why the addition is strictly necessary and why it cannot +live entirely in an MCC module. Keep compatibility logic in MCC-owned code; +preserve existing Xbox/Custom Edition branches, state, limits and behavior. +Guard MCC-specific work using the appropriate map or request identity, +including discovery, failed loads and unload cleanup rather than only the +active-map state. Verify both MCC operation and the unaffected legacy paths, +including transitions between them. This is standing permission for additions +meeting these conditions within an authorized task, not permission to replace +or refactor legacy implementations. Networking/versioning and platform-check +requirements still apply. + +## Evidence and unsupported data + +- Record the public format reference, inspected map structure or observed + behavior supporting a compatibility decision. Put durable evidence in + the relevant MCC documentation or a concise comment where necessary. + Do not present an inferred layout or behavior as confirmed. +- Independently implement compatibility logic. Do not copy proprietary + MCC source or prohibited SDK material. Preserve the licensing, + attribution and provenance requirements for permitted dependencies in + `AGENTS.md`; vendored code remains unchanged. +- Treat map files and network input as untrusted. Validate lengths, + arithmetic, indices and ownership before reading or allocating. +- Refuse unsupported or unsafe data with an actionable diagnostic. Include + the map, tag or script context and the reason where available. Do not + silently discard scripts, substitute resources or change gameplay merely + to make a map load. An intentional compatibility fallback needs a defined + rationale, evidence, diagnostics and verification within authorized scope. + +## Investigating systemic fixes + +Apply AGENTS.md's systemic-fix policy to behavior changes. Scale the +investigation to the defect; keep durable findings in the relevant existing +guide, test or concise code comment. + +### Establish the behavior + +- Describe the observed failure and expected result. Identify the reference: + the existing engine contract, documented format semantics or observed + behavior of a specified reference implementation and configuration. + Distinguish stock behavior from fixes introduced by extensions. +- Trace the relevant input through loading, conversion and runtime use. + Inspect authored values, flags, units, ownership and lifetime. Check for + omitted interpretation, repeated conversion and interactions with existing + exceptions before adding another correction. +- Separate independent causes even when one map exposes them together. + For example, HUD glyph size, digit advance and meter channel ordering + require their own evidence; a correct screenshot does not establish that + all three follow the same rule. +- State why the proposed selector identifies the affected class of inputs. + Map format alone may not identify an author's historical workaround. + Texture resolution alone does not establish intended display size. + If evidence is insufficient, report the uncertainty rather than treating + a plausible heuristic as established semantics. + +### Verify the general rule + +- Prefer a minimal synthetic reproduction exercising the real implementation. + For a defect, demonstrate failure before the fix where feasible. Retain + the reported map as a runtime regression case when available. +- Check identity independence: equivalent relevant content must receive the + same correction under unrelated map names and checksums. Change only + identity fields that are not themselves part of the required semantics, + keeping fixtures valid. +- Include counterexamples that must remain unchanged, boundary and malformed + inputs where relevant, and interactions with existing conversion rules. + Verify observable results rather than only selected flags or table entries. +- For a retained exception, test both the intended match and near misses. + Tests proving that an exception activates do not establish that its + behavior is correct or that a general replacement is impossible. +- Verify relevant load, failed-load, unload and map-family transitions. + Renderer changes require actual visual checks alongside automated coverage. + The platform, networking and regression requirements in AGENTS.md still apply. + +### Make remaining exceptions explainable + +- Keep exception selection and rationale discoverable in the owning module. + Expose the selected behavior and reason through appropriate load or debug + diagnostics without logging repeatedly in draw or simulation loops. +- Record unresolved root-cause work in an existing project document or issue, + including the evidence needed to resolve it. Do not describe an exception + as temporary without recording what remains to be established. +- When replacing an exception, remove obsolete selection logic and update + its tests and documentation in the same change. Preserve behavioral + coverage, attribution and useful evidence. + +## Code and comments + +- Match the surrounding naming, layout and comment density. Follow the + C89, ABI and deterministic-maths requirements in `AGENTS.md`. +- Comments should explain hidden constraints, invariants, workarounds or + important API contracts. Avoid narrating obvious statements, repeating + agent instructions or recording a chronological account of edits. +- Keep enough explanation to prevent a future change from reintroducing a + bug. Comment length follows the reasoning; remove padding, not evidence. +- For new project C comments, use ordinary `/* ... */` comments and the + surrounding plain style, without Doxygen tags or decorative doc blocks. + Follow the local header and `/* ---------- name */` section conventions + when applicable. Other languages retain their own conventions. +- Any authorized change to decompiled `source/`, including a necessary + additive MCC integration under the rules above, must retain the + `port:` markers and declarations required by `AGENTS.md`. Style guidance + never authorizes such a change itself. Do not reformat established Xbox + or Custom Edition code, generated output or vendored dependencies. + +## Working and review method + +- Resolve routine implementation choices within the user's authorized + scope. Ask about missing requirements or consequential tradeoffs that + cannot be resolved from the instructions and evidence; explain why the + answer matters. Do not repeatedly request approval already given. +- For reproducible bugs and new logic, prefer a regression test that fails + before the fix and exercises the real implementation. Documentation-only + edits, investigations and upstream merges do not require artificial + failing tests. Scale verification to the change without waiving required + platform or networking checks. +- Use relevant available skills through the tools the environment actually + provides, reading their instructions when applying them. Do not require + Superpowers, a particular skill tool or a plugin installation by default. +- Mutation tests can establish that a regression test catches the intended + fault. Use them selectively in isolated temporary copies; never leave + intentional faults in a shared working tree or run them concurrently with + another person's build or review of that checkout. +- Communicate concise findings, decisions and remaining uncertainty. Use + lists where helpful, without imposing a checklist on every response. + +## Design, maintainability and final implementation review + +Every agreed feature, change, fix or addition requires review during +implementation and a final pass before the final required regression run. +Apply this to the entire assignment across its commits and phases. Scale +the depth to the change without omitting the review or waiving required +checks; documentation-only changes require document review and consistency +checks rather than artificial tests or game builds. + +### During implementation + +- Before substantial implementation, review the proposed design against + existing interfaces and isolation requirements. Check module ownership, + dependencies, state lifetime, failure handling, activation and cleanup, + platform constraints and how the behavior will be tested. +- Revisit design and maintainability after each meaningful component or + phase, and when new evidence changes an assumption or integration need. + Check whether responsibilities remain clear, interfaces stay small and + complexity is justified. Resolve structural problems before building + further dependent code; do not knowingly accumulate avoidable refactoring + for the final pass. +- Prefer the simplest implementation that satisfies the agreed behavior + and established boundaries. Avoid speculative abstractions and unnecessary + layers. Duplication required by map-family isolation is not redundancy to + remove. Keep tests and documentation aligned as the design develops. +- Continue focused testing throughout implementation. Keep review notes + proportional: record consequential decisions, evidence and unresolved + issues without requiring a separate design document for every small edit. + +### Final pass + +- Review the final combined implementation across all assignment commits + and phases, by component and as an integrated change. Include declarations, + build and settings wiring, documentation, fixtures and regression tests. + Inspect relevant callers and lifecycle paths. Consult history where needed + to understand the resulting state; this does not require auditing every + obsolete intermediate version. Reviewing only the last patch is + insufficient. +- Complete necessary simplification and refactoring within authorised + scope. Remove dead or demonstrably redundant code, abandoned alternatives, + obsolete stubs, temporary scaffolding and stale comments or documentation. + Check references, supported configurations and platform uses before + declaring code unused; retain required platform and interface stubs. +- Review avoidable repeated work, allocations and resource retention. + Justify performance changes with measurements or concrete analysis of + unnecessary work, and measure claimed runtime improvements where feasible. + Do not introduce speculative micro-optimisations, obscure code or alter + deterministic behavior merely to claim the implementation is optimised. +- Trim obsolete or genuinely duplicate tests and fixtures only after + confirming that meaningful coverage is preserved. Retain distinct failure, + boundary, lifecycle, platform and map-family cases, even when their setup + looks similar. Never weaken assertions or remove a failing test to obtain + a passing result; resolve the defect or establish that the expectation is + obsolete under the agreed behavior. +- Preserve diagnostics, bounds checks, compatibility behavior, useful + evidence, source provenance and required `port:` markers. Review does not + authorize unrelated cleanup, changes to vendored code or combining Xbox, + Custom Edition and MCC implementations across established boundaries. + If an improvement conflicts with isolation, stop that part and explain + the conflict while continuing compliant work. +- Review is mandatory; refactoring is required only where justified. A + sound implementation may need no changes. Do not pursue line-count targets + or repeated cosmetic rewrites as a substitute for correctness and clarity. + +## Verification and reporting + +After the final pass and its corrections, run the required checks in +`AGENTS.md` for the affected platforms and resulting implementation. +Earlier results do not validate subsequently changed code. If validation +causes more edits, review those edits and rerun affected checks and required +integration checks. Reuse evidence for unchanged paths only where it remains +applicable; all required platform, networking and regression checks still +apply. + +For general features, verify established behavior with the feature disabled +and the intended behavior with it enabled. For relevant MCC changes, cover +representative Xbox and Custom Edition behavior alongside MCC. Shared-engine +changes require checks of the affected map-family paths, even when the +assignment is not primarily about MCC. + +Select checks according to the affected path: + +- Feature activation and state: default settings, enabled and disabled + behavior, supported activation changes, initialization, cleanup and + relevant map or session transitions. +- Loading/resource work: supported and malformed inputs, failure recovery, + package isolation, unload/reload and transitions between map families. +- Script/state work: representative execution, supported limits, + checkpoints, restart and cleanup of feature or MCC state at the relevant + lifecycle boundaries. +- Network work: host/client agreement, joining, synchronization and relevant + co-op/multiplayer paths, plus the required transport checks and protocol + version review. +- Renderer/UI work: real visual output at relevant resolutions and layouts, + alongside automated checks where they provide meaningful coverage. +- Existing behavior fixes: evidence of the defect, verification of the + intended correction and checks of related behavior that must remain + unchanged. Prefer a regression test exercising the real implementation. +- Upstream conflict resolution: identify the behavior affected by each + resolution and verify the resulting upstream and fork integration. + +These are risk-based examples, not a demand to replay every map for every +edit. Record the tested revision, build configuration, relevant feature +settings, maps, modes and outcomes. Clearly distinguish conversion success, +entry into gameplay, tested transitions and full campaign completion. +Report skipped checks, failures, unavailable tools and CI results +accurately. Compilation alone does not establish runtime compatibility, +and passing tests do not prove the absence of regressions. + +Briefly report the review scope and outcome, improvements made or why none +were necessary, and unresolved limitations. Distinguish self-review from +independent review; review requirements do not themselves authorize +delegation or additional agents. + +## Git, upstream contributions and code reduction + +- Follow the branch, commit, PR-description and merge conventions in + `AGENTS.md`. Keep commit messages concise but include the reason for the + change and what was checked. +- For contributions to OpenCE, prepare focused branches against current + upstream main, excluding unrelated fork changes and unnecessary upstream + merge commits. Rebasing an existing published branch requires appropriate + authorization; do not silently rewrite shared history. Revalidate affected + builds after resolving conflicts or changing the base. +- Merging OpenCE updates into GulchCE is a different operation: preserve + upstream history with a merge and review conflicts against MCC support. + PRs themselves retain the merge-commit convention in `AGENTS.md`. +- Line-count targets must not remove bounds checks, diagnostics, required + dependencies or compatibility behavior. Review and measure each reduction; + do not compress code into unreadable lines to meet a target. +- Keep tests and documentation maintained locally even when intentionally + excluded from an upstream contribution. Do not delete them merely to + reduce the contribution's size. The current upstream contribution target + is at most 2,000 changed lines per PR, ideally under 1,000, unless the + maintainers agree otherwise. Keep each phase reviewable and verifiable + on its own; the size target never overrides correctness or isolation. + +Camera-relative MCC projectile rays are owned by `mcc_projectiles`. diff --git a/LICENSES/GPL-3.0-only.txt b/LICENSES/GPL-3.0-only.txt new file mode 100644 index 0000000000..f288702d2f --- /dev/null +++ b/LICENSES/GPL-3.0-only.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md index 5c8b468f34..ee103177a1 100644 --- a/README.md +++ b/README.md @@ -1,29 +1,207 @@ -# OpenCE - Halo: Combat Evolved for Linux, Windows, Android and the web -

- OpenCE + gulchceopencelogo

+

+ A fork of OpenCE focused on bringing experimental features to OpenCE. +

+ +

+ download the latest release · + join the discord · + check out the youtube +
+
+ built for Windows, Linux, Android and the web +

+
+

+This development branch requires matching GulchCE network builds. +

+
+

+Shared checkpoint recovery, boat controls and clock recovery require matching simulation agreements. +

+

- Download - Play in browser - Discord + Halo is a trademark of Microsoft. GulchCE is a fan project, not made or endorsed by Microsoft, Bungie, 343 Industries, or Halo Studios, and does not include any game assets or content.

+
+
+ +## What is GulchCE? +GulchCE is a fork of [OpenCommunityEdition/OpenCE](https://github.com/OpenCommunityEdition/OpenCE) - the Halo: Combat Evolved decompilation project targeting Linux, +Windows, Android and web browsers. + +The decompilation is of the Xbox build 2342. (`cachebeta.exe`, SHA-256 +`4cc87b45f721270392a96f1674ed2b5cd4a7bb4355faeab4531d1cf1884d9520`). + +## How do I download a build? + +Release & debug builds are available in the Releases section of the repository. +The release builds are for playing; the debug builds stop at the first failed assertion and log it. + +Releases include `SHA256SUMS`, the SHA-256 of each packaged build. +`sha256sum -c --ignore-missing SHA256SUMS` checks downloaded files. When +release signing is configured, `SHA256SUMS.sig` carries the Ed25519 signature; +`tools/release_sign.sh verify SHA256SUMS` (OpenSSL 3) checks it against +[deploy/release-key.pub](deploy/release-key.pub). + +### Arch-based Linux Distributions + +The Linux binary release is available on the [AUR](https://aur.archlinux.org/packages/gulchce-bin). + +## Can I play with OpenCE clients? + +This development branch requires matching GulchCE clients on Xbox, Custom +Edition and MCC maps. Shared checkpoint recovery separates delayed messages +from a restored player's earlier object handle. Boat controls also require +matching simulation so hosts and predicting clients use initialized forces. +Clients also recover small clock delays by running the missing simulation ticks. +Existing OpenCE 41 clients cannot join these sessions. + +The shared console fix also changes the saved game allocation layout. Older +cores and checkpoints are refused; start a new map or campaign session with +this build. Original save files are not migrated. See the +[console checkpoint walkthrough](docs/reading/console_checkpoints.md). + +**GulchCE Standard** keeps the optional shoulder camera disabled. **GulchCE +Third Person** uses its own matching camera agreement. Recovery works in both +modes; changing the camera setting does not restore old-client compatibility. + +An upstream contribution is planned. Compatibility with a future OpenCE +release depends on the agreement it adopts and must be validated separately. + +## How do I install MCC maps? + +GulchCE can discover installed **Halo 1 MCC Workshop maps** on Windows and +Linux, or import complete packages on Android. Manual installation remains +available through the separate `mcc_maps` folder, beside `maps` and +`custom_maps` in your game data folder. + +You still need the [Xbox game data](#a-copy-of-halo-combat-evolved-is-required) +to run GulchCE. Obtain any required MCC resources from your own legally owned, +installed copy of Halo: Combat Evolved in Halo: The Master Chief Collection. + +### Windows and Linux: discover your Workshop maps + +1. Subscribe to the Halo 1 maps or campaigns you want in the MCC Steam + Workshop, and let Steam finish downloading them. +2. Open **Settings > Online > Map Sharing > MCC Packages** in the Modern + menu style. In Stock, Classic PC and Xbox styles, use + **Settings > Network Setup > Map Sharing > MCC Packages**. +3. Turn **STEAM DISCOVERY** on. For campaigns such as Ruby Rebalanced, also + turn **CAMPAIGN MISSIONS** on to use the package's mission order and + progression. Both settings are off by default. +4. Reopen the map list. If a newly downloaded package is missing, restart + GulchCE. Install the [shared resources](#shared-mcc-resources) below when + required by the map. + +GulchCE reads the installed Workshop package directly, including its supplied +resources, titles and supported level previews. You do not need to copy its +maps into `mcc_maps` or keep Steam running while playing. + +Steam installations and their library folders are detected automatically where +possible, including registered Windows installations such as `C:\Steam` and +Linux's standard, Flatpak and Snap locations. If yours is not found, set the +`steam` entry under `[paths]` in `config.toml` to your Steam installation or +library folder, for example `steam = 'C:\Steam'`. Leave it empty to use +automatic discovery. + +### Android: import a package without Steam + +1. Copy the **complete Workshop package folder or a ZIP of it** from your + computer to your phone. The package root is + `steamapps/workshop/content/976730/`. Keep `ModInfo.json`, any + campaign/mission JSON files, maps, package resources and the supplied + `assets` folder together. +2. Quit GulchCE, long-press its launcher icon and select **Import MCC maps**. +3. Select **Workshop package**, then **Choose folder** or **Choose ZIP**. + Follow the importer's installation prompts. +4. Import any required shared resources separately using **Singleplayer + shared resources** or **Multiplayer shared resources**. Start the game + and enable **CAMPAIGN MISSIONS** for campaign ordering and progression. + +Steam is not needed on the phone. The importer installs the package into +`mcc_maps` and retains its metadata and supported previews. See the +[Android import guide](port/android/README.md#importing-mcc-packages) for details. + +### Manual installation + +Create a separate folder for each package, such as `mcc_maps/MercuryRising`, +and copy its level `.map` files there. Workshop packages commonly keep these +under `steamapps/workshop/content/976730//halo1/maps`. + +**Keep any supplied `bitmaps.map` and `sounds.map` beside that package's +levels.** These belong to the individual package, not `_shared`. Do not mix +resources from different packages. + +For campaign ordering, titles and previews, also retain `ModInfo.json`, +`CampaignInfo.json` when supplied, and the referenced mission/map metadata +and PNGs. Preserve their metadata and image subfolders; the level `.map` +files go directly in your package folder. Enable **CAMPAIGN MISSIONS** in +MCC Packages to use campaign ordering and progression. Copying only the maps +loses those metadata features. See the +[package layout guide](docs/mcc_maps.md#installation-and-menus). + +### Shared MCC resources + +Some maps rely on MCC's standard resources instead of supplying their own. +Install these sets once in your game data folder, creating the destination +folders as needed. **Steam discovery does not install these shared sets.** + +| File in your MCC installation | Destination in GulchCE | +| --- | --- | +| `halo1/maps/bitmaps.map` | `mcc_maps/_shared/singleplayer/bitmaps.map` | +| `halo1/maps/custom_edition/bitmaps.map` | `mcc_maps/_shared/multiplayer/bitmaps.map` | +| `halo1/maps/custom_edition/sounds.map` | `mcc_maps/_shared/multiplayer/sounds.map` | + +Use the files from **MCC**, including its `custom_edition` subfolder, rather +than a standalone Halo Custom Edition installation. On Android, the shared +resource import modes create these destination folders for you. + +A package's own resources take precedence over the shared sets. Self-contained +maps need neither set. If a required resource is missing or incompatible, +GulchCE refuses to load the map and reports what needs attention. + +### Choose a map and play + +In the browser build, import Xbox base data first, then use **Custom maps** +to add CE files or an MCC package folder to the site's private storage. +See the [browser import guide](port/web/README.md#custom-edition-and-mcc-imports) +for supported metadata, storage limits and recovery behavior. + +- **Modern, Stock and Classic PC:** choose **MCC SINGLEPLAYER** or + **MCC MULTIPLAYER** in the map selector, then open the package folder and + select a level. +- **Xbox style:** with **CAMPAIGN MISSIONS** enabled, choose **MCC CAMPAIGNS** + on the main menu, then your profile, campaign, level and difficulty. For + multiplayer maps, use the **X — MCC Maps** prompt in the multiplayer map + selector. + +Supported package images appear automatically in the level cards; missing or +unsupported images keep the question-mark thumbnail. MCC compatibility is +still experimental: appearing in the menu does not guarantee that every map +or campaign works fully. See [MCC map support](docs/mcc_maps.md) for supported +formats, validation results and remaining limits. + +## About upstream OpenCE **OpenCE** (Open Community Edition) is an open source port of the Halo: Combat Evolved decompilation (Halo CE) based on an early Xbox development build (2342) and forked from -[bnunu/halo-1](https://github.com/bnunu/halo-1). The project aims to enhance the existing game and adds many features, such as 128-player multiplayer, online campaign co-op, mod packs, field-of-view settings, a server browser, peer-to-peer hosting, automatic map downloads, voice chat, support for Custom Edition maps and much more! +[bnunu/halo-1](https://github.com/bnunu/halo-1). -The game runs natively on **Windows, Linux, Android** and in the **web browser** with nothing to install. A macOS port is in progress. Worth noting that it is not an emulator, **the game's own code is compiled for each platform** with a new layer in place of the Xbox's hardware. Runs on OpenGL (Android is on OpenGL ES and WebGL 2 in the browser). Sound, input, gamepads are all handled through SDL3. The game currently draws a frame every refresh of your display with Smooth Motion enabled, while the simulation runs at 30 ticks just like the original Xbox. +The project aims to enhance the existing game and adds many features, such as 128-player multiplayer, online campaign co-op, mod packs, field-of-view settings, a server browser, peer-to-peer hosting, automatic map downloads, voice chat, support for Custom Edition maps and much more! -The game running on Windows -

OpenCE running on Windows (release build)

+The game runs natively on **Windows, Linux, Android** and in the **web browser** with nothing to install. A macOS port is in progress. OpenCE nor GulchCE are emulators - **the game's own code is compiled for each platform** with a new layer in place of the Xbox's hardware. + +The Xbox's native NV2A D3D8 rendering code is translated through OpenGL 4.5 on desktops, OpenGL ES 3 on Android, and WebGL 2 on web browsers. Sound, input, gamepads are all handled through SDL3. The game currently draws a frame every refresh of your display with Smooth Motion enabled, while the simulation runs at 30 ticks just like the original Xbox. ## A copy of Halo: Combat Evolved is required -OpenCE does not include the game data. You **must provide your own Xbox disc image** (`.xiso` or `.iso`) of Halo: Combat Evolved. Every version of the game works. The maps of the European (PAL) version were made for a slower console - the game changes them to play as the North American (NTSC) maps do, so players of the two versions can play together. +GulchCE does not include the game data. You **must provide your own Xbox disc image** (`.xiso` or `.iso`) of Halo: Combat Evolved. Every version of the game works. The maps of the European (PAL) version were made for a slower console - the game changes them to play as the North American (NTSC) maps do, so players of the two versions can play together. -1. Start the game (`halo.exe` on Windows and `halo` on Linux). +1. Start the game (`halo.exe` on Windows and `halo` on Linux). 2. At the first start you will get a pop up message asking for the disc image. Select it in the file picker. On Linux and Windows, a disc image (`.iso` or `.xiso`) next to the executable is used without the file picker. Where no file picker @@ -41,33 +219,18 @@ data folder. Refer to [port/android/README.md](port/android/README.md). On the web, the page copies `maps/` out of the disc image into the browser's storage for the site - nothing is uploaded ([port/web/README.md](port/web/README.md)). -## Download - -GitHub Actions builds the game for each commit. - -Builds for latest release: - -| Platform | Release | Debug | Guide | -| --- | --- | --- | --- | -| Linux | [halo-linux-release.zip](https://github.com/OpenCommunityEdition/OpenCE/releases/latest/download/halo-linux-release.zip) | [halo-linux-debug.zip](https://github.com/OpenCommunityEdition/OpenCE/releases/latest/download/halo-linux-debug.zip) | [Linux](port/linux/README.md) | -| Windows | [halo-windows-release.zip](https://github.com/OpenCommunityEdition/OpenCE/releases/latest/download/halo-windows-release.zip) | [halo-windows-debug.zip](https://github.com/OpenCommunityEdition/OpenCE/releases/latest/download/halo-windows-debug.zip) | [Windows](port/windows/README.md) | -| Android | [halo-android-release.zip](https://github.com/OpenCommunityEdition/OpenCE/releases/latest/download/halo-android-release.zip) | [halo-android-debug.zip](https://github.com/OpenCommunityEdition/OpenCE/releases/latest/download/halo-android-debug.zip) | [Android](port/android/README.md) | -| Web | [halocombatevolved.com](https://halocombatevolved.com/) (or [halo-web-release.zip](https://github.com/OpenCommunityEdition/OpenCE/releases/latest/download/halo-web-release.zip) for your own server) | [halo-web-debug.zip](https://github.com/OpenCommunityEdition/OpenCE/releases/latest/download/halo-web-debug.zip) | [Web](port/web/README.md) | - - -Release build is recommended for regular play. +## Platforms -The debug build stops at the first failed check (assertion) and writes it to the log, so use it when you want to find and report problems. +Each platform has its own instructions: -The game updates itself. At start-up it looks for a newer release, and asks -if you want to install it. Refer to "Updates" in -[port/linux/README.md](port/linux/README.md#updates). The web site offers -each new build when it is out. +| Platform | Instructions | +| --- | --- | +| Linux (32-bit x86 executable, OpenGL 4.5, SDL3) | [port/linux/README.md](port/linux/README.md) | +| Windows (32-bit x86 executable, OpenGL 4.5, SDL3) | [port/windows/README.md](port/windows/README.md) | +| Android (arm64 app, OpenGL ES 3, SDL3) | [port/android/README.md](port/android/README.md) | +| Web (WebAssembly, WebGL 2, SDL3; desktop Chrome, Edge and Firefox) | [port/web/README.md](port/web/README.md) | -Each build of the `main` branch that passes on all four platforms is a new -release, and the web site then plays it. The [Releases](https://github.com/OpenCommunityEdition/OpenCE/releases) -page keeps the last five releases. If the latest build has a problem, get -an older build from that page. +The Linux README also covers the controls, every setting and the multiplayer features. These are almost the same on all platforms. The settings are in `config.toml` next to the game, and many are in the menus too. Each release also has `SHA256SUMS`, the SHA-256 of each of its files, and `SHA256SUMS.sig`, that file's Ed25519 signature by the project's release @@ -75,26 +238,24 @@ key, whose public key is [deploy/release-key.pub](deploy/release-key.pub). `sha256sum -c --ignore-missing SHA256SUMS` checks the downloads, and `tools/release_sign.sh verify SHA256SUMS` (OpenSSL 3) the signature. -The Linux README also covers the controls, every setting and the multiplayer features. These are almost the same on all platforms. The settings are in `config.toml` next to the game, and many are in the menus too. - -The Arch-based distribution release is available on the [AUR](https://aur.archlinux.org/packages/opence-bin). +## Can I play multiplayer? -## Multiplayer +Yes! The game can play system link games on a local network and on the internet: - **Supports up to 128 players** on up to 128 machines and up to 4 players on each device in split screen. - **Every platform plays together:** Windows, Linux, Android and the browser all support cross-play! On a local network, the native builds can play LAN. Browser players can play each other in rooms over WebRTC ([port/web/README.md](port/web/README.md)). - **Peer-to-peer internet hosting:** join through the server browser or an invite link. A host lists a game as public in the server browser, or keeps it private for players with the invite link. With the Discord integration, the host can also send the invite through Discord. -- **Online co-op campaign:** with settings for friendly fire, player collisions and the number of enemies as a multiplier based on per player or static. +- **Online co-op campaign:** with settings for friendly fire, player collisions and the number of enemies as a multiplier based on per player or static. - **New gametypes:** SWAT, Infection, Gun Game and Hardcore (Slayer, CTF, Oddball and King), in Select Gametype's OPENCE bank; Edit Gametypes' OPENCE OPTIONS gives any gametype their rules ([port/linux/README.md](port/linux/README.md), "OpenCE gametypes"). - **Voice Chat:** push to talk (V) or an open microphone (can be changed in the menu's audio settings) - **Map sharing:** a player who does not have the game's Custom Edition map downloads it from the other players. -- **Moderation:** the host can kick and ban players from the scoreboard menu or the `kick` and `ban` console commands. Players can vote to kick. -- **Scrollable Scoreboard:** the mouse wheel or PageUp / PageDown scrolls through list of players in large multiplayer lobbies. +- **Moderation:** the host can kick and ban players from the scoreboard menu or the `kick` and `ban` console commands. Players can vote to kick. +- **Scrollable Scoreboard:** the mouse wheel or PageUp / PageDown scrolls through list of players in large multiplayer lobbies. - **A new netcode:** each machine moves its own player at once, and the host makes the decision for the game. Refer to [port/linux/NETCODE.md](port/linux/NETCODE.md). ## Custom Edition Maps -Halo Custom Edition maps are placed in `custom_maps` folder, not in the `maps` folder itself. It requires `bitmaps.map`, `sounds.map`, and `loc.map` in the `custom_maps` folder, which you must copy over from your existing installed copy of Halo Custom Edition. The maps folder is only for Xbox maps that's extracted from your disc image, not Halo Custom Edition. +Halo Custom Edition maps are placed in `custom_maps` folder, not in the `maps` folder itself. It requires `bitmaps.map`, `sounds.map`, and `loc.map` in the `custom_maps` folder, which you must copy over from your existing installed copy of Halo Custom Edition. The maps folder is only for Xbox maps that's extracted from your disc image, not Halo Custom Edition. Halo PC Gearbox exclusive maps (Ice Fields, Death Island, Danger Canyon, Infinity, Timberland and Gephyrophobia) **are not included by default**. They would need to be copied over from your existing Halo Custom Edition install's `maps` folder into `custom_maps` folder too. @@ -164,7 +325,7 @@ Some maps need MCC’s standard resources. Copy these files once into your game Keep package-supplied resources inside their package folder; they take priority over shared resources. Self-contained maps need no shared files. OpenCE reports missing or incompatible resources when loading. -### MCC map support disclaimer +### MCC map support disclaimer Halo 1 MCC version-13 packages use an independent loader and `mcc_maps` root. The stock menus support package selection, optional campaign missions, previews @@ -175,10 +336,12 @@ See the [MCC reading guide](docs/reading/README.md) for setup, limits and eviden ## Mods -Mods go in a `mods` folder next to `maps`. Each mod is a folder of Halo PC tag files, as the Halo Editing Kit and Invader make them, with a `mod.toml` describing it. Every mod in the folder is on by default. Mods in the main menu turns them on and off and sets their order. Think of it like a resource pack list, the mod at the top plays over the ones below it. The game also refuses mods that say they cannot be played together. +Mods go in a `mods` folder next to `maps`. Each mod is a folder of Halo PC tag files, as the Halo Editing Kit and Invader make them, with a `mod.toml` describing it. Every mod in the folder is on by default. Mods in the main menu turns them on and off and sets their order. Think of it like a resource pack list, the mod at the top plays over the ones below it. The game also refuses mods that say they cannot be played together. -Refer to [docs/mods.md](docs/mods.md) to make your own. +Mods apply to Xbox and Custom Edition maps only. MCC maps always use their +authored resources; loose-tag mods are bypassed. +Refer to [docs/mods.md](docs/mods.md) to make your own. ## Graphics @@ -218,6 +381,10 @@ The game retains the original look and feel as it did on the Xbox by default. Th | OVERSHIELD | The overshield's own color, rising up the body as it charges | Off | | PASSENGER THIRD PERSON | Third-person view for Warthog and Scorpion passengers (Campaign-only) | Off | +Android builds omit the optional Dynamic Lighting renderer, including Shield +Glow, after reports of rendering failures across devices. Stock lighting and +effects remain. See [Android lighting availability](port/android/README.md#lighting-availability). + ## How to build the game @@ -266,6 +433,12 @@ always start on a different computer. ## For developers +Start with the [GulchCE code reader's guide](docs/reading/README.md) for a +route through startup, input and menus, gameplay objects, rendering, +networking, map loading, platform support and testing. It includes a +glossary of engine terms and C conventions, a detailed FOV walkthrough, +dynamic lighting 1.0, and notes on the Vulkan and third-person branches. + ### Testing The tests are listed in [AGENTS.md](AGENTS.md) ("Testing"). Most run @@ -350,6 +523,9 @@ A profiling build plays with normal builds. It does not use The decompilation is of the Xbox build 2342 (`cachebeta.exe`, SHA-256 `4cc87b45f721270392a96f1674ed2b5cd4a7bb4355faeab4531d1cf1884d9520`). + +GulchCE is a fork of [OpenCE](https://github.com/OpenCommunityEdition/OpenCE) The main contributor is Chester (@chestahh). Everyone else who has contributed is on the [contributors page](https://github.com/chestahh/GulchCE/graphs/contributors). + OpenCE starts from the decompilation of [bnunu/halo-1](https://github.com/bnunu/halo-1), which is a fork of [punpckhdq/halo](https://github.com/punpckhdq/halo). The artists of the @@ -358,7 +534,12 @@ high-res redraws are in [AUTHORS.md](AUTHORS.md). The main contributors are Jona ## Licence -OpenCE is free software: you can give it to others and change it under the +Optional bot and Android features credit their authors and earlier sources +in [the provenance guide](docs/reading/bots_and_android_features.md). +Adapted BirchWoodGod/thelinkin3000 bot tactics retain +[GPL-3.0-only](LICENSES/GPL-3.0-only.txt), alongside the project's AGPL code. + +GulchCE is free software: you can give it to others and change it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3 of the License or (at your option) any later version (`AGPL-3.0-or-later`). It comes with no warranty. The full text is in @@ -389,5 +570,5 @@ version (`AGPL-3.0-or-later`). It comes with no warranty. The full text is in ## Disclaimer -OpenCE (Open Community Edition) is an unofficial fan project. It is not endorsed by or affiliated with Microsoft, Xbox Game Studios, Halo Studios, Activision or Bungie. Halo and Halo: Combat Evolved are trademarks of Microsoft Corporation; Halo © Microsoft Corporation. +GulchCE is an unofficial fan project. It is not endorsed by or affiliated with Microsoft, Xbox Game Studios, Halo Studios, Activision or Bungie. Halo and Halo: Combat Evolved are trademarks of Microsoft Corporation; Halo © Microsoft Corporation. No game data is included. You must provide your own copy of the game. diff --git a/docs/changelog.md b/docs/changelog.md new file mode 100644 index 0000000000..498d990f3f --- /dev/null +++ b/docs/changelog.md @@ -0,0 +1,282 @@ +# Player-facing changelog + +The changelog uses short, authored highlights. It does not publish commit +subjects, infer changes from file names, or call an AI service. Internal +maintenance commits can remain unannotated. The generated JSON supplies the +menu; `notes.md` supplies release highlights from the same authored source. +Each published entry uses its exact GitHub release build number. Previous and +Next navigate these published builds; long notes scroll within a build's page. + +The main menu also shows `gulch build N` directly below the original Xbox +version, using its orange font and style. `N` comes from the executable's +`HALO_BUILD_NUMBER`, the same GitHub Actions number used for its release; +the label does not infer a number from Git history or the notes archive. +Local and testing builds without a release number show `gulch build local`. +This label remains visible when the optional changelog is disabled. + +## Writing a note + +Add one or more lines to the commit message body: + +```text +Player-Note: Added controller navigation to the changelog. +Player-Note: Fixed missing sounds on supported maps. +Player-Note: [INTERFACE] Improved menu navigation. +Player-Note: [QUALITY OF LIFE] Added controller shortcuts. +``` + +Each note must contain 1 to 100 printable ASCII characters. Keep it a short +sentence about a change players can observe. Backslashes, menu pipes (`|`), +tabs, newlines within a note, control characters and non-ASCII text are +rejected. Annotations start at the beginning of a line. The spelling +`Player-Note:` is case sensitive; incorrectly cased prefixes and empty notes +fail generation with the commit SHA and a corrective diagnostic. Ordinary +prose mentioning Player-Note and indented documentation examples are ignored. +XML punctuation is permitted; the menu generator must escape it when writing +XML. A note's surrounding spaces are removed. + +An optional `[CATEGORY]` prefix assigns a blue section heading in the menu. +Its label contains 1 to 24 uppercase ASCII letters, digits and single spaces, +starting with a letter, such as `INTERFACE`, `QUALITY OF LIFE`, `GAMEPLAY`, +`GRAPHICS` or `MULTIPLAYER`. The note's 100-character limit excludes this +prefix. Categories are authored explicitly; the collector never classifies +notes from keywords or asks an AI service. Plain notes continue to work and +appear under `GENERAL`. Categories follow their first appearance in a build, +and notes retain their order within each category. Release Markdown retains +the original note order and plain bullet format. + +The published testing merge `4f3eec76a1165a111bff83047b064a55c156f3bc` +mistakenly used `[Android]`. The collector corrects that exact commit's prefix +to `[ANDROID]` before normal validation, preserving its notes without rewriting +shared history. This historical exception does not accept mixed-case categories +in new commits or relax note-text validation. + +The CPU optimization `9bf9554aa86dbeba9fa49f5d8ff1b99f2ba82c1b` was withdrawn +from main by `192ba0b5c0c1549b76bc7b21de786c9fd7202711` before publication, +while remaining on testing for ongoing development. The collector omits that +original note only for histories containing the withdrawal. Testing previews +without it retain the note. This is a recorded correction to published history, +not inference from commit subjects or general detection of reverts. A later +reviewed restoration must carry its own annotation, which may reuse the note. + +Use `Player-Note: none` to explicitly omit a commit, including any catch-up +entry for it. Do not combine `none` with another note in the same commit. +The omission marker has no category. +Unannotated commits produce no automatic fallback. Do not add annotations +merely to satisfy a quota. + +Before adding a highlight, inspect its actual diff and evidence. Never use +commit titles alone as evidence of a player-facing change. + +## Generating the files + +Run from a full checkout with Git and Python's standard library: + +```sh +python tools/player_notes.py --head HEAD --output build/player-notes +python tools/player_notes.py --head --build-number 433 --base --previous previous-changelog.json --output build/player-notes +python tools/player_notes.py --head HEAD --preview --output build/player-notes-preview +``` + +`--head` accepts `HEAD` or a full 40-character commit SHA. `--base` accepts a +full commit SHA and must be an ancestor of the selected head. A base identifies +the previous successful release, rather than the previous commit: highlights +therefore include changes from failed or skipped builds. Without a base, +release highlights cover all history after the catch-up baseline. Invalid or +unavailable ranges fail instead of publishing incomplete notes. Shallow +checkouts fail with instructions to use `fetch-depth: 0` or fetch full history. + +`--build-number` is the GitHub Actions run number, from 1 to 2147483647, used in the published +release's `Build N` title and `build-N` tag. Without it, local generation defaults +to an `UNRELEASED` preview; `--preview` states that choice explicitly. Preview and +a numbered build cannot be combined. Each run produces a current entry even +when its note list is empty, so releases without player-facing changes still +have their own build page. Rebuilding the same commit under a new build number +also creates a new entry. + +`--previous` supplies the schema-2 `changelog.json` attached to the previous +published release. It requires `--base`, and the archive head must match that +base exactly. The first archive entry must name the same commit, each retained +entry must name an ancestor of it, and build numbers must be unique positive +integers at most 2147483647, in descending order below the current build number. Dates and every +note are validated too. A missing or malformed supplied file fails generation. +Omit `--previous` when no archive exists, such as the first numbered rollout: +the result contains only the current build, with no inferred historical build +numbers. A preview may include a supplied published archive. + +The default catch-up manifest is +`port/assets/changelog/catchup.json`; `--catchup ` selects another. +The tool reads Git history and the manifest, then writes only the requested +output directory. Each output file is replaced atomically after successful +validation. JSON encoding, entry dates from Git and note ordering are +deterministic for the same selected history and manifest. + +The output directory contains: + +- `changelog.json`: the selected history for the in-game menu. +- `notes.md`: all newly introduced highlights in `base..head`, or + `baseline..head` without a base. With no highlights it contains + `No player-facing notes were recorded for this build.` This describes missing + notes without claiming that the code has no player-facing changes. + +The menu JSON has this schema: + +```json +{ + "schema_version": 2, + "head": "0123456789012345678901234567890123456789", + "entries": [ + { + "build": 433, + "date": "2026-10-18", + "commit": "0123456789012345678901234567890123456789", + "notes": ["Added controller navigation to the changelog."], + "categories": ["INTERFACE"] + } + ] +} +``` + +The current entry comes first; previous entries retain their published build +numbers, commit IDs, dates and notes. Preview entries have `"build": null` and +are labeled `UNRELEASED`; published archives contain numbered entries only. +An optional `categories` list contains exactly one label per note; an empty +label means `GENERAL`. The collector omits this field for a new entry with no +categorized notes. Previous archives without it remain valid and unchanged; +category metadata on published entries is carried forward and validated. +Git history determines which notes enter the current release, including every +newly reachable commit's body on merged upstream and testing branches. It does +not determine release identities or create pages for commits. Notes follow +their chronological introduction to the first-parent history, preserving +topological and authored order within that introduction. Only commits in +`base..head`, limited to coverage after the catch-up baseline, contribute. + +Duplicate notes ignore case, repeated whitespace and an optional trailing +period. The first introduction owns a duplicate, even if it is outside the +visible history window. Repeating an old annotation therefore does not publish +it again in a later release's `notes.md`. A duplicate also keeps its first +category; adding a new label does not create a new highlight. + +The menu retains the current build and the seven newest previous builds, with an explicit +stderr notice if older entries are omitted. It preserves every note within +each retained entry; the renderer scrolls long entries. A retained history +with more than 4096 notes fails for manual consolidation. Release Markdown is +only the current release's highlights. Preview mode collects notes since the +base, or since the baseline when no base is supplied, and applies the same +4096-note limit. An empty range still produces the current build or preview +entry with an empty notes list. + +## Catch-up history + +The checked-in catch-up manifest records reviewed highlights for older +commits that predate `Player-Note:` annotations: + +```json +{ + "schema_version": 1, + "baseline": "0123456789012345678901234567890123456789", + "notes": [ + { + "commit": "1123456789012345678901234567890123456789", + "text": "Added controller navigation to the changelog.", + "category": "INTERFACE" + } + ] +} +``` + +The baseline is excluded and must be an ancestor of the selected head. Every +referenced commit must exist and use a full SHA; every text follows the same +note validation rules. Only references actually included in the selected +ancestry contribute. For several highlights on one commit, preserve their +intended order in the manifest. Catch-up highlights precede message annotations +on that commit and participate in the same deduplication. To omit a catch-up +highlight, remove its entry instead of using the text `none`. +The optional `category` uses the same label rules as annotations. Existing +catch-up headings are manually assigned from the reviewed change descriptions; +they do not change the notes' text, commit provenance or release boundaries. + +## CI and published history + +The workflow's `changelog` job checks out full history and generates the notes +once. On `main`, `tools/changelog_release_base.py` lists published `build-*` +releases, excludes drafts, prereleases and the current run's tag, then chooses +the most recently published release whose tag resolves to an ancestor of the +selected commit. The workflow publishes builds only from `main`; ancestry +checking prevents a newer unrelated release from becoming the range base. +The helper reads the documented `tagName`, `publishedAt`, `isDraft` and +`isPrerelease` fields from +[`gh release list`](https://cli.github.com/manual/gh_release_list). + +With no prior published ancestor, generation uses the catch-up baseline. A +prior release older than that baseline is valid: the baseline still defines +the start of authored changelog coverage. Failed or cancelled builds create +no published base, so the next successful release includes their highlights. +Other branches receive one `UNRELEASED` preview entry. + +On `main`, the job passes `GITHUB_RUN_NUMBER` as `--build-number`, together with +`--require-notes`. If the release range contains new commits but no new highlights, +generation fails before any platform builds or publication. An empty range or a +range containing only explicit `Player-Note: none` commits is allowed. For an +internal-only integration, review the entire release range and put +`Player-Note: none` on its tip commit to explicitly confirm that decision. +An omission on an unrelated maintenance commit does not excuse an unannotated +merge. Repeating an already released note does not satisfy this check. + +Upstream authors need not use our annotation convention. When merging upstream, +review its changes and add short `Player-Note:` summaries to the integration +commit, or add reviewed notes for that commit to the catch-up manifest. This +guard catches empty releases; it cannot judge whether nonempty notes describe +every player-facing change. That remains part of integration review. + +If the previous +release has a `changelog.json` asset, the helper downloads it and the collector +uses it as `--previous`. A release from before this feature has no archive and +starts the numbered history at the current release. Existing but invalid +archives fail rather than silently dropping known build history. Unpublished +preview snapshots never become previous published entries. The helper accepts +only the named JSON asset, limits it to 2 MiB, and checks its head and newest +build number against the selected release tag before the collector validates +the complete archive. + +The job renders the text-only menu from `changelog.json` and uploads one +`player-changelog` artifact. Linux, Windows, Android and web all download this +same artifact before building, installing its menu XML and JSON. Consumers +therefore need no Git history or note-generation dependencies of their own. +The collection job uses read-only repository permission. Release publication +keeps the existing `contents: write` permission in the release job. + +After all four platforms succeed, publication uses the generated `notes.md` +and attaches `changelog.json` alongside the build archives. The JSON records +the selected head and retained history, providing an archive of exactly the +notes used for that build. Later builds carry the previous release's retained +entries forward in their new archive. They therefore preserve exact release +boundaries even after the workflow deletes older releases and tags. Full Git +history and authored notes determine the current range; the latest published +archive supplies the previous release pages. No unpublished commit grouping +is presented as a release. + +Repeating generation for the same source and base produces the same files. +The artifact upload replaces the same named artifact on reruns, and base +selection excludes the current run's release tag. Release publication retains +the workflow's existing `gh release create` behavior: a fully published run's +tag already exists, so rerunning publication is not an automatic replacement +of the existing release. + +## Verification + +```sh +python -m pytest -q tools/test_player_notes.py +``` + +These tests create real, temporary Git repositories. They cover merged +ancestry, chronological collection, release ranges, deduplication, explicit +omissions, previews, catch-up filtering, missing commits, shallow history, +unsafe text and revision-option injection. They also check deterministic +output, numbered release snapshots, failed-build recovery, empty releases, +archive validation and preservation of existing outputs when validation fails. +Category checks cover explicit labels, old uncategorized archives, duplicate +ownership, unsafe labels, parallel metadata lengths and collection through to +the renderer's grouped blue-heading tables. These tests do not establish +visual menu correctness or game compatibility; those +require the renderer's checks and the project's platform validation. diff --git a/docs/contrail_timing.md b/docs/contrail_timing.md new file mode 100644 index 0000000000..8e4ff4bb10 --- /dev/null +++ b/docs/contrail_timing.md @@ -0,0 +1,113 @@ +# Projectile contrail timing + +[Issue 84](https://github.com/chestahh/GulchCE/issues/84) reports thinner, +dimmer Covenant turret trails above 30 FPS. This is a fix to the existing +shared effect implementation, not an MCC data conversion or a new feature. + +## Cause and correction + +Before GulchCE's original fix, `contrails_update` in +[contrails.c](../source/effects/contrails.c) batched point emission using +accumulated frame time, but passed only the current frame time to +`contrail_update_points` for aging existing points. + +Point-state transitions reset their normalized time to zero, discarding +overshoot. Consequently, a short state lasts until the next update boundary. +A local inspection of Xbox b40's `vehicles\c gun turret\c gun turret` +contrail found a 30-points/second rate, a 0.01-second state at width 0.15 and +alpha 1, then a 0.05-second transition to width/alpha zero. Per-frame aging +shortened that bright body as render frequency increased. + +The correction supplies the emission interval as a separate state-aging +argument. The 30 Hz transition behavior remains; point physics, bitmap +sequence animation and texture scrolling still use frame time. Calling the +point updater with zero state time remains necessary: a point created by an +attachment change or collision must have a valid state before it is rendered. +The original fix also reset the emission clock on map initialization and disposal. + +This changes no tags, loader, map-family dispatch, projectile simulation, +network messages or shared random seed. Contrail state durations use the +local random stream. No network version change is needed. Xbox, Custom Edition +and MCC keep their existing loaders and use the same effect timing afterward. +No feature-owned hook is necessary for a correction within this implementation. + +## Integration with OpenCE PR 546 + +The November upstream integration retains GulchCE's separate state-aging and +per-frame motion arguments. It adopts upstream's nominal tick duration for +emission and aging: 1/30 second per elapsed game tick, halved in double-speed +mode. At 144 FPS, four or five render frames can fall between ticks; their +accumulated time therefore varies even though each game tick has equal duration. +Nominal tick time removes that variation in short bright states. + +When a render frame spans several ticks, existing point states advance one +tick at a time because each transition discards the remainder of its step. +Point physics still runs once with the frame delta. This does not reconstruct +historical attachment positions or reproduce every intermediate emission at +low frame rates. New points still initialize when state time is zero. + +`contrails_reset_render_state` owns the clock reset. Map initialization, +disposal and the existing `after_load_procs` table in +[game_state.c](../source/saved%20games/game_state.c) call it. A checkpoint can +restore a different point pool at the same tick, so comparing tick numbers +alone cannot invalidate the old clock. This is a general saved-state lifecycle +fix, shared by existing map families; it adds no MCC conversion logic. + +The [original harness](../tools/harness/tests/test_contrails.py) now also checks +same-tick checkpoint restoration through the real callback table, two-tick +state aging, and double speed. The +[upstream harness](../tools/harness/tests/test_contrail_tick_points.py) checks +steady 144 FPS, uneven frame intervals and time jumps with real point emission. +Both compile production functions; attachment/physics stubs do not establish +visual equivalence or full map compatibility. + +## Validation on Windows, 1 November 2026 + +Base: `origin/testing` at `6303ff6a0847525d385bcb9aca5fed518b211130`. +Build: portable release, PGO off, LTO off; LLVM 23.1.4, OpenGL, hidden windows. + +- [Real-code harness](../tools/harness/tests/test_contrails.py): nine tests, + including identical tick-boundary point counts/widths at 30/60/120/240 FPS, + a non-aligned 144 FPS schedule, zero-time pause, attachment reactivation, + initialization between ticks, detached cleanup and map-clock resets. + Deliberately restoring per-frame aging fails both rate checks; removing + clock resets fails the lifecycle check. Attachment placement and physics + are stubs; this is not a rendering or map-loader test. +- Xbox b40: before/after captures at 30 and 120 FPS, 640x480, Smooth Motion + enabled, optional lighting disabled. The existing capture fixture moves + three Shade projectiles along a controlled path near the camera. Visual + inspection shows the bright trail retained at 120 FPS, matching the + substantial bright body at 30 FPS. These are not pixel-identical frames: + simulation/render phase and emission positions can differ. Measured rates + were approximately 30.00 and 120.01 FPS for the corrected captures. +- Custom Edition Death Island: three Ghost projectile captures at about + 119.92 FPS, same renderer/settings, successful exit. This checks a second + trail and the existing CE path, not every CE contrail definition. +- Final combined regression run (contrails, BMP readers, cache formats and + web build checks): 203 passed, five skipped. +- Windows build passed. Full `ninja android` and `ninja web` were attempted + but their generated shell commands require unavailable Unix utilities on + this Windows host. The changed translation unit compiled successfully + with the generated arm64_32 Android and wasm32 flags; Android assembly + conversion and AArch64 assembly also passed. Full platform links/runtime + remain unverified. Linux/WSL is unavailable here. +- MCC DigsiteMP maps 1 and 10 converted and loaded their tags, then refused + the `host_spawn` script's unsupported `debug_camera_load` call. The smoke + runner stopped before its simulation-advance check. MCC gameplay and real + cross-family transitions therefore remain unverified; those script paths + were not changed for this issue. + +The original b40 free-flight fixture hit nearby scenery too soon for a useful +trail comparison; the controlled-path captures above replaced it. Blood Gulch +had no requested multiplayer Shade tag, so those attempts are not validation. + +Self-review covered the entire source change, its sole private caller, +initialization/disposal, point cleanup, renderer state access, tests and this +reading route. Per-frame physics was deliberately retained when separating +state time. No unrelated refactoring was needed. This preserves the engine's +existing tick-batched emission and state quantization; it does not introduce +sub-tick trail interpolation or solve low-FPS/catch-up sampling in general. + +Local logs, capture manifests and compressed images are retained under the +worktree's ignored `build/issue84-evidence`. Test map copies and generated map +caches are removed; test saves and captures are preserved losslessly. diff --git a/docs/covenant_emitter_lighting.md b/docs/covenant_emitter_lighting.md new file mode 100644 index 0000000000..dbaf8064b2 --- /dev/null +++ b/docs/covenant_emitter_lighting.md @@ -0,0 +1,418 @@ +# Covenant emitter lighting + +Three independent options default to false: `display.jackal_shield_lighting`, +`display.fuel_rod_lighting` and `display.covenant_shield_lighting`. Their environment +variables are `HALO_JACKAL_SHIELD_LIGHTING`, `HALO_FUEL_ROD_LIGHTING` and +`HALO_COVENANT_SHIELD_LIGHTING`. Projectile lighting is not required. The menu now groups the two shield +preferences under **Shield Emitters** and fuel rods under **Weapon Glow**; +the individual configuration keys remain available. +`display.plasma_occlusion` optionally adds the existing approximate collision +visibility filter. CStencil and Modern are separate work. + +`port/linux/game/covenant_emitter_lighting.c` owns eight additional render lights +shared by these options, the optional Assault Rifle counter, held Needler and +the [vehicle/world/flame additions](reading/emitter_expansion.md). The additions +reuse the pool; they do not increase its capacity. +Stock effects, tag data, damage, weapons, explosions and +network state are unchanged. Excess emitters retain stock appearance. Stable +admission avoids swapping lights every frame when the budget is full. Lights +fade between 22 and 25 world units from the nearest local camera. + +## Profiles and evidence + +Read-only inspection of Xbox c40 tags and the existing model/shader interpreter +established these identities; no third-party implementation was copied. + +| Emitter | Exact tag | Marker | Radius | +| --- | --- | --- | --- | +| Jackal minor / major | `characters\jackal\jackal`, `characters\jackal\jackal major` | `shield light` | 3.6 | +| Stationary shield | `scenery\c_field_generator\c_field_generator` | `shield light` | 2.8 | +| Fuel rods | `weapons\fuel rod gun\fuel rod` (weapon group) | `lens flare` | 1.6 | +| Hunter fuel rods | `characters\hunter\hunter` (biped group) | `rodflare` | 1.6 | + +Shield colour comes from runtime change colour C, the stock shield shader's +colour source: minor blue, major gold and stationary violet. Blue Jackals use a +wider radius and a (0.30, 0.42, 1) minimum blue profile for more visible spill. +Both stock generic shield shaders blend this colour towards red with A-out in +stage 3. The feature samples the same evaluated outgoing function, without a +separate hit timer or colour smoothing that would lag behind the shield. Gold shares the 3.6-unit reach, with green/blue floors of 0.78/0.24 for +brighter warm spill. The resting stationary violet profile is unchanged. Both shield models +have a `shield` region with visible permutation zero and `~shield_off` permutation +one. The marker also exists with the shield off, so marker presence alone is +insufficient. Depleted vitality, depleted flags, shield permutation, destroyed +region and death all suppress illumination. Indestructible scenery with zero +maximum body vitality remains eligible. + +Fuel rods use a restrained green light at the back of the weapon, not its muzzle. +A held weapon must be the unit's current weapon; a dropped visible weapon stays +luminous until stock removal. The Hunter's exposed rods use its biped model's +`rodflare` marker on the animated right forearm, with the same green profile. +This includes visible corpse rods until stock removal. Its model-less weapon +remains excluded, avoiding a second misplaced light. Renamed +custom tags are deliberately not guessed from substrings. + +The rendered marker pose follows existing render interpolation. An 80 ms +exponential response smooths activation, shield damage and collapse using render +time, including frames between 30 Hz simulation ticks. Repeated views at the same +time do not advance the response. World diffuse, model lighting and eligible +specular highlights use the existing soft falloff. Occlusion shares the existing +eight-field budget and is approximate; it is not stencil or shadow-map rendering. +The stationary shield is excluded from its own visibility rays because the +point source approximates its luminous surface. Other scenery and machines, +including other shield emitters, still block it. + +## Integration and lifecycle + +The small `port:` additions in `source/objects/object_lights.c` are necessary +because feature modules cannot independently enter light collection, extend its +bounds, or observe engine light-storage resets. They call the owned module before +collection, extend only owned light bounds, and forget identities at initialization, +old-map disposal, shutdown and light-storage recovery. Existing light allocation/move interfaces are reused. +Existing feature modules route submission, model masks, optional occlusion and +frame cleanup. Each frame ends with owned lights black and disconnected from the +map, preventing their use by simulation/AI. Disabling removes owned lights; +missing markers/templates and allocation failure fall back to stock appearance. + +No map-family discovery or loading code changes. Xbox, Custom Edition and MCC use +their existing paths; only recognized tags with valid models/markers participate. +Network messages and simulation contracts do not change, so no network-version +bump is needed. + +## Assault Rifle counter + +`display.ammo_counter_lighting` / `HALO_AMMO_COUNTER_LIGHTING` is independently +off by default. `ammo_counter_lighting.c` supplies the rendered source position; +the existing emitter module owns its bounded light, easing and cleanup. No new +light-allocation hooks are needed. The radius is 0.95 world units, colour +(0.24, 0.65, 1.0), and strength 0.65, increased after playtest feedback. + +A minimal marked hook in `rasterizer_xbox_models.c` lets the feature adjust the +self-illumination colour before shader selection and constant submission. A +feature-only light cannot brighten the screen's own emissive mask, hence this +addition to the shared Xbox/CE/MCC model drawing path. The helper matches only +`weapons\assault rifle\fp\shaders\display`, shared by both stock models, and +raises its emissive minimum to (0.45, 1, 1) in both views. The authored multipurpose texture +still masks the emission. It does not add global bloom or alter tag data. The +cached shader identity is cleared by the existing map/light-storage lifecycle. +The setting-off path returns before looking up or changing any shader. + +The display constants are already saturated, so `ammo_counter_lighting_draw_begin` +additionally doubles the completed RGB output for that display material only, +before fog. A paired `ammo_counter_lighting_draw_end` restores the exact saved +combiner output before another material or view. These minimal marked calls in +`_rasterizer_model_draw` are necessary to bracket the engine's draw; policy and +state remain in the feature module. Authored output scaling/bias is preserved. +There is no shader translator or GPU workaround change. The first-person spill +gain is 1.35, with the existing 0.95-unit radius and directional mask. The world +display now shares the first-person material boost; third-person light strength +(0.65), radius and falloff are unchanged. Per-view +gain does not enter shared fade history, so a first-person view cannot brighten +a later third-person view. + +Only the exact `weapons\assault rifle\assault rifle` weapon currently held by a +visible unit participates. That includes Marines and remote players without +depending on player ownership. Holstered, dropped, missing-marker and unfamiliar +weapons are excluded. The existing first-person marker API selects the local +visible model; other views use the third-person weapon marker. No tag, ammo, +animation, or networking state is changed. The screen shader receives only the +optional per-draw emissive adjustment described above. + +Read-only Xbox c40 geometry inspection found counter-digit part centroids near +(0.04706, +/-0.00160, 0.06850) in first person and +(0.04734, +/-0.00160, 0.06840) in third person. Both `primary trigger` markers +have identity rotation; their z coordinates differ by 0.002744. An offset of +-0.18 along forward and +0.025 (first person) / +0.027744 (third person) along up +places the light just behind and above the display, tracking the rendered pose. +Custom models reusing the stock tag name may require separate tuning. + +## Reproducing checks + +The harness compiles the real module and exercises settings, authored colours, +shield permutations, held/dropped eligibility, frame-rate-independent easing, +capacity, cleanup and allocation failure. Negative controls remove the shield +permutation guard or replace render time with tick time and must fail. + +Build the diagnostic executable with `tools/plasma_visual_build.py`; normal +sources are restored and the normal Windows executable rebuilt afterwards. +Run `tools/plasma_visual_run.py --data-root --map c40 --emitter +--fps <30|60|120> --enabled <0|1> --occlusion 1 --label ` where kind is +`jackal`, `major`, `fuel` or `stationary`. The fixture spawns original tags, +depletes/recover shields through engine damage interfaces, drops held fuel rods, +and deletes its emitter. The fuel fixture clears the temporary detonation timer +from creating a loose weapon when its hand attachment completes; later dropping +uses the stock weapon behaviour. These controlled state changes exist only in the capture +build. Logs, timing reports and images remain in `build/plasma-visual`; copied +maps are removed. Visual checks do not establish exhaustive campaign compatibility. + +Counter fixtures use `--emitter ammo-fp`, `ammo-marine` or `ammo-player`. +Blood Gulch supplies the first-person/player-model cases; b40 supplies Marines. +`--hide-viewmodel` removes the local weapon from the image for clearer third-person +inspection, using the existing setting that leaves weapon lights active. + +## Validation of this milestone + +Windows portable release builds passed. The 51 focused real-source harness +checks passed across emitters, muzzle/projectile ownership, occlusion, falloff +and model shaders. These include negative controls for shield permutations, +tick-only easing and loss of the first-person counter pose. Existing light-storage +COFF/full-LTO checks and their corruption negative control also passed. + +32 final enabled/disabled capture cases passed: Jackal minor, Jackal major, held +and dropped fuel rods, stationary shields, Warthog fire, first-person counters, +Marine counters and player-model counters. Each has enabled 30/60/120 FPS captures +and a disabled 60 FPS control. All sustained their cap within 5% during the +measured windows. Disabled cases submitted no added feature lights. Shield +collapse/recovery and fuel-rod attachment/drop/deletion were exercised. Images +were inspected at all three rates. An additional b40 first-person counter run +observed both model diffuse and specular draws; Blood Gulch's counter scenes did +not demonstrate positive specular output. Stock shader eligibility is preserved. + +Reports/images are under `build/plasma-visual`, with the selected 32 reports +listed in `build/lighting-release-captures.json`. Jackal captures use +`emitter-final-*`, fuel/turret captures `emitter-release-*`, and the latest +stationary/counter captures `ammo-final-*`. The earlier captures precede the AR +addition but exercise unchanged profiles. `build/ammo-ground-visual` records +the final production source hashes. Normal sources were restored, a normal +executable rebuilt, and capture logging/fixture absence checked. Two additional +60 FPS plasma-rifle/Needler regression captures passed before the AR addition. + +The initial short b40 counter run did not reach its capture window; the longer +run passed. A stationary fixture initially placed the source below the floor; +the fixture now uses a structure collision ray to place it on the floor. Failed +runs are retained as diagnostics and excluded from the final count. + +Android/web builds were attempted but this Windows build graph has neither +target configured. Linux was not built because WSL is unavailable. Browser +networking was not rerun; protocol/transport code is unchanged. These are bounded +Windows scene and lifecycle checks, not full campaign, arbitrary custom-model, +GPU, split-screen or multiplayer acceptance. Approximate occlusion and bounded +light admission retain the limitations described above. + +The final two-instance native Blood Gulch run at 60 FPS produced counter samples +on both host and client, including the host's newly equipped AR as seen by the +client. Both exited normally after 84 reported snapshots. 75 snapshots matched +exactly; nine differed during live firing/death/respawn, so this checks bounded +rendering/connectivity rather than establishing deterministic network agreement. +The client fixture did not equip a weapon. Reports are in `build/ammo-network-rifle`. +Additional 60 FPS Marine/player-model captures with the local viewmodel hidden +passed and are retained under `ammo-clear-*` for less obstructed inspection. + +Final Xbox c40 -> CE Death Island -> MCC Mercury Falling -> Xbox Blood Gulch +transitions passed with all additions off at 30 FPS and on at 120 FPS. Each run +executed all three transitions, loaded MCC once, exited normally and logged no +exceptions (`build/ammo-transitions`). These checks do not establish full visual +compatibility for arbitrary MCC assets. The exact normal release executable +passed a hidden OpenGL startup smoke test with stock defaults; its SHA-256 is +recorded in `build/ammo-playtest-smoke/report.json` and checked against the ZIP. + + +## Shield colour and counter refinement validation (2026-10-15) + +The normal Windows x86 portable release builds successfully. All 52 focused +emitter/projectile/muzzle/occlusion/falloff/model-shader harness checks pass, +including a negative control removing the shader-driven damage colour. The +screen tests cover disabled behavior, unrelated shaders, missing tags and cache +reset across maps; the profile tests cover both brighter Jackal colours. + +`build/colour-capture-summary.json` records 24 accepted cases: blue Jackal, gold +Jackal, stationary shield, first-person AR, player-model AR and Marine AR, each +on at 30/60/120 FPS and off at 60 FPS. All sustain the requested rate within 5%. +Captured RGB telemetry verifies resting and red damage colours for all nine +shield/FPS combinations. The fixture applies stock damage-network state, which +then drives the actual object functions and shield shader; it does not force the +light colour. It also exercises depletion, recovery and deletion. One gold +60-FPS run failed due to a long hitch; its retry passed at approximately 60 FPS. +The failed report is retained rather than counted as a pass. + +Images show broader blue/gold spill, matching red shield/light states and stronger +AR housing illumination with readable first-person digits. Third-person captures +show illumination on the held models, but shoulder occlusion and the counter's +small screen size limit assessment of its readability. An additional close +player capture exposes the weapon; the close Marine experiment was off-screen +and is not evidence of screen readability. The standard fixture placement is +retained. These are bounded visual checks, not exhaustive gameplay acceptance. + +Source manifests are in `build/emitter-colour-visual` and +`build/emitter-colour-final`; gold uses the latter after its extra brightness +change. The unchanged blue/AR/stationary paths use the former captures. Final +production sources match the final manifest. The normal executable was rebuilt +without fixtures and smoke-tested separately in `build/colour-playtest-final-smoke`. +Its hash is checked against the packaged executable; no capture markers remain. + +Xbox c40 -> CE Death Island -> MCC Mercury Falling -> Xbox Blood Gulch +transitions pass off at 30 FPS and on at 120 FPS, with clean exit and no logged +exceptions (`build/colour-transitions`). This checks lifecycle/loading boundaries, +not full map-family compatibility or every custom shader. Android and web builds +were attempted but the generated build has neither target; Linux and browser +transport testing remain unavailable locally. No network format, simulation +contract, map loader, CStencil or Modern implementation changed. + + +A two-instance native loopback AR session passed with both options enabled: +84 shared snapshots, 83 exact matches and one differing `ed` value (221 vs 220). +Positions, health and ammo matched in that sample. Both instances exited cleanly; +only the host fixture equipped the AR, and the client recorded 856 emitter +samples from the replicated weapon. See `build/colour-network-rifle`. This is a +bounded multiplayer smoke/regression check, not a proof of deterministic or +internet/browser compatibility. All test map copies were confined to private +run folders and removed; original maps and saves were preserved. + +## Directional ammo counter refinement + +The counter keeps its 0.95 radius, 0.65 strength, colour and emissive screen +floor. Its spill now follows a broad rear/up-facing hemisphere in the animated +weapon marker basis (-0.8 forward + 0.6 up), in both first and third person. +This approximates the sloped display orientation; it is not a measured mesh +normal or an area-light simulation. A smooth angular fade reaches full strength +at a dot product of 0.6 and zero behind the display. This removes downward spill +for a normally held rifle while allowing nearby surfaces when the rifle turns. + +`ammo_counter_falloff.c` owns the bounded eight-light, 16-cubed texture pool. +Existing world diffuse/specular and model visibility interfaces consume the +same angular mask. With collision occlusion enabled it multiplies the visibility +field after admission blending. Without an admitted field it uses a separate +mask, so disabling wall occlusion or exhausting its budget does not remove the +directionality. Allocation/upload failure still permits the existing unmasked +fallback; this is not a guarantee under graphics resource failure. +Textures reset with the existing occlusion lifecycle and refresh per view. +No stock source hooks, map loaders, simulation or network formats changed. + +Regression tests exercise the actual feature sources, rotated poses, forward +brightness, rear rejection, combined visibility, disabled collision, independent +world/model textures and resource cleanup. A mutation that removes the angular +mask is rejected. The brighter shield profiles and screen material are unchanged. + +The directional refinement passes 54 focused lighting, falloff and shader +regression tests. Windows portable release and diagnostic builds compile. +The final capture manifest is `build/directional-sweeps/build-manifest.json`. +Earlier stationary captures use `build/directional-visual`; the only later +production changes are a collision comment and retaining the directional cache +between emitter-only frames when collision occlusion is off. + +Visual captures cover first-person AR, Marine and player models at 30/60/120 FPS, +with disabled controls at 60 FPS. The final aim sweeps exercise yaw, elevation +and reloads. First-person screen readability and nearby housing light remain; +the tested held-model scenes have no broad blue foot pool. Their rear camera +angle limits assessment of face illumination and tiny third-person digits. +The angular model is intentionally approximate and needs normal playtest feedback. +Initial weak-input sweeps were superseded after correcting controller dead-zone +coverage; two also failed timing due to frame hitches. Those logs are retained. +Final captures are separate and must sustain the cap within five percent. + +`build/directional-capture-summary.json` records 26 accepted capture cases, +including counter-only lighting with collision off at all three frame caps. +Xbox c40 -> CE Death Island -> MCC Mercury Falling -> Xbox Blood Gulch passed +with features off at 30 FPS and on at 120 FPS, clean exits and no logged +exceptions (`build/directional-transitions`). This checks lifecycle boundaries, +not exhaustive map compatibility. Android and web builds were attempted but +both targets are absent from the generated build; Linux and browser transport +remain unverified locally. No simulation agreement or wire format changed. + +The two-instance native AR session exited cleanly with 84 shared player snapshots: +76 exact matches; the other eight differed only by one in the logged `ed` field. +Positions, health, ammunition and the other compared player fields matched. +The client recorded 4926 emitter samples without equipping a fixture locally. +This is a bounded replication smoke test, not bit-identical multiplayer proof +(`build/directional-network-rifle`). The normal executable passed a separate +hidden OpenGL smoke test with stock defaults and no capture markers; its hash +matches the final package. Final production hashes match the sweep manifest. +Owned map copies were removed; original maps/saves and diagnostic logs remain. + + +## Held Needler crystals and first-person AR refinement + +`display.needler_lighting` (`HALO_NEEDLER_LIGHTING`) defaults to false and is +independent of projectile lighting. The exact stock `weapons\needler\needler` +tag uses the shared eight-emitter pool while equipped by a visible unit. Holstered, +dropped, deleted and markerless weapons do not retain an added light. The light +uses the interpolated first-person pose when available and the rendered world +marker otherwise, so players and NPCs use the same policy. + +Read-only inspection of the stock c40 tags found matching `smoke` markers at +(-0.031742, 0, 0.080221) in both models, on the exposed needle cluster. The +radius-1.5 pink-purple light has strength 0.9 and the existing render-time easing. +Its radial mask spills broadly sideways and upwards, smoothly suppressing spill +farther below the housing (see the baseline refinement below). This is an +approximation, not mesh shadows; weapon and biped triangles are not collision +blockers. The same lower fade +applies with occlusion enabled or disabled, including model/specular passes. + +The masked `needler dull` material gets a pink emissive floor. The first-person +`needler core` and world `needler luminous 3p` transparent colour stages are +brightened 2x before fog, retaining authored colours, textures, alpha and blending. +Already scaled/biased custom stages are left alone. No tag data is modified; +material identities are forgotten at map cleanup. Other needle projectile and +ammo pickup materials are not selected. This enhances existing crystal emission, +not a new screen-space bloom effect. + +Minimal `port:` model and transparent-renderer hooks are necessary because the +feature module cannot access the per-draw illumination/combiner values through +existing engine interfaces. Shader identity checks, activation and adjustment +logic remain in `needler_lighting.c`. The Xbox/CE/MCC loading and conversion +paths are unchanged; matching loaded materials use the guarded render hook. + +For the AR, the rendered first-person pose alone raises spill strength from +0.65 to 1.0 without increasing radius or changing its directional mask. The +first-person geometry flag selects a brighter screen floor (0.45, 1.0, 1.0). +World-model strength and screen colour remain exactly at the earlier tuning. +Both changes remain under the existing off-by-default AR option. No simulation, +weapon ammunition, packets or protocol version changed. + +Validation is recorded with this branch's local build reports. Windows portable +release builds use `--release --portable --lto=off --pgo=off`. Asset-free tests +exercise actual feature sources, shader selection, stock defaults, held/dropped +policy, rendered poses, broad falloff, cleanup and AR world-model invariance; +negative controls detect missing crystal emission and first-person AR intensity. +Android and web build attempts report unavailable targets in this Windows +configuration. Linux, cross-platform multiplayer and MCC runtime acceptance +remain unverified for this change. + +The final Windows capture matrix passed all 14 cases: first-person Needler, +third-person Needler holder and first-person AR at 30/60/120 FPS enabled, plus +60 FPS disabled comparisons; a Marine carrying a Needler on b40 and the +unchanged third-person AR on bloodgulch at 60 FPS. Frames were visually reviewed, +including brighter crystal cores, AR screen/spill and NPC/world models. Measured +average rates met each requested cap within 5 percent. All 26 related asset-free +regressions passed, including negative controls. Capture manifests match the +production source hashes. These are bounded Xbox-map fixtures, not campaign, +CE/MCC, reload-animation, multiplayer or all-GPU acceptance. Temporary map +copies/cache files were removed and only representative frames/logs retained. + + +## Baseline polish and radial Needler spill + +The Needler now uses radial spill around the crystal cluster instead of the +weapon-up angular mask. Receivers immediately below the source retain full +light, so the casing and hands are not cut out by a cone. Only farther downward +spill fades: full strength through 0.06 of the radius below the source, a smooth +transition through 0.12, then zero. This uses world height and does not rotate +with aim. Radius (1.5), colour, brightness, crystal material emission and held +weapon policy are unchanged. It is an artistic approximation to body/housing +shielding, not mesh shadows. Visual acceptance shortened the original 0.24 +endpoint because filtering between volume-texture slices extended its spill +to a crouched holder's feet. The full-strength region immediately below the +needles remains unchanged; no new textures, traces or per-frame work were added. +Unusual custom poses still need playtest judgement; CStencil and Modern remain +separate work. See [visual acceptance](dynamic_lighting_acceptance.md) for the +tested crouched-player and short-NPC cases and their limits. + +The model, world diffuse and specular paths use the same physical lower fade. +In an occlusion field enlarged for specular range, the height is converted back +to the source radius before evaluating it. Without an occlusion field, a third +mask variant preserves that same physical height for larger or smaller specular +radii; equal radii reuse the diffuse variant. Directionality remains mandatory for +the AR, independent of optional wall occlusion or field-budget overflow. + +AR first-person intensity is now a per-view gain applied after the common +render-time fade. Previously the first-person target entered shared temporal +history and could brighten another view of the same weapon. A regression first +reproduced that leak, then verified both view orders without advancing time. +Single-view first-person and third-person tuning remains 1.0 and 0.65. + +Unchanged masks retain their cached volume textures across views. AR rotation +or a profile change invalidates both mask variants; translation and radius +changes update the transform without rebuilding normalized texels. The radial +Needler mask is also independent of weapon rotation. The eight-slot bound and +map/disable cleanup remain intact. Each reused variant avoids generating and +uploading 4096 texels. The visual fixture's `--face-camera` option permits front +views of hands/torso in addition to the earlier rear-facing holder views. diff --git a/docs/covenant_lighting.md b/docs/covenant_lighting.md new file mode 100644 index 0000000000..a8600e8aa8 --- /dev/null +++ b/docs/covenant_lighting.md @@ -0,0 +1,153 @@ +# Covenant projectile lighting + +The existing `display.plasma_lighting` option now includes supported Covenant +projectiles. It remains false by default. `display.plasma_occlusion` adds the +existing approximate collision visibility; it also remains false by default. +Muzzle lighting is independent. Shield illumination and persistent fuel-rod +weapon glow are not part of this change. + +## Coverage and map evidence + +Read-only inspection of Xbox map tag tables and weapon trigger references +established the following mappings. The campaign inventory covered a30, a50, +b30, b40, c10, c20, c40, d20 and d40; Blood Gulch and CE Death Island supplied +multiplayer comparisons. The inspected weapon references show Shade and +dropship guns using the same turret projectile, and Grunt/Hunter fuel-rod +weapons using the same fuel-rod projectile. No firing, damage, effects or map +tags are modified by this feature. + +| Source | Projectile tag | Lighting | +| --- | --- | --- | +| Needler | `weapons\needler\needle`, `weapons\needler\mp_needle` | Missing-light fallback: pink, radius 1.0 | +| Ghost | `vehicles\ghost\ghost bolt` | Authored radius x1.75 | +| Banshee plasma | `vehicles\banshee\banshee bolt` | Authored radius x1.75 | +| Banshee fuel rod | `vehicles\banshee\banshee fuel rod`, `vehicles\banshee\mp_banshee fuel rod` | Authored radius x2.75 | +| Shade/dropship | `vehicles\c gun turret\c gun turret` | Authored radius x2.5 | +| CE multiplayer Shade | `vehicles\c gun turret\mp gun turret` | Authored radius x2.0 | +| Grunt/Hunter fuel rod | `weapons\fuel rod gun\fuel rod` | Authored radius x2.75; greener flight illumination | +| CE fuel-rod cannon | `weapons\plasma_cannon\plasma_cannon` | Authored radius x2.75 | +| Wraith | `vehicles\wraith\wraith mortar` | Missing-light fallback: blue-violet, radius 3.5 | + +Stock Needler needles and Wraith mortars have no attached `ligh` in the +inspected maps. If a custom map supplies one for those exact tags, it takes +precedence: its colour/effects are preserved, with radius scales 1.5 and 1.75 +respectively, and no duplicate fallback is created. Unknown custom projectile +names remain stock. Grenades and non-Covenant projectiles are outside this +extension; the previously supported rockets are unchanged. + +## Implementation and isolation + +`port/linux/game/covenant_lighting.c` owns exact-tag policy and eight bounded +fallback slots. Existing authored attachments use `plasma_lighting.c` and its +soft diffuse/model/specular falloff. Light modulation and no-specular flags remain +authoritative. Authored colours are preserved except for the optional Grunt/Hunter +flight-light tint described below. Needler and Wraith fallbacks use the +existing glow bridge and rendered attachment pose, with no simulation updates. +Keep render interpolation enabled for smooth movement between ticks. + +`covenant_lighting_color` matches only the shared Grunt/Hunter projectile and its +`weapons\fuel rod gun\fuel rod exhaust` light. Read-only Xbox c40 inspection found +authored lower/upper RGB values of approximately (0.557, 1, 0.510) and +(0.678, 0.996, 0.447), producing a pale yellow-green. With Projectile Lights on, +the submitted render colour multiplies red by 0.30 and blue by 0.20; green and +authored modulation remain unchanged. The helper caches the light tag only until +the existing map/light-storage reset. Missing tags and unrelated attachments +retain their authored colour. CE's differently named cannon and Banshee shots +are not retinted. + +The minimal `port:` call in `lights_preprocess_scene` adjusts only the local submission +copy, used by world diffuse, model lighting and eligible specular passes. The +feature module cannot otherwise access that private render copy. It does not +write the light datum used by flares and simulation illumination queries, or +touch transient impact/explosion lights. Disabling the setting takes effect on +the next submission without colour restoration state. + +Fallback lights stay dark and disconnected between rendered frames. They are +released on disable, projectile deletion, modeled-object invisibility or leaving the 25-unit +camera range. Map unload, failed-load recovery and shutdown forget their +identities before the engine destroys light storage. Salted light handles and +owners are checked before reuse or deletion. Owned fallbacks bypass authored +radius save/restore so that cleanup cannot reconnect them into simulation. +Model-less projectiles remain eligible: the engine's `object_set_visibility` +cannot clear their invisible flag, including the stock particle-only Wraith mortar. + +Minimal `port:` additions in `source/objects/object_lights.c` wire preparation, +cleanup and visibility bounds. The feature module cannot independently run at +these private light-array and partition lifecycle points. All policy remains +in feature-owned modules. No Xbox, CE or MCC loading paths are replaced, and +there are no network payload or gameplay-rule changes requiring a network +version change. Stock trails, impacts, explosions and supercombine effects +remain under the original engine's control. + +The existing limits still apply: 128 authored attachments, eight rocket glows, +eight Covenant fallback glows and eight muzzle pulses. Only eight submitted +lights can receive approximate occlusion at once. Excess fallbacks keep stock +lighting; excess occlusion candidates keep unoccluded soft illumination. +Occlusion can leak at coarse edges and is not a shadow-map or stencil system. + +## Validation + +The 39-case Windows OpenGL capture matrix passed: all eleven projectile tag +variants above at 30, 60 and 120 FPS, plus disabled Needler controls and +32-needle capacity probes at each rate. Captures used hidden 640x480 windows +and were run serially on the local RTX 5070 Ti. Measured average rates across +those cases were: + +| Requested FPS | Measured range | +| --- | --- | +| 30 | 29.46-30.03 | +| 60 | 59.98-60.01 | +| 120 | 119.41-120.02 | + +Captured sequences were visually reviewed for every variant at every rate. +Enabled native-flight cases selected the expected tag and reached model lighting and +occlusion updates; disabled cases selected no feature lights and performed +no occlusion updates. Capacity probes admitted eight lights from 32 needles. +The 60/120 FPS traces show changing rendered projectile positions within +simulation ticks for every variant. Flight, homing, illumination and stock +impact effects remained consistent across the reviewed rates. This is bounded +automated visual coverage, not a full-resolution performance guarantee or a +complete campaign/vehicle combat acceptance pass. + +Additional 60 FPS stock controls for Ghost and Wraith shots selected no +feature lights or occlusion updates; paired captures retained the stock +projectile and impact effects. A real-firing Needler capture with both muzzle +and projectile lighting enabled sustained 119.99 FPS, submitted both light +types and recorded 132 intermediate muzzle fade samples. These three extra +captures also passed and were visually reviewed. + +The focused ownership, radius restoration, falloff, model shader, occlusion, +rocket and muzzle harness suite passes 46 tests. Negative controls verify +that missing reconnection and rejecting invisible particle-only projectiles +are detected. The light-storage bridge checks pass ordinary COFF and full +LTO builds, including the deliberate pointer-corruption negative control. + +A hidden two-instance Windows loopback test ran real Needler firing with +projectile lighting/occlusion enabled on the host and disabled on the client. +Both instances exited normally and each logged 29 network state reports. +All 29 matching ticks had identical complete player-state lines on both sides. +This is a local regression check, not an internet or long-session soak test. +No network implementation, payload or simulation rule changed. + +Two hidden map-transition passes loaded Xbox Blood Gulch, CE Death Island, +MCC Mercury Falling and Xbox Blood Gulch again: lighting disabled at 30 FPS +and enabled at 120 FPS. Both completed all three transitions, loaded the MCC +map once, exited normally and logged no exceptions. The enabled pass exercised +Needler lights before transitions. This checks lifecycle and map-family +boundaries on those maps; it does not establish full MCC gameplay compatibility. + +The visual fixture uses real projectile definitions with native flight, +collision, homing and impact effects. Separate held-projectile probes test +capacity. Campaign captures wait for the opening cinematic, then disable AI +attacks and make the player deathless to avoid invalidating the capture with +checkpoint reloads. These controls, forced input and capture instrumentation +are absent from the normal playtest executable. Early cinematic/reload captures +were rejected rather than counted as evidence. + +Windows portable release builds succeeded. Linux could not be built locally +(WSL is not installed); Android and web build attempts reported unavailable +Ninja targets/toolchains. Those platforms still require CI/device validation. +The normal executable passed a hidden OpenGL stock-settings smoke test and +contains no capture-fixture markers. The capture manifest's source hashes +match the implemented sources. Private test maps were removed; diagnostic +logs, reports and images remain under `build/`. diff --git a/docs/custom_edition_caches.md b/docs/custom_edition_caches.md index 76a91ceaca..6d4c792c56 100644 --- a/docs/custom_edition_caches.md +++ b/docs/custom_edition_caches.md @@ -15,6 +15,15 @@ the Xbox maps' are, before anything reads them ## Running a map +Load refusals name the map and explain known causes such as required OpenSauce +features, unreadable files, missing resources or the tag-cache limit. Later +conversion failures identify the failing stage, with detailed checks in +`debug.txt`. Precache failures retain the fatal media screen and later load +failures retain the existing fatal error path; clearer text does not add retry +or return-to-menu recovery. +If a startup command fails before the UI map has loaded, the existing fatal +path has no error widget to draw; the explanation is still written to the log. + Custom Edition maps run when the `game.custom_edition` setting is on, as it is by default (`custom_edition = true` under `[game]` in `config.toml`, or `HALO_CUSTOM_EDITION`). Put the maps and Custom Edition's `bitmaps.map`, @@ -243,7 +252,7 @@ changed: size of the one its Xbox counterpart draws (256×64 for 128×32, 512×512 for 256×256), with the same scale, and every unflagged one a bitmap of the same size ([Evidence](#observed-not-stated-by-the-sources-established-on-the-sample-maps)). - This build ignores the flag, so it drew them twice too large; the + The Xbox renderer ignores the flag, so it drew them twice too large; the placements of the unit, weapon and grenade HUD interfaces and the HUD globals' messages that have it get half their scale, and lose the flag (32 in `bloodgulch.map`). Halo PC reads the flag only on statics, meters and @@ -252,11 +261,14 @@ changed: digits', so a flagged number keeps the flag and `hud_draw_numbers` draws its digits at half their size, spaced as the digits tag says. A bitmap may ask the same of every element that draws it, with Halo PC's bitmap flags *half hud - scale* and *force hud use highres scale* (Invader's `bitmap.json`): an - element drawing such a bitmap (a static or meter, its bitmap after its - placement; a crosshair's or overlay's items, their crosshair's or - overlay's) gets half its scale too. None of the 18 Custom Edition maps on - hand, nor `bitmaps.map`, sets either. + scale* (bit 4) and *force hud use highres scale* (bit 7), documented in + Invader's `bitmap.json`. Placement high resolution OR bitmap force-highres + supplies one halving; bitmap half-scale supplies a separate halving. + Both bitmap flags therefore give quarter scale. Crosshair and overlay + items continue to ignore the placement flag. These bitmap flags were + absent from the original sample of 18 maps and its `bitmaps.map`. + [CE HUD scaling](reading/hud_corrections.md#custom-edition-authored-hd-scaling) + describes conversion, drawing and the preserved known-map exceptions. - **Maps made around Halo PC's own behaviour.** Chimera fixes Halo PC to draw as the Xbox does, and keeps a list of the maps made around Halo PC's way instead, by map name (in lower case) and tag data checksum, with the @@ -270,9 +282,11 @@ changed: number's digits drawn at half size (`hud_number_scale`), bitmaps' HUD scale flags cleared (`disable_bitmap_hud_scale_flags`), and model shaders' detail after reflection flag flipped (`invert_detail_after_reflection`). - Not yet: Halo PC's fixed-function meters (`gearbox_meters`), its + Partially supported: PC meter tint (`gearbox_meters`) and legacy warning + placement (`old_widescreen_fix`), described below. Not yet: the complete + fixed-function meter pipeline, its transparent chicago multiply, bump attenuation and environment shader - types, the old widescreen HUD and embedded Lua. + types, the remaining old widescreen HUD behavior and embedded Lua. - **The score hint.** String 100 of `ui\multiplayer_game_text` is Halo PC's `Hold "%s" for score`, which Halo PC fills in with its score key; this build copies it as it is (`game_engine.c`, the press-back-for-score @@ -281,6 +295,114 @@ changed: ### In the game (`custom_edition_cache.c`, `custom_edition_geometry.c`, `custom_edition_bitmaps.c`) +The High-Res HUD registers CE bitmaps after menus and before loose-tag mods, +using the same unload cleanup as Xbox maps. Compatible shared HUD redraws +are listed in `port/assets/hud/custom_edition.json`. The first mip's +dimensions, byte count and CRC in hardware order must also match: shared +`bitmaps.map` resources can contain custom artwork. Embedded custom sheets +retain their own pixels; placements, anchors, +offsets and sprite definitions are never rewritten by this replacement. +With High-Res HUD disabled, the original CE pixels remain authoritative. +Xbox registration and MCC's separate loading branch are unchanged. + +`tools/ce_hud_signatures.py ` records these fingerprints +for the existing layout allowlist without distributing game pixels. The +reference resource SHA-256 is recorded in the JSON (the two local copies +inspected matched). `ce_stock.json` inventories all 77 bitmaps in that +resource's `ui\hud\bitmaps` groups. Stock pieces without redraws, including +CE-only lettering and symbols, use the existing fourfold HUD interpolation +at runtime; custom pixels never qualify. Its compressed/512-pixel extension +in `xbox_textures.c` is necessary because only that renderer service can +decode those formats; it activates only for a verified CE stock sheet. + +`ce_layout.json` packs the OpenCE unit and ammunition meter redraws into +CE's different sprite arrangement. The recipe records source and destination +artwork bounds, not merely sprite rectangles: CE's internal padding differs. +For the full-size shield and health sprites, preserve the redraw's screen +coordinates relative to the top-right anchor instead of fitting the stock +pixel bounds. CE's half placement scale and different sprite padding require +translation only; stretching those shapes misaligns the separately drawn +background, most visibly at the health cross and shield emblem. +The reference was the stock CE resource above and Xbox Blood Gulch. The +generator (`python tools/ce_hud_assets.py build`) needs only committed OpenCE +redraws. Red categorical meter thresholds are resized with nearest sampling; +coverage and alpha remain filtered. No retail pixels are shipped. + +Stock crosshairs use the redraws where their normalized sprite layout agrees; +CE-only crosshairs use interpolation. Controller prompts use the existing +OpenCE button-style path when their CE controller definitions match stock. +The messaging sheet may contain custom weapon pictures: TSC, Snow Grove +and Bigass retain the stock controller entries but use those same sequence +numbers for weapons. Controller records are identified by their address in +the button array; weapon records continue to draw their authored pictures. +Embedded custom messaging sheets use a controller fallback even with +High-Res HUD off, because those sheets have no matching stock buttons. +When disabled, the original low-resolution controller sprites are read from +the shared `hud_msg_icons_sm` resource, including animated stick prompts. +The bounded reader accepts its stock two-image ARGB layout, preserves the +sprite frames, sizes the 20-pixel faces to the native 26-pixel gameplay size, +centers them on the active font's capitals with room for the adjacent text, +and releases the textures on +map unload. The selected button redraw style applies only when enabled. +Shared stock CE sheets retain the original low-resolution path when disabled. +Custom controller offsets/sequences stay authored. +HUD text still follows the separate High-Res Text setting. + +Custom meter sheets may also supply static artwork. Snow Grove's protected +HUD sheets and TSC Evolved Multiplayer's `default\vitals`, `default\visr_meter` +and `vehicles\vehicle_vitals` exercise this case. Such mixed-use sheets retain +their original channels in the texture cache. A CE meter draw now scopes a +shader conversion from `(R,G,B,A)` to `(A,A,A,R)`: the fill threshold is alpha, +and the shape is red. Ordinary draws of the same texture remain unchanged. +Already-converted meter textures and OpenCE replacements skip this conversion. +The scope ends immediately after drawing and is also cleared on texture-map +cleanup. Xbox and MCC do not enter it. No authored artwork, anchors, scales, +offsets or sprite rectangles are changed. + +The small `hud_draw.c` hook is needed to identify the current consumer; +load-time bitmap classification alone cannot distinguish these two uses. +The texture description and shader key carry that decision to the sample, +without changing the shared texture's upload or sampler state. + +For maps already identified by the name/checksum compatibility table as +depending on `gearbox_meters`, the meter's emitted color is no longer +multiplied by Xbox's `1-opacity` intensity. TSC's shield and ammo meters +have opacity 1, which otherwise turns their filled areas black. The +map's colors, threshold, empty color and fade remain in use. The public +[Chimera meter shader](https://github.com/SnowyMouse/chimera/blob/master/src/chimera/halo_data/shaders/pixel/hlsl/hud_meters.psh) +also omits that intensity multiplication. This is a targeted tint correction, +not a claim of implementing the entire PC fixed-function renderer. + +Bigass Open v1.1 (`bigass_open_v1.1`, tag checksum `D2BC19F7`) needs a +different ammo-sheet interpretation from Bigass v3 (`852EE757`). Inspection +of `bourrin\hud\v3\bitmaps\all icons wips` shows that Open's twelve weapon +meter sequences keep their thin shapes in alpha and fill progression in +color, whereas v3 keeps those channels reversed. The local compatibility +entry marks only this sheet as explicitly Xbox-ordered; that identity +survives static-icon use and suppresses the per-draw CE channel swap. +Other meter sheets retain their existing interpretation. The classification +is rebuilt with the map and cleared on bitmap disposal, including failed +loads. No pixel data or HUD placements are edited. + +Both revisions use the same `iris italic` HUD-number metrics +`(16,14,0,0,6,7)` and half-scale digit placements. Open's entry also enables +the existing `hud_number_scale` conversion, producing `(8,7,0,0,3,4)` so +the current-magazine and reserve digits advance consistently with their +drawn size. These corrections apply with High-Res HUD on or off and are +matched by both map name and tag checksum; unrelated CE, Xbox and MCC +maps do not acquire them. No unrelated v3 shader or Lua flags are inherited. + +CE warning crosshair states (ammo, heat and reload) draw in HUD coordinates, +without the FOV or passenger-camera transform used by aiming reticles. +For `old_widescreen_fix` maps, nonzero warning offsets also retain +their distance from the corresponding edge of the authored 640x480 canvas, +accounting for PC's 8-pixel HUD margins and OpenCE's current title-safe frame. +Snow Grove places its low/reload warnings this way beside its ammo panel; +their bitmap scale and animation remain authored, and offsets translate +with the panel rather than being scaled toward the aiming point. +The draw uses a placement copy, without modifying the loaded tags. Xbox and +MCC retain their existing crosshair drawing and meter tint behavior. + - **Models.** Every `mod2` part is given this build's part layout (the first 0x68 bytes of the 0x84-byte Custom Edition part are the same fields; the parts are repacked in place), its vertices are compressed from the map's @@ -302,14 +424,27 @@ changed: - **Bitmaps.** Every bitmap must pass the game's own `bitmap_verify` and be of a kind the texture cache and the swizzling code handle (a format with a hardware texture, a compressed flag that agrees with the format, - power-of-two sizes unless linear, square cube maps, all its pixels - present). Halo PC draws a 2D bitmap of any size, so an uncompressed one + power-of-two sizes unless linear or the bounded DXT case below, square + cube maps, all its pixels present). Halo PC draws a 2D bitmap of any size, + so an uncompressed one whose sides are not powers of two is made linear as the map loads, and drawn from its first level (birdcage-plus's 3840 by 64 needler plasma). Its pixels are laid out for Halo PC, levels as the tag stores them, unswizzled; as they arrive, the game's own `rasterizer_xbox_bitmap_rebuild_hardware_format` lays them out as an Xbox cache would (swizzled, cube maps face by face, padded). + Non-power-of-two DXT1/3/5 2D bitmaps are also supported when both sides + are multiples of four, no larger than 4096, depth is one and there are + no mip levels beyond the base level. These retain their compressed blocks + without rebuilding. The port's descriptor extension records exact sides + in the Size word while keeping normalized texture coordinates. Admission + still checks the compressed flag and required pixel bytes; other + non-power-of-two compressed, cube, volume and P8 layouts remain refused. + The extension requires ownership by the loaded CE tag cache and is disabled + while MCC tags are loaded; Xbox and MCC descriptors retain their own paths. + `tools/test_ce_npot_bitmaps.py` exercises the real admission and descriptor + functions with synthetic 200 by 112 textures, malformed layouts and legacy + cases. It does not establish that an entire custom map or authored UI works. - **Chicago extra layers.** January's transparent chicago shader draws its extra layers in a loop that never advances (`rasterizer_xbox_transparent_geometry.c`, marked as a preserved bug). No @@ -335,7 +470,9 @@ changed: which leaves them compressed). A bitmap also drawn another way (a multipurpose map that is also a base map, say) keeps its channels, since the renderer has one order for each texture, and is logged: 3 in - `bloodgulch.map`, all multipurpose maps. + `bloodgulch.map`, all multipurpose maps. Mixed-use CE HUD meter sheets + instead select meter channels in the shader for that draw, as described + above; their ordinary artwork still reads the original channels. - **Reads.** The renderer write-protects the memory it has made textures of and learns of changes from the faults writes take; the kernel fails a read into such memory instead. Every read of the map is therefore made into a diff --git a/docs/damage_and_shader_cache_fixes.md b/docs/damage_and_shader_cache_fixes.md new file mode 100644 index 0000000000..142dd98d6b --- /dev/null +++ b/docs/damage_and_shader_cache_fixes.md @@ -0,0 +1,161 @@ +# Projectile owner lifetime and shader cache follow-up + +This follows the [collision optimisation investigation](dynamic_lighting_tracing.md). +The scope is two existing-engine defects: a stale damage-owner lookup, then +redundant compilation of byte-identical fragment shader sources. Lighting +settings/defaults, visual equations, host policy and Xbox/CE/MCC loading paths +must remain unchanged. + +## Projectile-damage crash + +Both original failures assert that an object datum is "unused or changed": +`0x8107004a` in the disabled control and `0x8e8b0048` in the enabled control. +The subsequent null dereference is in `object_get_and_verify_type`, reached +from `object_cause_damage`'s gametype multiplier lookup. In +`get_player_index_from_object_or_parents`, a failed `unit_try_and_get` was +followed by a strict `object_get` on the same handle. + +The engine permits a projectile to outlive its owner. Its deleted-object +handler clears a homing target but does not retire the owner handle. The +damage structure also carries player/team ownership separately. Therefore the +fix checks the object before following its parent and returns `NONE` if it no +longer exists, rather than erasing ownership or suppressing damage. Datum +generation checking prevents a reused slot from being treated as the old +owner. Valid units and parent chains retain their original results. + +This is a general object-lifetime defect reproduced on an Xbox multiplayer +map with lighting off and on, not an adaptation to MCC data. Only this lookup +in `source/objects/damage.c` changes; it carries a `port:` comment. Host damage +admission still precedes calculation. No wire format, prediction rule or +valid-input damage calculation changes, so the pinned OpenCE and MCC network +versions remain unchanged. A departed player's separate damage attribution +still follows the existing validation and network rules. + +The combined owner-lookup, stale-player-damage and MCC-damage harness run passed +52 cases, including negative controls that restore the strict lookup and fail +on deleted/reused objects and missing parents. The normal Windows release +build passed. Twenty protocol/admission checks also passed. Two hidden +six-minute measured Carousel combat runs with 15 Heroic bots completed normally, +with lighting off/on respectively. A test-only diagnostic detected no retired +owner encounters in those particular runs: they are stability evidence, while +the harness supplies the deterministic stale-owner regression. They ran together +at 640x480/30 FPS and are not performance benchmarks. No diagnostic logging is +present in the normal build. +The damage commit's [four-platform CI](https://github.com/chestahh/GulchCE/actions/runs/40254648830) +and [MCC validation](https://github.com/chestahh/GulchCE/actions/runs/40254648722) +passed. + +## Fragment shader duplication + +The full-state key remains unchanged. On its miss, the existing translator +still generates the exact same GLSL; `fragment_source_get` in `d3d8_gl.c` hashes +the bytes and compares the complete string before sharing a compiled shader. +This fixes a shared renderer cache inefficiency already demonstrated with +dynamic lighting disabled, not an MCC compatibility requirement. No map-family +adapter or shader translator is changed. The shared backend owns the GL objects, +so this general renderer fix belongs there rather than in a lighting module. + +The source entry owns the generated string and shader result for the existing +GL context lifetime. Key entries reference the shader ID, and the unchanged +program cache can reuse links for identical vertex/fragment pairs. Per-program +uniform state and serial tracking remain unchanged. Failed compilation stays +cached; failed cache allocation falls back to the original per-key ownership. +Map unloads retain these context resources, with no map/tag pointers retained. +The existing device is created once, and `D3DDevice_Release` does not destroy it; +this change does not introduce or claim context-recreation support. + +The new harness compiles the actual source/full-key cache functions and covers +identical versus different/prefix sources, forced hash collisions, recent-key +eviction, source ownership, compilation failure and allocation failure. Fourteen +tests passed, including deliberately broken equality/sharing controls. The +normal Windows build passed. Diagnostic resource CSVs now distinguish full-key +entries (`fragments`) from unique source entries and their retained string bytes; +key-entry counts alone no longer represent compiled fragment-object counts. + +The AMD/NVIDIA visibility implementation was reviewed separately. AMD's CPU-only +query readback, typed query pool, buffer binding restoration, NVIDIA's buffered +delivery, delayed fences and post-swap nonblocking polling are unchanged. Their +30 contract/harness tests passed before the cache change and in the combined +128-test final regression run (30.37 seconds). That run also covers damage, +protocol/admission, shader sharing, occlusion binding/reprojection and model +shader translation. Source comparison confirms the visibility functions, +compile/link functions, `program_get`, `prepare_draw`, presentation and shader +translators remain unchanged. No new AMD hardware run is available; GPU runtime +observations here use the NVIDIA RTX 5070 Ti. + +## Real-renderer cache checks + +Two isolated 180-second measured Carousel runs (30-second warm-up, 15 Heroic +bots, 640x480/30 FPS) completed normally with no detected runtime errors. They +ran concurrently to check correctness/resource counts, not comparative FPS or +memory cost. GLSL dumping replaced screenshot readback in these diagnostics. + +| Lighting | Full-state keys | Distinct fragment sources | Duplicate compilations avoided | Linked programs | Retained source bytes | +| --- | ---: | ---: | ---: | ---: | ---: | +| Off | 466 | 64 | 402 (86.3%) | 82 | 381,681 | +| On | 538 | 65 | 473 (87.9%) | 85 | 386,104 | + +Counts are the final samples, including warm-up/shutdown margins. Independent +SHA-256 grouping of every dumped fragment source exactly matched the source +cache counts, and file counts matched full-state entries. Each distinct source +is compiled once; key aliases reuse that object. Percentages describe avoided +fragment compilation/object duplication in these runs, not FPS or memory savings. +The new source strings occupy about 0.36-0.37 MiB. The previous diagnostic +compiled one object per key; its different workload/resolution prevents an +honest before/after process-memory or program-count percentage claim. + +This repairs the confirmed duplication, but does not prove a steady-state +memory plateau or attribute every remaining allocation. Vertex shaders and +other retained renderer resources remain outside this focused change. + +## Combined validation + +The shader commit's [four-platform workflow](https://github.com/chestahh/GulchCE/actions/runs/40255510975) +passed Windows, Linux, Android and web builds and configured tests; its +[MCC workflow](https://github.com/chestahh/GulchCE/actions/runs/40255510976) passed. +Android/web builds were performed in CI, not represented as local hardware runs. + +Nine final visual cases passed their runtime checks. Contact sheets were +inspected for crouched Needler holders at 30 FPS, a shorter Grunt and +first-person AR at 60, Warthog and shield charge/depletion at 120, a moving door +at 60, and disabled/vertex-lit/CE controls at 60. No new visual regression was +observed in these samples. They are 640x480 still captures, not every case at +every cap, continuous animation review, or full campaign/material coverage. + +Xbox c40 -> MCC Mercury Falling -> CE Death Island -> Xbox Blood Gulch +completed with lighting off at 30 FPS and on at 120 FPS. Each sequence logged +all requested map loads and exited normally without exceptions. These are +bounded render/lifecycle checks rather than proof of full map compatibility. + +A normal-build two-player Windows loopback session also exited normally, with +36 host and 32 client two-player snapshots, eight scripted firing events per +peer and no detected runtime errors. Other lighting was enabled on the host +and disabled on the client; the host requested `glow_overshield` while the +client's local policy was `stock`. This supplements the unchanged policy and +admission tests, not internet crossplay or comprehensive co-op validation. + +The combined review covered the complete damage lookup, source cache, +integration, diagnostics, tests and documentation. No broader refactoring was +needed. Host policy, optional lighting defaults, shader equations, AMD/NVIDIA +query delivery and map-family loading/conversion remain unchanged. These fixes +do not by themselves establish locked 120 FPS or finish the 1.0 performance +acceptance milestone. + +All recorded production source hashes matched the restored sources, and the +normal Windows binary contains neither damage-owner logging nor capture/timing +fixtures. No owned game processes remain. Cleanup removed temporary maps and +generated caches after runs and another 63,314,236 bytes of diagnostic binaries +and fixture objects at completion. All 332 archived test-save files +(356,663,960 bytes uncompressed) were verified against their SHA-256 manifests. +About 55 MiB of diagnostic evidence remains; original maps/saves, toolchains +and the normal Windows build were preserved. + +Local evidence includes `build/damage-owner-runtime.json`, +`build/shader-cache-runtime.json`, `build/shader-cache-counts.json`, +`build/shader-cache-final-visual.json`, the transition/network report folders, +`build/damage-shader-final-regression.log` and `build/damage-shader-cleanup.json`. +Retail data/captures are not committed. No further endurance rerun was queued. + +The subsequent approved [20-minute stability check](dynamic_lighting_stability.md) +records sustained 30/60 FPS, the remaining 120 FPS shortfall and bounded +process-memory observations on this unchanged implementation. diff --git a/docs/digsite_projectile_offsets.md b/docs/digsite_projectile_offsets.md new file mode 100644 index 0000000000..a550367123 --- /dev/null +++ b/docs/digsite_projectile_offsets.md @@ -0,0 +1,209 @@ +# MCC camera-relative projectile rays + +The user-provided native MCC screenshot and video establish the required muzzle +alignment. The user accepted the grounded Prisoner control capture on 11 November +2026. That run used commit `075043861`'s camera-relative firing calculation with +the experimental trail adjustment explicitly disabled. The delivered implementation +retains that calculation and removes the visual experiment and runtime probes. +Passing builds alone were not used to accept the alignment. + +Digsite multiplayer exposed a mismatch between the original Xbox firing +calculation and MCC camera-relative triggers. This fix follows trigger semantics, +not map names, weapon names, tag paths or checksums. Original map files are unchanged. + +## Observed behavior and intended result + +At stock FOV, the Sentinel Beam fired above the crosshair when looking down, +with a visible gap between the muzzle and beam. The Rocket Launcher also had +an offset spawn. The intended result is an offset projectile converging on +the surface under the crosshair, with authored spread and aim assistance +retained and nearby cover still blocking shots. + +The initial investigation on main `9d8aa9411` found: + +- In Digsite Albatross, the support animation class limits unit aim to 70 + degrees, while the player view reaches 85.5 degrees. The Sentinel uses + that class. The Rocket reaches the requested angle and does not share + the Sentinel clamp. +- The original ray projects the animated world muzzle onto unit aim, then + applies the trigger offset. The subsequent spawn-safety trace includes + the player, pulling the resulting spawn back towards the eye. +- Original aim assistance limits the final adjustment to its deviation cone. + That also limits close-range convergence from an offset spawn; a weapon + with zero autoaim can retain an off-centre parallel firing line. + +A read-only audit of all 75 installed Digsite MP maps (Workshop package +`3477809506`) found the same offsets and trigger flags in all 150 relevant +triggers. Sentinel uses `(0.15, -0.15, -0.15)` and `0x2000`; Rocket uses +`(0, -0.10, 0)` and `0x2008`. The animation-class audit was of Albatross, +not all 75 maps. Neither trigger selects weapon origin (`0x20`) or the +MCC original-ray flag (`0x4000`). + +The public [c20 weapon reference](https://c20.reclaimers.net/h1/tags/object/item/weapon/) +documents that MCC normally uses newer ray handling, with bit 14 selecting +original Halo behavior. It does not specify the replacement algorithm. +This implementation independently meets the player aiming contract; it is +not a claim of exact native MCC algorithm equivalence. No proprietary +source or SDK headers were used. The user supplied a native MCC screenshot +and video as visual references; no separate native MCC test session was run. +The user confirmed that beam instability during erratic aim is native behavior. +The fix must preserve that behavior and is limited to alignment and offsets. + +## Controlled follow-up + +The earlier desired-direction substitution was not a direction-only control: +it also changed the offset basis and left other calculations inconsistent. +Shooter collision established relocation, but did not alone prove the cause +of the visible gap. Those limitations motivated a fixed-position follow-up. + +Hidden Windows tests fixed player position and facing, equipped the named +weapon, and recorded ray stages. Original firing, coherent aim adjustment, +owner exclusion and their combination were checked separately. Neither aim +nor owner exclusion alone produced the complete correction. Camera-relative +placement with crosshair convergence corrected the impact position. +Six equipped Rocket shots were measured per run; deathless test setup kept +the weapon available instead of attributing respawn shots to it. + +The implemented ray was exercised on Albatross at level, -45-degree and +-85.5-degree aim: 227, 227 and 218 Sentinel shots respectively, and six Rocket +shots at each angle. A further 227 Sentinel shots used world/viewmodel FOV +110/90. Selected 2560x1440 captures establish crosshair convergence. These are +controlled local tests, not complete map playthroughs. + +Muzzle review rejected the earlier Albatross captures and bare-marker trail warp. +A read-only firing-effect audit found an authored first-person particle offset of +`(-0.01, 0.004, 0.03)` from the trigger marker. An additional experiment aligned +initial trail points to that emitter, but the controlled comparison did not justify +retaining this new rendering behavior. + +The accepted capture is +`build/projectile-validation/sentinel-prisoner-control/captures/frame01034.png` +(lossless PNG; the user-reviewed original BMP is also retained). It was captured at 2560x1440, +stock world/viewmodel FOV, with the player grounded at `(7.586, -2.646, -0.408)`, +facing 180 degrees at level pitch. The fixture placed the player once and then +allowed normal physics. `DIGSITE_PROBE_DISABLE_VISUAL=1` bypassed the experimental +trail adjustment. The user explicitly confirmed this control looked correct. +That establishes acceptance of this visible case; it does not establish why each +earlier Albatross frame looked wrong or prove every map/pose combination. + +All visual experiments were removed. The fix uses the authored trigger offset; +it does not derive a projectile origin from flash particles, retune content +offsets, attach trails to later weapon poses, or alter trail timing and fading. +Native beam instability during erratic aim is preserved. + +## Implementation and reading route + +1. [mcc_projectiles.c](../port/linux/game/mcc_projectiles.c), + `mcc_projectile_ray`, owns activation, offset placement, cover checks, + aim assistance and convergence. It uses the unit's simulation-owned + desired aim, never local rendering matrices or viewmodel FOV. +2. [aim_assist.c](../source/game/aim_assist.c), + `player_get_aim_assist_target`, exposes existing target selection and + authored zoom rules without invoking the original ray adjustment. +3. [weapons.c](../source/items/weapons.c), `trigger_create_projectiles`, + calls the MCC ray before spread, distribution and projectile creation. + `weapon_get_projectile_ray` queries the same calculation without recording + aim-assist state. The original implementations remain the fallback. +4. [third_person_weapon.c](../port/linux/game/third_person_weapon.c), + `third_person_muzzle_target`, queries the same nominal MCC ray before + applying its existing shoulder muzzle/cover calculation. + +The authored offset is relative to the camera's aim basis. The camera-to-spawn +segment is checked against cover, excluding the on-foot shooter. A blocked +spawn remains just on the camera side of the surface, before attachments emit +their first point. Aim assistance acts in camera space; the shot then converges +from that checked spawn to the first surface on the camera ray. A target +behind the spawn cannot reverse the shot. The post-creation safety check +continues to exclude the owner for this validated MCC path. + +The shared hooks are necessary because the engine owns firing, preview and +object creation; no existing hook can replace this complete pre-spread ray. +The small aim-assist query avoids duplicating target selection or altering +legacy aim-assist calculations. All compatibility decisions stay in the MCC +module. There is no retained ray state, allocation or cached tag pointer: +unload, failed-load and family transitions use the existing MCC loaded guard. + +The original-ray flag, cannot-aim/weapon-origin triggers, non-player units, +seated units, gunners, dead units, units without camera firing and authored +following cameras retain the existing path. Xbox and Custom Edition return +before any ray output or shot bookkeeping changes. Animation limits remain +unchanged. This is required content interpretation, not an optional FOV fix. + +## Networking + +The calculation changes simulation agreement, without adding packet fields +or accepting client-provided origins. MCC protocol advances from 64 to 65; +MCC shoulder sessions advance from 32713 to 32714. Ordinary Xbox/CE protocol +41 and their shoulder agreement 32712 remain unchanged. Admission tests +reject older MCC versions. See [NETCODE.md](../port/linux/NETCODE.md). + +## Validation and limits + +The asset-free tests in [test_mcc_projectiles.py](../tools/test_mcc_projectiles.py) +compile the actual module and target-query functions. They cover pitch/yaw, +vertical aim, offset placement, close cover, owner exclusion, no reversed +shots, aim assistance, zoom rules, inherited velocity, preview bookkeeping, +activation exclusions and loaded/unloaded transitions. They require no +content identity or retail assets. + +Checks on the camera-relative implementation (the discarded render experiment +is excluded): + +- Windows release build passed. Temporary runtime probes were removed, the + affected objects rebuilt, and the executable checked for probe strings. +- Full web compilation and linking passed using equivalent Python copy/SDL + preparation steps for generated recipes that require a POSIX shell. +- All six affected C translation units compiled for Android's ILP32 guest. + Full Android building stopped at POSIX shell recipes unavailable on this + Windows host; full Android linking and device behavior remain unverified. +- 74 focused regression tests passed; the POSIX socket harness was skipped + on Windows. All 36 web JavaScript tests passed. Coverage includes admission + rejection of old MCC protocols and the third-person MCC preview route. +- Xbox Blood Gulch and MCC Albatross host/client runs passed the existing + `net_compare` tolerances with both host assignments. Final runs repeated + both families on the clean executable, comparing 28 seconds each. Xbox had + zero divergent simulation ticks; MCC had 13/840, maximum 0.045020 world + units, within the comparison tolerances. This is not perfect determinism. +- The browser/native WebRTC harness failed before compilation because its + URL-to-path handling produces `C:\C:\...` on Windows. Browser internet + gameplay also requires unavailable POSIX tooling; neither is claimed as + validated. Linux execution and real Custom Edition gameplay were unavailable. + +Self-review covered the complete implementation, shared hook boundaries, +protocol isolation, documentation and tests. It added coverage for the +third-person preview integration and removed all test probes and the unproven +trail warp. The final alignment-only pass repeated the 74-test selection, +Windows and web builds, and six affected Android guest object compilations. +The simulation module differs from the previously network-tested candidate +only in its introductory comment. No retained state or content-specific +selector was needed. Full map playthroughs and real map-family transition playtests are not claimed; +automated guards and lifecycle tests are distinct from those runtime checks. + +Local evidence lives under `build/digsite-evidence` and +`build/projectile-validation`: original and follow-up logs, settings, captures, +probe patches and runners. Temporary probes are removed from delivered code. +Only this assignment's copied maps, generated caches and disposable test +outputs are cleaned; originals, user saves and toolchains are preserved. +Inactive test saves were archived with original paths and verified SHA-256 +hashes before removing loose copies. The follow-up removed approximately 9.7 GiB of disposable captures, map caches +and verified staged map copies. Approximately 226 MiB of validation evidence +remains, including the accepted capture, settings, logs, experimental source +snapshots and verified archives of inactive test saves. Original assets and +user saves were not changed. + +The final follow-up reviewed the combined engine change and removed the second +visual experiment and all runtime probes. Source files match `075043861`; the +remaining follow-up change records the accepted control and validation. The +clean Windows executable was checked for probe strings. The 74-test selection +passed again (one POSIX-dependent test skipped), Windows and full web builds +passed, and all six affected wasm translation units compiled. Earlier Android +object and host/client results apply to the identical retained engine sources; +full Android, Linux and browser/native internet validation remain limited as +described above. No new CI run or upstream publication was performed. + +## Refactor branch integration + +This branch retains shared protocol 32738 and Xbox/CE shoulder agreement 32740. +MCC agreement advances 72 to 73, and MCC shoulder agreement 32741 to 32742. +The older agreement numbers above describe the original testing-branch validation. +The integrated projectile, protocol and shoulder regression selection passes 36 tests. diff --git a/docs/dynamic_emitter_expansion_acceptance.md b/docs/dynamic_emitter_expansion_acceptance.md new file mode 100644 index 0000000000..130d7a1196 --- /dev/null +++ b/docs/dynamic_emitter_expansion_acceptance.md @@ -0,0 +1,809 @@ +# Energy, vehicle and world lighting: local validation + +This records the `dynamic-emitter-expansion` work based on testing commit +`0bc618eac6a4d22630a4e74fa3b606fe780e8df7`. It does not replace the historical +1.0 acceptance or certify every device or custom map. The +[implementation guide](reading/emitter_expansion.md) explains the profiles, +controls, reading route and lifecycle. + +**The current target is sustained 240+ FPS in busy combat; acceptance remains +open.** The earlier 120 FPS investigation below is historical evidence, not +acceptance against the new target. The November optimisation section records +the follow-up work from commit `0973085ab3a7110e758bc41d77ffba622ff02571`. + +## Implemented scope + +- Elite energy swords; projectile plasma grenades; held plasma-pistol + charge and plasma-weapon heat lights reuse their authored attachments. +- Ghost, Banshee and Covenant dropship engine/running illumination, plus + Warthog and Scorpion headlights. Vehicle sources request chassis blocking + even with general Light Occlusion off. +- Flamethrower streams use one bounded, smoothed sample per firing owner. +- Visible overshield/active-camouflage pickups and the green teleporter + surface cast local light. Collected pickups and unlit teleporter bases do not. +- Both settings frontends group Weapon Glow and Shield Emitters, add Vehicle + Lights and World Emitters, and retain the separate projectile, muzzle, + occlusion and host-governed Shield Glow controls. Old individual preferences + remain supported; mixed groups display CUSTOM without overwriting them. + +All new settings default off. Stock models, particles, explosions, damage, +vehicle controls and network simulation remain unchanged. Android excludes +the feature modules and uses inert hooks. No shader translator, shader-cache, +AMD/NVIDIA workaround or map-family loader was changed. + +## Review and optimisation + +The combined review covered the new modules, existing emitter pool, +attachment restoration, occlusion registration, menus, generators, platform +stubs, fixtures and documentation. An additional game-source argument +exposes the private light-definition identity at the existing render hook; +the rationale is in the implementation guide. Feature policy stays in port +modules, and that source change retains its `port:` marker. + +Exact tag identities are cached for the current map. Enabled categories +restrict object scans; a projectile-only configuration with no live flame +stream skips the emitter-owner walk. Flame grouping and ambient lights remain +bounded, with no new independent GPU pass or increased emitter budget. An +existing held-weapon/shield emitter can reclaim the weakest ambient slot when +the shared pool fills, preventing the additions from starving baseline lights. +The saturation regression also checks that stable lights are not recreated. + +The review corrected a broader-than-needed menu-save fallback, regenerated +the optional frontend's stale settings page, and retained all existing shader +and compatibility checks. Shared changes target measured costs; unrelated +renderer cleanup and future shadow features remain outside this change. + +### CPU/GPU investigation + +At 2560x1440, 8x MSAA, 16x anisotropic filtering and highest model detail, +the initial 15-bot Blood Gulch comparison measured 30.00/59.97/113.81 FPS +at the three caps with lighting on, and 120.00 FPS at the 120 cap with it off. +These were 60-second measurements after 15 seconds of warmup, without +screenshot readback. They establish a local shortfall, not a device-wide limit. + +Sampled profiling attributed about 2.07 ms per frame to collision batches, +0.71 ms to visibility projection/filtering, and 0.42 ms to texture preparation. +Sampled GPU draws totalled about 1.38 ms. These diagnostics have overhead; +nested CPU timings must not be summed. GPU draw queries do not cover resolves, +presentation or every driver wait. World BSP queries dominated the collision +cost, making CPU-side lighting the primary measured optimisation target. + +The current candidates retain ray count, update cadence, filtering and light +budgets. Lighting proves a common collision-tree prefix for a ray cube and +passes that entry to the existing traversal. A bounded 8 KiB batch cache +reuses node/plane data for the identical BSP and origin. Stock callers still +enter at the root with no cache. Original traversal depth and node budgets +include the skipped prefix. A same-pose comparison of 34,913,280 rays found +zero differences against stock or uncached batches; cached batches took +8.53 seconds cumulatively versus 9.38 seconds without that node cache. +That is a batch cost comparison, not a whole-frame FPS improvement. + +Unchanged lighting texels reuse the last successful upload, checked byte for +byte. This uses a fixed 384 KiB across all fields and skips memory watching, +texture decoding and GPU upload only when the result is identical. A failed +upload invalidates that copy. Lighting also caches its local boolean options +until `config_changes()` advances, avoiding repeated locks and full settings +table searches. Host policy remains independently evaluated. + +Successful pass textures also survive between views when all texel inputs +remain identical. Rotation invalidates directional profiles independently. +The disabled reset path does not repeatedly clear already-empty field storage. +A proposed early trace-refresh scheduler was removed: its combat measurement +did not demonstrate a gain, so the original refresh cadence remains intact. + +The resulting build measured 30.00/60.00/118.10 FPS at the respective caps. +A separate three-minute run with the limiter explicitly disabled measured +140.12 FPS overall, with minute averages of 142.46/145.19/132.70. Its p95/p99 +frame times were 10.40/12.49 ms, worst 27.96 ms, with no frames over 50 ms. +This establishes local average headroom, not a locked 120 FPS or universal +hardware acceptance. Combat evolves between runs; timings are not a +deterministic replay or an exact causal percentage improvement. +A later disabled 120-cap control averaged 114.55 FPS and contained twelve +frames over 50 ms, whereas the initial disabled control held 120.00. Its cold +shader-cache log and timing record are retained; the cause of those stalls was +not established. They are not silently discarded or attributed to lighting. + +Benchmark correction: early `*-headroom` reports used `max_fps=0`, which +means twice the display refresh rate. Their `uncapped` flag was incorrect. +They remain preserved with a correction record and are not used as unlimited +measurements. `emitter-unlimited-final` explicitly records `frame_limit=-1`. +The runner now records the actual limiter and bounds memory windows before +shutdown, avoiding a false plateau from exit-time deallocation. + +The corrected unlimited pre-optimisation comparison averaged 120.94 FPS over +one minute (p95/p99 13.68/16.45 ms). The final run's frames over 8.33 ms averaged +61 selected lights and 2.99 ms of occlusion work, versus 32 lights and 1.67 ms +within budget. This correlation points to crowded-light frames for further +profiling, rather than a blanket GPU rewrite or reducing light quality. +Frames with a simulation tick were slower on average, but render-only frames +also exceeded budget. Bounded process-memory windows averaged 657.28 then +659.03 MiB during the final run; this small increase is not proof of a plateau. + +## Automated and menu checks + +The final focused suite passed **150 tests**, with **one platform-dependent +skip**. It exercised production profile matching, map cache invalidation, +missing assets, frame restoration, split views, allocation limits, flame +aggregation, emitter priority, vehicle occlusion, stock shader/GPU isolation, +host shield policy, generated menus, Android exclusion and MCC shader checks. +These are code-level checks, not hardware or whole-map compatibility proof. + +Windows builds passed. The touch-menu C unit also passed with the installed +toolchain's explicit x86 target; its generic pytest command attempts to link +Unix `libm` on Windows and fails before running the unit. +Final ordinary/full-LTO light-storage checks also passed, including the +intentional pointer-corruption negative control. The final document/source +audit checked 185 local links and 95 recorded source hashes; the normal binary +contains no capture, policy-probe or trace-comparison fixture identifiers. + +Hidden real-game menu checks verified fresh defaults, every consolidated +control, Save, Cancel, Defaults followed by Cancel/Save, process restart, +unchanged CUSTOM values and independent weapon/shield groups. The classic +screen was inspected at 640x480 and the optional GulchCE frontend at 1280x720. +The latter also passed grouped Save, Cancel, Defaults and restart checks. +The production executable was checked for absence of capture/profiling +fixture identifiers. +After the settings-cache change, Save, Cancel, Defaults and process restart +were refreshed successfully in the real classic menu. A supported projectile +probe repeatedly toggled occlusion at runtime and verified that disabled +intervals performed no occlusion updates. + +## Rendered coverage + +Captures used one hidden Windows instance, an NVIDIA RTX 5070 Ti with driver +617.42, per-pixel lighting and 1280x720 output. Xbox Blood Gulch/c40, CE Death +Island and MCC DigsiteMP were exercised at 30, 60 and 120 FPS caps. Real object +attachments, enhanced model draws and occlusion submissions were logged; +representative frames were visually reviewed. Test fixtures are not shipped. + +The cases covered sword-bearing Elites, plasma grenades, held charge/heat, +Ghost/Banshee/dropship sources, both headlight vehicles, both powerups, +teleporter scenery and Xbox/CE flame streams. Off controls for the new groups +selected no enhanced lights and made no optional occlusion updates. + +Two capture limitations are retained rather than counted as passes: + +- An ordinary MCC grenade placement disappeared on its first simulation + update in a narrow doorway and never submitted a visible light. Controlled + nearby grenade probes rendered correctly at all three caps. Those probes + freeze projectile simulation: they validate rendering, not MCC throwing, + sticking or detonation gameplay. Xbox natural-projectile captures provide + separate flight/impact coverage. +- An initial 60-cap Banshee capture averaged 54.94 FPS. Its focused repeat + averaged 58.93, versus 60.00 disabled. The original hitch remains recorded. + The earlier 60-cap plasma-rifle heat capture also missed its timing target; + a visible effect is not evidence of sustained performance. + +One MCC pickup run reached the short exit deadline before the fixture began. +The runner now allows package loading more time while preserving the same +85..240-tick measurement window; incomplete runs remain failed records. + +Final optimisation checks refreshed CE Ghost and MCC pickup captures at all +three caps, Xbox held-AR captures at 30/120 and rotating first-person AR at 60, +plus a campaign Grunt/Needler case at 60. Representative images were inspected; +these short captures met the runner's 5% timing tolerance. Three final ray +comparisons covered 924,672 CE, 465,408 MCC and 370,176 campaign Xbox rays with +zero differences from both stock and uncached traversal. + +Invalid fixture combinations remain recorded as failures: Blood Gulch lacks +the requested Marine/Grunt actor tags, so supported player/campaign fixtures +replaced those attempts. The held-weapon tick handler also never executed the +projectile toggle control. The runner now rejects that combination before +launching; separate rotation and projectile-toggle runs passed. These setup +failures are not treated as valid effect or lifecycle coverage. + +## Platform and acceptance limits + +Refreshed two-instance Xbox, CE and MCC local compatibility runs passed with +differing lighting preferences, joining, respawning, weapon changes and host +policy on the final implementation. The comparator found no divergences over +81 paired snapshot seconds for Xbox/CE and 74 for MCC. This is local transport +and representative-map coverage, not an internet or full-campaign run. + +Full `ninja android` and `ninja web` were refreshed with the installed NDK and +Emscripten outside the sandbox. Unix shell operators were passed literally to +helper executables; the web build also encountered its Python launcher setup. +A targeted web-object attempt still stopped at the SDL shell prerequisite. +The normal Windows configuration was restored. WSL is not installed. +Build-graph, inert-hook, menu and shader isolation tests +passed, but full Linux/Android/web builds still require a supported builder/CI. +No Android device or AMD GPU runtime result is claimed. + +The baseline's [performance and memory limitations](dynamic_lighting_release.md#known-limitations) +remain. Local visibility fields approximate occlusion; model lighting retains +its existing two-light limit. Authored world spotlight cones survive, while +model lighting retains the baseline point-light approximation. Unknown custom +tag names and missing markers remain stock. Bounded pools can reduce optional +coverage in crowded scenes. Neither short captures nor capped timing samples +establish universal 120+ FPS, a memory plateau or exhaustive map compatibility. + +Local logs, build/source hashes, reports and representative frames live under +`build/emitter-expansion`, `build/plasma-visual`, `build/lighting-performance` +and `build/lighting-compatibility`. Only this assignment's staged maps and +caches are removed; test saves are archived losslessly and verified first. +Final retention removed approximately 2.45 GB of this assignment's redundant +test binaries, raw/duplicate captures, interrupted-run map caches and loose +archived saves, after an earlier 1.02 GB cleanup. A final inventory confirmed +that no staged map files remained in this assignment's run folders. +About 383 MB of representative visual/menu evidence, +reports and archived saves remain, alongside small manifests/logs, the normal +build and one passive performance build retained for the open performance +investigation. Original maps, user saves and other worktrees were untouched. + +## November optimisation: 240 FPS target (in progress) + +This follow-up uses 2560x1440, AA off, 16x anisotropic filtering, highest model +detail and per-pixel lighting on the same RTX 5070 Ti/617.42 setup. Release +comparisons use full LTO and the existing PGO profile. Earlier rapid builds +with both disabled are labelled separately in their manifests and must not +be compared as equivalent release builds. + +Plasma prongs now have a separate, default-off control in both frontends. +Their short forward spill and camera-distance fade retain stock flare art; +the existing Weapon Glow group cannot enable them. Prongs still share the +eight-field budget. The guide records their smaller ray grid; other sources +retain their existing grids and attenuation profiles. + +Retained optimisations are conservative object rejection outside a ray batch's +cube, exact local collision snapshots for stationary-field reuse, cached +stationary visibility targets, seven-step trilinear interpolation and bounded +model texture/uniform/binding reuse. No simulation or networking code changes +are part of this follow-up. The binding cache owns only units 6/7 and expires +at view/reset boundaries. Failed texture resolution retries; sampler failure +retains the explicit texture-parameter path. Desktop and ES harness cases +exercise those paths and active-unit preservation. + +The collision broad phase matched stock and uncached queries for 14,902,656 +checkpoint rays with zero mismatches. That is a diagnostic result, not a +timing sample or proof for every map. The earlier model-node cache candidate +had no demonstrated benefit and was removed. A texture-coordinate candidate +regressed the release checkpoint measurement (about 172 versus 231 FPS in +its control); it was also removed. + +The first two-minute, 15-heroic-bot Derelict run averaged 185 FPS with lighting +and 392 FPS with it disabled. These are independently evolving combat runs, +not identical replays. The lit second minute averaged 165 FPS. Bot telemetry +confirmed kills, deaths and respawns; captures confirmed combat. This fails +the sustained 240 FPS target. A later instrumented run averaged 243 FPS but +its second minute averaged 173 FPS: its headline average is not acceptance. + +The user's copied Two Betrayals checkpoint is immediately before the snowy +Covenant encounter. Five seconds of ordinary forward controller input reaches +the exterior; a further 0.6-second right turn faces the fight. No teleport, +actor substitution or mission-script changes are used. These route captures +are diagnostics, with frequent screenshot readback excluded separately from +raw timings. Original maps and saves remain untouched. + +In that same route, the model-binding change reduced the inclusive binding +timer from 4.58 to 3.46 ms per frame with approximately 115 binds per frame +in both runs. Diagnostic throughput increased from about 138 to 164 FPS; +neither is a sustained acceptance result. Trace time remained about 1.60 ms, +visibility reconstruction 0.83 ms and texture preparation 0.72 ms. Timers +overlap: binding includes field work, so these columns must not be added. +The remaining work is active optimisation, not a declaration that this +performance is an acceptable limitation. + +The subsequent exact row-reuse change reduced field reconstruction from +0.83 to 0.69 ms in the same route; texture preparation was 0.69 ms with the +half-scale specialization. The combined diagnostic run averaged about +174 FPS. Ten focused occlusion/binding tests passed, including exact +per-cell history and half-scale sampling comparisons. + +The subsequent passive release runs retained only sparse captures, excluded +their readback frames from pacing, and also recorded the raw distributions: + +| Workload | Measured time | Mean FPS | 1% low FPS | p95 frame time | Frames above 4.17 ms | +| --- | --- | --- | --- | --- | --- | +| Two Betrayals snowy encounter, all lighting | 120 s | 193.3 | 128.7 | 6.68 ms | 89.5% | +| Derelict, 15 heroic bots, all lighting | 120 s | 279.8 | 146.8 | 5.37 ms | 34.2% | +| Same snowy route, lighting off | 60 s | 607.4 | 367.2 | 1.93 ms | 0.025% | + +These independently evolving fights are not frame-identical replays. The +snowy lit run's second minute averaged 199.8 FPS; the bot run's second minute +averaged 264.3 FPS. Captures show active outdoor combat and bot telemetry +records kills, deaths and respawns. Neither lit result meets sustained 240 +FPS. The stock control identifies substantial remaining feature overhead; +it does not establish that every stock encounter meets the target. The +remaining measured costs are primarily CPU collision and field/texture +preparation, not the added GPU lighting passes. No broad shared-renderer +change is retained in this follow-up. + +No crash or shader error was reported in those runs. Private memory rose +about 2.4 MiB between windows in the snowy run and 4.3 MiB in the bot run; +these short runs do not establish a plateau or resolve the earlier memory +investigation. + +The combined implementation review retained bounded caches, conservative +fallbacks, unchanged host policy and Android exclusion. The focused suite +passed 82 tests, covering real field/collision calculations, menu staging, +activation, GL/ES binding state and shader/Android isolation. Runtime menu +checks passed independent prong Save, Cancel, Defaults and restart persistence. +The modern short label was inspected at 640x480 without clipping. Xbox/CE +prong captures passed at 30/60/240 FPS; the CE 120 FPS capture exercised +occlusion toggling, and a disabled prong capture selected no enhanced lights +and performed no occlusion updates. These small visual fixtures do not prove +busy-combat performance. + +MCC Digsite validation is incomplete. Its stock Plasma Rifle weapon tag is +absent; the tag named Plasma Pistol is a custom weapon in the rendered view. +The capture runner now starts this multiplayer package as an isolated local +match, excludes menu-scene frames, and reports unavailable/rejected weapons. +The pistol equipped successfully, but neither that prong case nor the rifle +projectile fixture selected a light during the measured interval. Those are +failed lighting captures, not passing MCC acceptance or proof of a renderer +regression. Their logs and frames are retained; this remains an unresolved +map-specific validation issue. No MCC adapter or gameplay code was changed +to force the fixtures to pass. + +Windows release and capture builds succeeded. Full Android and web builds +were attempted with the installed NDK/Emscripten, but stopped at missing Unix +shell helpers (`sed` and the SDL copy prerequisite). The original Windows +configuration was restored. The passing exclusion/inert-hook and GLES tests +are not substitutes for those full builds. No AMD device, Android device, +Linux runtime or fresh two-peer multiplayer result is claimed for this pass. + +Run manifests, raw samples, captures and reports are retained under +`build/lighting-240` and `build/lighting-performance`. The earlier validation +sections do not certify these later changes. Sustained 240 FPS and the +outstanding platform/multiplayer checks remain open acceptance work. + +Cleanup removed 497.6 MiB of superseded diagnostic/capture binaries from this +follow-up. Its final visual saves were archived with verified hashes and raw +captures converted losslessly to PNG. The build/evidence area retains about +142.3 MiB, including the clean Windows candidate, one passive performance +build, the current capture build for the unresolved MCC check, menu evidence +and useful logs. Performance-run evidence is retained separately. Original +maps, active user saves and unrelated worktrees were not modified. The normal +Windows configure arguments are restored to portable release with LTO/PGO +off; the delivered candidate and reported release runs used full LTO and the +existing PGO profile, as their manifests record. No branch was pushed. + +## CPU collision and visibility follow-up, 5 November + +The retained follow-up caches the exact sphere predicate's batch invariants, +proves separate common BSP prefixes for eight ray octants, reuses interpolation +rows when preparing half-scale textures, and keeps large scratch buffers off +the repeated field/texture lookup paths. Fully clear depth samples skip distance +feathering while retaining the original ordered weight sum. Long blocked fades +now settle values below `1e-20` to zero rather than retaining subnormal values; +this is below 8-bit visibility precision and does not change the simulation's +floating-point mode. Light counts, ray resolution, cadence and visible profiles +are unchanged by this follow-up. + +Before any shared model-query experiment, the two-minute release snowy run +`c40-phase2-sustained` averaged 211.6 FPS, with a 138.3 FPS 1% low, 6.07 ms +p95 and 75.5% of frames above 4.17 ms. Its two minutes averaged 205.7 and +217.5 FPS respectively. This improves on the earlier 193.3 FPS run, but is +not sustained 240 FPS acceptance. Independent combat evolution prevents +treating the difference as a frame-identical A/B measurement. + +The octant collision path agreed with stock and uncached queries for +21,003,360 snowy-encounter rays, with zero depth mismatches. An experimental +nearest-hit bound and synchronous model-transform cache also matched stock +for 21,677,088 rays and reduced diagnostic time per ray by roughly 7% relative +to the octant run. However, its subsequent two-minute release run averaged +191.0 FPS, with a 107.3 FPS 1% low and 7.00 ms p95. That failed to demonstrate +a whole-frame benefit, so the shared model API, cache and candidate-only tests +were removed. `source/physics/collision_models.c` and its header are restored +exactly to HEAD. No new shared-engine change is retained from this follow-up. + +The rejected candidate's two-peer Blood Gulch check compared it with the +previous release using different lighting preferences. Both peers exited +normally, observed 66 two-player samples, damage and weapon pickups; the host +recorded two kill events. The comparator paired 59 seconds with no divergences, +and recorded zero movement drift in 1,770 samples. This is evidence for that +candidate, not a substitute for final-state integration checks. + +Further candidates were checked against the same live inputs. Finer face-tile +BSP prefixes agreed with stock on 21,225,792 rays. A subsequent comparison of +8-by-8 tiles, 4-by-4 tiles and octants in the same batches found less than 1% +timing separation, with zero differences on 15,252,864 rays. The extra range +API and tile traversal were removed; the simpler octant path remains. The +earlier large per-cell projection cache was also removed because it did not +demonstrate a whole-frame benefit. Neither discarded cache is a new runtime +memory requirement. + +The compiler had inlined the large scratch helpers back into lookup functions; +explicit no-inline attributes now keep that allocation off cache hits. Flat +stationary fading and ordinary model conversion retain the same arithmetic. +A nearby control of the older 211.6-FPS binary averaged only 186.4 FPS over +60 seconds, versus 191.1 for the flat-loop candidate. These independently +evolving encounters demonstrate substantial run variation, so small differences +and earlier candidate slowdowns cannot be attributed solely to code changes. + +The half-scale radial conversion candidate was compared against the actual +generic loop in live combat, alternating their timing order without an intervening +simulation step. All 198,352 masks matched byte-for-byte. Conversion totals were +2,897.7 ms specialized versus 3,515.0 ms generic (17.6% less CPU conversion time). +This comparison includes the flat model path and is not a whole-frame FPS gain. +The subsequent unit-scale extension is covered by the same per-pixel harness +comparison; this earlier live measurement does not measure that extension. +A small model-selection uniform cache was evaluated, but removed to keep the +follow-up focused on the dominant CPU costs; no meaningful frame-time gain +was established for it. + + +### CPU batching and packed reconstruction + +Before these CPU changes, `c40-phase3-final` measured 200.6 FPS over 120 seconds, +110.9 FPS 1% low, 6.80 ms p95, and 75.2% of frames above the 4.17 ms budget. +That is not sustained 240 FPS acceptance. A phase-3 two-peer check paired 59 +seconds without divergences; those results predate the CPU batching changes. +Android and web builds were attempted again: the Windows NDK compiler-wrapper +invocation and missing Unix shell tools respectively prevented completion. +These are environment failures, not successful platform checks. + +`phase4-batch-compare` compared model-major collision batches, the previous +ray-major batches, uncached batches and stock queries in the same live Two +Betrayals poses, rotating timing order. All 18,693,120 rays agreed exactly +across all four paths. Model-major batches took 6,552.5 ms cumulatively versus +6,828.2 ms for the previous batches: 4.0% less collision CPU time. Stock queries +took 23,090.8 ms. The previous-batch comparison is the relevant incremental +gain; the stock difference includes earlier optimisations. This diagnostic +executes four queries and must not be used as an FPS acceptance run. + +Model-major work remains in feature-owned code and preserves the shared model +implementation. Tests compare actual engine matrix/query functions with the +batch on translated, rotated, scaled, masked and malformed synthetic inputs. +The packed reconstruction candidate likewise preserves the scalar output; +live timing and final-state acceptance are recorded separately below. + + +The live `phase4-visibility-compare` comparison alternated scalar and packed +reconstruction on 80,316 identical fields (328,974,336 cells). Every field +matched byte-for-byte. Packed reconstruction took 2,090.7 ms cumulatively +versus 4,665.0 ms scalar: **55.2% less CPU reconstruction time**. The isolated +synthetic benchmark's larger gain is not used as the live performance claim. +Neither diagnostic changes ray count, resolution, update cadence or light +budget. The rendered capture shows the snowy stairs, Jackal shield and plasma +fire intact; it is a sampled frame, not a full visual acceptance pass. + +The final focused regression suite passed 171 tests; one POSIX socket test was +skipped on Windows. This includes actual collision/model math, packed/scalar +field and texture equality, 30/60/120/240-Hz synthetic filtering, isolation, +host policy, menu/configuration, Android exclusion and web build-graph checks. + + +The combined normal release timing build (`c40-phase4-final`) then ran the +same copied checkpoint/normal-input route for 120 seconds after 15 seconds +of warmup, uncapped at 2560x1440, AA off, 16x AF and highest models. It measured +219.5 FPS average, 123.7 FPS 1% low, 6.12 ms p95 and 7.12 ms p99. Six capture +frames were excluded; 63.2% of remaining frames still exceeded 4.17 ms. +The two minutes averaged 208.5 and 230.5 FPS. Mean occlusion work was 1.29 ms, +versus 1.64 ms in the preceding 200.6-FPS run; light selection means were both +about 11.7. These fights are not deterministic frame replays, so the directly +paired CPU comparisons establish causality more strongly than the FPS change. + +**Sustained 240 FPS remains unfinished work, not accepted performance.** +World BSP traversal remains the next collision target; the measured 4% model +batch gain does not remove that cost. No additional GPU optimisation was +retained in this phase. Private memory window means rose from 662.54 to +665.37 MiB in this short run; this neither proves a leak nor establishes a +long-session plateau. The run exited normally without logged renderer errors. + + +Final-state CE Death Island and MCC Digsite two-peer checks paired the current +normal Windows build (lighting enabled) with the previous normal build +(lighting disabled), using host shield policy `players`. Both peers exited +normally, joined, exchanged damage, observed kills/respawning and weapon +pickups. The comparator found no divergences or problems over 59 paired CE +seconds and 50 paired MCC seconds. These are bounded rendered integration +checks, not complete map-family or long-session acceptance. + +Windows release compilation passed. The final Android/web attempts again +failed before completing their builds: Android could not launch the local +NDK compiler wrapper as a Windows executable; web could not launch required +Unix shell commands. Build arguments were restored. Android exclusion and +web graph/scalar-fallback tests pass, but full builds and Android/AMD-device +validation are not claimed. No Linux runtime check was performed in this phase. + +The final review covered batching gates, model transforms, node ordering, +bounded scratch ownership, fallbacks, scalar/SSE2 equality, lifecycle isolation, +Android source exclusion, diagnostics and documentation. No new shared-engine +or renderer edit is retained in this CPU phase. Superseded diagnostic binaries +and the older normal candidate were removed after hash verification, reclaiming +418.1 MiB. Test maps/caches were removed; test saves were losslessly archived +with verified manifests. Logs and captures remain. The current normal Windows +candidate (26.8 MiB) and passive timing build (24.5 MiB) remain for ongoing work. + +## World collision traversal, 6 November 2026 + +The retained optimisation prepares one-sided internal BSP chains for each +ray octant, including chains below branching nodes. Preparation belongs to +`plasma_collision.c`; the small shared traversal extension consumes caller- +proven skip counts through the existing optional batch cache. A feature-only +root entry cannot skip these private internal traversal steps. Every skipped +node still consumes the original depth and visit budgets. Boundary planes, +leaf ordering, surface tests, breakable state and cache-miss traversal retain +the engine's existing behaviour. No map-family conversion or shader changes +are involved. Simulation callers use no cache; model batches use zero skip +counts. All scratch is bounded and cleared between batches. Lighting defaults, +host policy, Android exclusion and AMD/NVIDIA shader paths are unchanged. + +Review consolidated the identical prefix/preparation plane bounds in +`trace_side`. Regression cases compare complete traversal results and state, +including exhausted budgets, cyclic nodes and cache-slot eviction. Deliberately +broken bounds, budget accounting and eviction must fail those checks. + +The whole-cube trial matched 19,466,976 live Two Betrayals rays but saved only +1.98% of tracing time. The retained octant trial matched all 19,312,992 rays: +6326.253 ms prepared versus 6966.486 ms without preparation, a 9.19% reduction. +The comparison rotates execution order on identical rays and poses, outside +simulation updates, and compares outputs outside the timed intervals. The +unprepared variant retains model batching and uses one node cache; both +variants include the new bounded scratch allocation/clearing. These are CPU +batch timings, not gameplay FPS. A further leaf/plane lookup cache matched +19,652,544 rays but did not establish an additional gain, so it was removed. + +The reviewed release build used full LTO/PGO at 2560x1440, AA off, 16x AF, +highest models and per-pixel lighting. The copied checkpoint/save hashes +matched the preceding phase. Normal controller input advances five seconds +and turns right for 0.6 seconds into incoming Covenant fire on the snowy +stairs. All optional lighting, including prongs, was enabled. After 15 seconds +of warmup, the 120-second run measured: + +| Metric | Reviewed traversal | Previous phase | +| --- | ---: | ---: | +| Average FPS | 228.52 | 219.50 | +| 1% low FPS | 149.95 | 123.68 | +| p95 frame time | 5.607 ms | 6.119 ms | +| p99 frame time | 6.164 ms | 7.123 ms | +| Frames above 4.167 ms | 59.39% | 63.18% | +| Mean occlusion update time per frame | 1.218 ms | 1.286 ms | + +The two one-minute windows averaged 223.00 and 234.04 FPS. Selected lights +averaged 11.53, peaked at 19, and were present throughout. Six screenshot +frames were excluded from pacing statistics; no frame exceeded 50 ms. Both +retained screenshots show the snowy combat encounter with active shield and +weapon lighting. This is a sustained fixed-view encounter check, not a +playthrough of every busy area. Independently evolving fights prevent claiming +the entire FPS difference as an exact A/B gain; the identical-ray comparison +establishes the traversal improvement separately. + +A separate 60-second lighting-off control averaged 624.57 FPS with 403.77 FPS +1% lows, no selected enhanced lights and zero occlusion updates. Both runs +exited normally without reported runtime errors. Their reports and settings +are under `build/lighting-performance/c40-world-final-on` and +`c40-world-final-off`. The enabled run's private-memory window means rose +from 663.27 to 666.54 MiB; this short run does not establish a memory plateau. +**Sustained 240+ FPS is not achieved.** The stock control supports continued +work on enabled-feature overhead; the traversal improvement does not close +the remaining frame-time gap or resolve the previously tracked memory issue. + +The performance runner now marks its deliberately authored lighting settings +as current, avoiding the one-time legacy-preference reset introduced on +testing. Player preferences and migration behaviour are unchanged. + +Final validation passed 163 lighting, collision, menu, isolation and build-graph +checks, with one POSIX-pthread socket harness skipped on Windows. The local +test runner needed UTF-8 mode and a compiler wrapper with a consistent CRT +warning macro; neither required a production change. Light-storage checks +passed ordinary and full-LTO COFF builds, including their corruption control. + +Two-peer CE Death Island and Workshop Bigass sessions used lighting on at the +host, off at the client, and host shield policy `players`. Ordinary release +runs compared 60 and 55 seconds respectively, with normal exits and no +sustained divergence. Both covered joining, shooting, respawning and weapon +pickup. The first, instrumented CE attempt reported a brief scripted-pickup +position difference; the ordinary release repeat passed without mismatches. +Its collision comparison independently matched 1,118,208 rays. Bigass was +loaded through Workshop item `3010816711`; its matching `halo1/maps` resources +were copied only into the isolated test's shared-resource folder after an +initial missing-resource refusal. The installed Workshop files were unchanged. + +Testing advanced to `d91cd8599` during validation. That bot/lobby update was +fast-forwarded without conflicts; it changes none of this optimisation's +rendering or collision files. Its 128 focused integration checks passed, and +the combined state rebuilt successfully as Windows full LTO/PGO. The final +MCC mixed-setting run compared 55 seconds with no state mismatches or +divergences and matched all 1,559,040 live collision rays. Xbox snowy combat, +CE and MCC captures were inspected; these are representative checks, not +exhaustive map/device compatibility coverage. The sustained FPS measurements +above predate the unrelated bot/lobby integration. + +Local Android and web builds were attempted but remain blocked by the local +toolchain launch failures recorded in the preceding phase (NDK executable +wrapper and missing Unix commands respectively). Build arguments were +restored. The published commit's Linux/Android/web/Windows CI must be checked +separately; no local Android device, AMD GPU or Linux runtime test is claimed. + +Cleanup removed 98.80 MiB of superseded diagnostic executables after verifying +their recorded hashes. No loose test map files remain. Test saves are preserved +in verified lossless archives. About 89.62 MiB remains for this phase's logs, +captures, archives and two measurement executables; normal build outputs and +the user's installed maps/saves were preserved. + +## CPU mask conversion and collision continuations, 7 November 2026 + +The initial candidate combined two CPU changes. `texture_row` converts four +visibility-mask pixels together on SSE2, including the AR, Needler and prong +angular profiles. It preserves the scalar operation order, exact division and +square roots, with a scalar fallback elsewhere. The general conversion remains +for arbitrary radial scales. No shader, texture format, radius, ray grid, +refresh cadence or light-admission limit changes. + +The candidate's shared vector traversal iterated tail continuations, retaining +recursion for the near side of a split. Compiler output showed that Windows +still created full stack frames for these calls. The rewrite preserved plane +arithmetic, ordered leaf results, cache contents and logical depth/visit +budgets. It affected the general collision service used by Xbox, CE and MCC, +including lighting-disabled gameplay; it added no new API, cache or feature +logic to the shared engine. The comparison harness checked complete results +and continuation state against the prior recursive form. + +The live `c40-visibility-packed-verify` comparison checked 223,962 masks with +zero differing bytes. Conversion totals were 698.028 ms packed and 4,104.309 ms +generic, 83.0% less conversion time. The generic reference also predates earlier +half/unit-scale specialisations, so this is not an incremental whole-frame FPS +claim. A separate asset-free test checks 524,288 packed/scalar output pixels +across all four profiles, varied axes, admission, radial masks and blend weights. + +Two empty-space proof candidates were evaluated. The first required no +eligible objects and showed only 0.07% timing separation on 16,425,888 rays. +The world-only version initially saved 2.0% on 15,895,872 rays. After the +iterative traversal change, the same-input comparison measured 5,066.789 ms +with that proof and 5,069.583 ms without it: only 0.06% separation. The proof, +its extra shared accessor and its candidate-only tests were removed. + +`c40-visibility-iterative-verify` compared 15,679,968 rays across stock recursive +queries, prepared/unprepared batches, uncached queries, the proof-disabled +path and recursive batches. Every result agreed. Iterative batches measured +5,066.789 ms versus 5,136.523 ms for recursive batches (1.36% less time in this +comparison, both still carrying the subsequently removed proof). These are +same-pose CPU timings, not FPS acceptance. No claim of a large collision gain +or universal map speedup follows from them. + +The work incorporates testing through `0acce6818`, including the concurrent +upstream 562 integration. None of those changes was reverted or repurposed. +The final review retained the generic/scalar fallbacks, invalid-data checks, +batch cleanup and meaningful negative-control tests. Lighting settings, +default-off behaviour, host policy, Android exclusion and AMD/NVIDIA shader +fixes are unchanged. + +The first two-minute production measurement, `c40-visibility-production-on`, +returned 138.7 FPS and a 93.3 FPS 1% low. Its cause remains unresolved; the +result is retained rather than discarded. Immediate 45-second matched repeats +at the same checkpoint and settings measured 233.2 FPS for the pre-traversal +candidate and 233.6 FPS for the final code, with 1% lows of 146.1 and 139.0 FPS. +Both had about 54.1% of frames over the 4.17 ms target. These independent live +encounters vary; this does not establish an incremental whole-frame gain or +sustained 240 FPS acceptance. The byte/ray comparisons above isolate the CPU +changes more reliably than these separate combat runs. + +Testing then advanced through `045cb99bc`, adding Workshop resource discovery +and its qualification notes. Those non-overlapping changes were fast-forwarded +without alteration. The Xbox performance measurements above predate that +integration; the final combined build and checks are recorded below. + +The combined Windows full-LTO/PGO release built successfully. Final lighting, +collision, isolation, menu and build-graph checks passed 167 tests with one +Windows POSIX-pthread skip. Workshop checks passed another 71 with eight +Linux-filesystem skips; their first attempt used the lighting harness's CRT +macro wrapper and failed at compilation, then passed with the native compiler. +No production fix was needed. Light-storage tests passed ordinary and full-LTO +COFF builds and detected the deliberate pointer-corruption control. Source +hashes were checked after temporary instrumentation was restored, and the +ordinary executable contains none of the measurement CSV markers. Both changed +guides' local links were checked. + +Local Android and web builds were attempted but hit the existing Windows +toolchain launch problems (NDK compiler wrapper and missing Unix commands). +These are not platform passes; the exact published commit's CI is required. +No Android-device, AMD-GPU or native Linux gameplay validation is claimed. + +The final combined `c40-visibility-integrated-on` run measured 120 seconds +after 15 seconds of warm-up at 2560x1440, uncapped, with all lighting enabled. +It used the same copied snowy-encounter checkpoint and ordinary controller +input as the preceding runs. It averaged **222.7 FPS**, with a **135.6 FPS 1% +low**, p95 **5.855 ms**, p99 **6.623 ms**, and **61.7%** of frames over 4.17 ms. +The two minute averages were 223.2 and 222.1 FPS; selected lights averaged +11.78 and peaked at 17. Occlusion averaged 1.307 ms. There were no recorded +errors or frames over 50 ms, and exit was normal. Screenshot readback frames +were excluded using the runner's existing rule. Captures confirm the snowy +encounter, shields, weapon lighting and combat; they do not establish full +playthrough visual acceptance. Private-memory window means increased from +663.44 to 666.19 MiB; this short run does not establish memory stability. + +**Sustained 240 FPS is not achieved.** Separate live runs ranged materially +even with the same checkpoint, and the final run does not establish an overall +FPS gain over the prior published build. The retained CPU improvements are +supported by same-input comparisons; they do not justify a performance sign-off. + +The 30-second final lighting-disabled control, `c40-visibility-integrated-off`, +averaged 563.2 FPS with a 331.9 FPS 1% low. Selected enhanced lights and occlusion +updates stayed at zero, with no recorded errors and a normal exit. This verifies +the off-state execution counters in that scene, alongside the isolation tests; +it is not a claim that all engine rendering costs disappear. + +Mixed-settings two-peer checks paired the final ordinary host (lighting on) +with the pre-traversal measurement build (lighting off), using host shield +policy `players`. CE Death Island compared 60 seconds with no mismatches; +Workshop Bigass compared 56 seconds with no sustained divergence. Both covered +joining, shooting, death/respawn and weapon pickup, and both peers exited +normally without recorded errors. Bigass had eight isolated shield differences: +every one paired a host sample two ticks after the client's sample, at the +seven-second scripted shooting interval (host 0.76, client 1.00). They cleared +between shots, consistent with damage-sampling timing rather than accumulating +simulation drift; this remains a qualification, not a claim of identical live +network samples. Maximum position separation was 0.0093 world units on CE and +0.082 on MCC. The final MCC host used installed Workshop resources directly; +only the older client needed matching resources copied into its disposable +fixture. These representative checks do not prove exhaustive map compatibility. + +Cleanup removed 172.94 MiB of superseded measurement executables after checking +their manifest hashes. No loose test map files remain. Saves are retained in +verified lossless archives, and about 116.55 MiB remains for this phase's logs, +captures, archives and final measurement executable. Original maps, saves, +toolchains and the ordinary production build were preserved. + +## Controlled comparison and retained change, 7 November 2026 + +The user challenged whether the CPU microbenchmarks justified the slower +whole-frame results. Eight new runs compared four variants on exactly the +`9bf9554aa` source base: both changes, neither change, mask conversion alone, +and traversal alone. Removing a change used its exact pre-`9bf9554aa` source; +other production-source hashes matched. All used Windows full-LTO/PGO release +settings, the same compiler and timing fixture, a frozen copy of the checkpoint, +2560x1440, AA off, 16x AF, all lighting enabled, 15 seconds of warm-up and a +120-second measured window. Screenshot capture was off for every run. Builds +finished before measurement; games ran one at a time. The Windows Balanced +power policy was left unchanged. + +Order was neither, both, mask, traversal, then traversal, mask, both, neither. +This balances a linear drift in conditions; it does not make live combat +identical or turn individual frames into independent experimental trials. +Every run is retained, including the two long frames in the first combined run. + +| Production variant | First two-minute average | Reverse-order average | +| --- | ---: | ---: | +| Neither change | 228.5 FPS | 225.0 FPS | +| Mask conversion only | 240.3 FPS | 242.8 FPS | +| Traversal only | 221.7 FPS | 236.0 FPS | +| Both changes | 220.3 FPS | 228.6 FPS | + +Mask conversion improved the round-matched averages by 5.1% and 7.9%; its +two-run mean was 241.5 FPS against 226.8 FPS for neither change, a 6.5% gain. +Its 1% lows also improved: 164.9/168.0 FPS against 158.7/154.1 FPS. Its p99 +frame times were 5.657/5.550 ms against 5.863/6.033 ms. Selected-light means +were similar (11.52/11.69 versus 11.51/11.64), without reducing light budgets, +quality, ray counts or refresh cadence. These results support retaining the +mask conversion in this encounter; they are not a universal hardware claim. + +Traversal alone varied by 14.3 FPS between runs and did not show a repeatable +gain. Adding it to the mask conversion was slower in both rounds. The original +same-input 1.36% collision timing result therefore did not justify retaining +that shared-engine rewrite. The recursive traversal was restored exactly, +along with its existing verification path. Candidate-only traversal comparison +instrumentation and tests were removed; the established cache, depth/budget, +eligibility and malformed-input coverage remains. No network contract, map +family boundary, host policy, Android exclusion, default setting or AMD/NVIDIA +shader workaround changed. + +The final retained implementation is **mask conversion only**. Sustained +240 FPS is still not achieved: 50.7% and 45.0% of its frames exceeded 4.17 ms, +and its 1% lows remain below the target. This resolves the retention decision; +it does not complete performance acceptance. All eight runs exited normally +without recorded rendering errors. Evidence is under +`build/lighting-240/controlled-comparison` and the `c40-controlled-*` run folders; +the plan records executable/source hashes, checkpoint hashes and run order. +The earlier candidate's [Build workflow](https://github.com/chestahh/GulchCE/actions/runs/42324288419) +and [MCC validation](https://github.com/chestahh/GulchCE/actions/runs/42324288332) +passed; the follow-up commit's checks are separate. + +Final review confirmed that the retained production code matches the measured +mask-only variant, and the shared collision source matches the pre-candidate +version. The final 164 focused checks passed with one Windows POSIX-pthread +skip; ordinary/full-LTO light storage and its corruption control also passed. +The ordinary Windows full-LTO/PGO executable rebuilt successfully. Android and +web were attempted again but hit the same local NDK-wrapper and missing Unix +command failures; no local platform success is claimed. Documentation links +and named retained functions were checked. The preceding CE/MCC network runs +tested the initial candidate; they were not repeated after restoring the +previous shared traversal. + +Comparison cleanup removed another 74.11 MiB of superseded executables after +hash checks. The frozen checkpoint was archived losslessly and verified before +removing its loose copy. Original maps/saves were unchanged, and no loose test +maps remain. About 137.27 MiB remains across this phase and its comparison runs +for logs, captures, save archives and the retained mask-only measurement build; +normal build outputs and toolchains remain available separately. diff --git a/docs/dynamic_lighting_acceptance.md b/docs/dynamic_lighting_acceptance.md new file mode 100644 index 0000000000..98a986d5ab --- /dev/null +++ b/docs/dynamic_lighting_acceptance.md @@ -0,0 +1,269 @@ +# Dynamic lighting visual acceptance + +This records milestone 2 on `dynamic-lighting-test`, based on `7c1309bd`, +on 25 October 2026. All eight settings remain off by default. CStencil and +Modern are outside this milestone. Stock effects, simulation, network protocol, +tag eligibility and Xbox/Custom Edition/MCC loading paths are unchanged. + +## Findings and changes + +The held Needler's broad downward fade left a coloured patch around a crouched +player's feet. The analytical fade alone did not describe its rendered reach: +linear filtering between the 16-cube texture's samples extends the transition, +especially in the larger specular volume. `needler_falloff_factor` in +[ammo_counter_falloff.c](../port/linux/game/ammo_counter_falloff.c) now fades +between 0.06 and 0.12 of the radius below the source, instead of 0.06 and 0.24. +At the stock 1.5 radius, the analytical transition spans 0.09–0.18 world units. +Horizontal/upward spill, the full-strength region immediately below the +needles, radius, colour, brightness and crystal emission remain unchanged. +This changes one feature-owned tuning constant, adding no allocation, raycast, +texture upload or work per frame. AR and shield policies are unaffected. + +The [visibility regression](../tools/harness/tests/plasma_occlusion.c) samples +between texture slices at the observed crouched-player and short-Grunt heights, +with collision occlusion on and off and a doubled specular radius. It checks +no diffuse foot pool at a 0.38-unit source height, no specular pool at 0.25 or +0.38 units, faint near-contact diffuse spill at 0.25 units, and retained bright +spill immediately beneath the needles. This remains a filtered approximation; +it is not a floor plane or a geometric shadow of the holder. Very low or unusual +poses and custom light radii still require judgement. + +The Light Occlusion help incorrectly implied it controlled Warthog blocking. +The existing `enabled` and `field_for` policy in +[plasma_occlusion.c](../port/linux/game/plasma_occlusion.c) makes muzzle blocking +automatic with muzzle lighting. The independent occlusion toggle controls +projectile and emitter lights. The wording is corrected in +[port_settings.py](../tools/port_settings.py), and its generated Dynamic Lighting +XML was regenerated; other screens are unchanged. No default or rendering +policy was changed to accommodate the wording. + +## Capture method + +The hidden Windows portable release runs use OpenGL 4.5 on an NVIDIA RTX 5070 Ti, +640x480, at 30, 60 and 120 FPS. At most two game instances run concurrently, +with separate data/save folders. Screenshots and render-time diagnostics are +both examined; a successful load or selected-light counter alone is not a +visual pass. Timings include capture readback and are bounded fixture averages, +not general performance guarantees. + +[plasma_visual_build.py](../tools/plasma_visual_build.py) temporarily installs +[the capture fixture](../tools/fixtures/plasma_lighting_capture.c), then restores +production sources and rebuilds the normal executable. The normal game contains +none of its forced controls, spawns, camera override or instrumentation. +[plasma_visual_run.py](../tools/plasma_visual_run.py) supplies isolated runs: + +```sh +python tools/plasma_visual_build.py --output-dir build/acceptance-capture +python tools/plasma_visual_run.py --data-root --capture-dir build/acceptance-capture --fps 60 --enabled 1 --label crouch --emitter needler-player --grounded --crouch --face-camera --hide-viewmodel --occlusion 1 +python tools/plasma_visual_run.py --data-root --capture-dir build/acceptance-capture --fps 60 --enabled 1 --label grunt --map c40 --emitter needler-grunt --grounded --face-camera --hide-viewmodel --occlusion 1 +python tools/plasma_visual_run.py --data-root --capture-dir build/acceptance-capture --fps 60 --enabled 1 --label turret --muzzle warthog --exterior --occlusion 1 +``` + +Use unique labels per run, repeat at each cap, and compare `--enabled 0`. +Grounded actors are placed with a structure collision trace. The player-model +fixture enters the normal combat stance, crouches using persistent unit controls, +then stands again; logged crouch samples must be 1, 1, 0. This is a rendered +player-model pose test, not a remote player's movement test. The exterior view +keeps the Warthog and ground visible while the seated player fires and aims +forward, sideways and backward; its actual muzzle-marker directions are logged. +Campaign skip input stops when the cinematic ends, avoiding accidental jumps. + +Early setup attempts with an alert, non-crouching actor, a poorly framed Grunt, +and an unguarded pre-initialization cinematic query are excluded. They exposed +test-fixture defects, not production-game crashes. The corrected fixture guards +the cinematic state, frames the grounded holder and verifies the crouch cycle. +Earlier gunner-camera captures are supplementary; exterior captures provide +the chassis-blocking evidence. + +## Scope of acceptance + +These are controlled stock Xbox-map scenes: Blood Gulch for crouched players, +first-person weapons and the turret; c40 for the Grunt and shields; b40 for the +Marine's AR. Both blue and gold Jackal shields and the stationary shield are +driven through damage, depletion and recovery using the engine's damage state. +Their evaluated A-out colour animation and the emitted RGB values are logged. +This establishes colour synchronization, not natural combat damage timing. + +The exact stock held-Needler tag remains `weapons\needler\needler`. +This milestone does not add CE `mp_needler` or arbitrary custom weapon aliases. +Map-family transition and networking checks, where recorded below, are lifecycle +and smoke checks; they do not establish full MCC campaign, cross-platform +internet play, split-screen or every-GPU visual compatibility. + +## Results + +Thirty-nine accepted visual runs passed their activation and 5% frame-cap +checks. Their measured averages span 30.00–30.06, 59.41–60.04 and +119.78–120.04 FPS. Representative frames at each rate were visually inspected: + +| Case | Coverage | Observation | +| --- | --- | --- | +| Needler player model | Crouch/stand at 30/60/120; disabled 60; occlusion off 60 | Broad foot patch removed; weapon and upper-body spill retained | +| Needler Grunt | Grounded c40 at 30/60/120; disabled 60; occlusion off 60 | Crystal/body illumination retained without a broad floor pool | +| First-person Needler | 30/60/120; disabled 60 | Crystal emission and nearby weapon spill retained | +| AR | First person and b40 Marine at 30/60/120; disabled 60 | Screen/weapon and upper-body illumination retained; no new floor pool | +| Shields | Blue/gold Jackal and stationary at 30/60/120; disabled 60 | Added spill follows red damage, depletion and restored base colour | +| Warthog | Exterior forward/side/rear aim at 30/60/120; disabled 60; separate occlusion toggle off 60 | Chassis-covered ground stays dark; exposed ground receives warm pulses | + +Nine shield sequences also passed a runtime RGB check: the damage phase's +emitted colour becomes over 97% red while the shader's evaluated damage +function approaches one. Warthog marker logs confirm three distinct actual +turret directions; the added warm spill is visible in enabled/disabled pairs. +Small collision-edge leakage remains possible; these are not exact mesh shadows. + +The AR/shield captures use the unchanged policies from the initial matrix. +The revised Needler, exterior Warthog and menu captures use the final build. +The earlier Needler results that exposed the foot patch are excluded from the +accepted count. Source manifests identify both versions. + +Twenty normal-executable menu cases passed: fresh defaults; all eight on/off +and saved; fresh-process reloads of both; Cancel button and controller Back; +Defaults then Cancel; Defaults then OK; unchanged OK; eight independent +one-toggle saves; Video Setup entry/return; and 1280x720 layout. Configuration +values and logs were checked, and captures show loaded/pending values and the +corrected help. The usual 640x480 layout was inspected too. These use scripted +controller navigation through the real menu, not a mock UI or physical-device +coverage of every input method. + +Retained local evidence is under `build/plasma-visual/*-m2-accept-*`, +`*-m2-verified-*`, `build/m2-menu/`, `build/m2-accepted-visual-results.json`, +`build/m2-final-results.json` and `build/m2-shield-colours.json` in the worktree. +The `m2-fix-*` and `m2-final-rates-*` comparison sheets show the correction and +frame-rate comparisons. Rejected/setup runs are retained separately with their +logs and are not counted as acceptance. + +The final combined review covered the feature mask, diffuse/model/specular +consumers, disabled fallback, texture reuse, generated help, fixture lifecycle, +regressions and documentation. No new shared-engine integration or broader +refactoring was needed. The final Windows portable release build passed; +97 focused lighting/menu/XML/settings tests passed, including the deliberate +old-fade negative control. Light-storage checks passed in ordinary and full-LTO +COFF builds and detected deliberate legacy pointer corruption. Local Android +and web targets are unavailable in this Windows configuration; CI supplies +platform build coverage, not runtime visual coverage. + +Xbox c40 → MCC Mercury Falling → CE Death Island → Xbox Blood Gulch completed +with lighting off at 30 FPS and on at 120 FPS. Each run exited normally, with +all three transition commands, a confirmed MCC load, CE model conversion and +the final Xbox load, and no exception. A normal-build two-peer Windows Blood +Gulch smoke test used all eight options on for the host and off for the client: +36/32 two-player snapshots, eight scripted shooting events each, normal exits, +and no logged assertions, exceptions or shader failures. These establish +bounded lifecycle and mixed-setting session operation, not full simulation +equivalence or internet/browser crossplay. No packet or simulation agreement +changed, so the network version is unchanged. + +Copied maps, generated map caches and capture-only executables were removed. +Selected PNGs, contact sheets and logs remain; redundant captures were trimmed. +The 1,205 inactive test-save files (about 1.86 GiB loose) were archived losslessly +in `build/m2-inactive-saves.zip` (about 5.2 MiB), with original relative paths +and SHA-256 hashes in its manifest. Every archive member was verified before +removing its loose copy. Roughly 300 MiB of evidence remains, including comparison +sheets. Original maps, user saves, other assignments and installed toolchains +were preserved. See `build/m2-cleanup.json` for the bounded cleanup totals. + +## Shield Glow and animated Overshield addition + +The optional Shield Glow now uses the shared soft world/model lighting path, +selected Shield Look and authored colour channels. Animated Overshield supplies +one shared layer hue and charge coverage to the surface, arms and emitted light. +The light rises with the luminous body, follows its rendered pose, and releases +smoothly instead of changing reach with every hit. Eight lights are selected by +contribution and distance, with an incumbent bonus to limit selection churn. +Light Occlusion uses the existing bounded collision budget. The borrowed light +template's flags, including no-specular, are preserved. + +The implementation review covered ownership, selection, repeated render views, +map/disable cleanup, shader colour evaluation and host policy. Overshield model +caches and queued arm identities now reset explicitly; duplicate activation +checks were removed. Feature logic remains in its dedicated modules. The only +new engine hooks are shield radius bounds and shutdown reset in object_lights.c, +where private light storage requires integration. Existing map loaders and +network messages are unchanged. See the [shield lighting reading guide](reading/shield_lighting.md). + +Shield Glow and Glow Intensity moved to Dynamic Lighting without changing their +saved keys. Animated Overshield remains independent in Extra Effects. Both +switches remain off by default. The host's existing shield-effects policy still +overrides local shield preferences unless it delegates to PLAYERS' OWN. + +The final focused run passed 165 tests; four reference-map tests were skipped. +This includes the actual shield-light module in a synthetic world, selected +colour channels, camouflage, green/pink layer agreement, 30/60/120 Hz release +equivalence, bounded selection, host overrides and cleanup. Windows portable +release builds and ordinary/full-LTO light-storage checks passed. The latter +also detected the deliberate legacy pointer-corruption negative control. + +Thirteen additional real-menu cases passed: fresh defaults, all nine toggles +and Light Show saved, fresh-process on/off reloads, Cancel button, Back, +Defaults/Cancel, Defaults/OK, unchanged OK, Shield Glow alone, intensity alone, +and 1280x720 layout. Both 640x480 and 1280x720 captures were inspected. Existing +eight-option acceptance above remains evidence for those independent controls; +the new cases exercise their combined operation with the two added rows. + +Six local web tests could not pass in this Windows environment: five assume +Unix path separators and one requires pthread.h. The remaining web checks +passed. Android and web Ninja targets are unavailable in this configuration; +cross-platform CI is required separately. These limitations do not count as +successful platform validation. + +The implementation at `ecf2cd69` subsequently passed all four +[platform CI jobs](https://github.com/chestahh/GulchCE/actions/runs/40230539919): +Linux, Windows, Android and web, including their configured test stages and +the web browser tests. The separate +[MCC validation workflow](https://github.com/chestahh/GulchCE/actions/runs/40230539927) +also passed. This closes build/test coverage for the locally unavailable +targets; visual acceptance remains the Windows GPU coverage described here. + +The Xbox c40 -> MCC Mercury Falling -> CE Death Island -> Xbox Blood Gulch +transition was repeated with all lighting off at 30 FPS and on at 120 FPS. +Both completed all three commands, logged the MCC load and CE model conversion, +returned to the final Xbox map and exited without exceptions. A normal-build +two-peer Windows smoke test retained 36/32 two-player snapshots and eight +scripted shooting events per peer, with no logged assertions, exceptions or +shader failures. Its host requested glow plus overshield while both peers' +local shield preferences were off; other dynamic lights were on for the host +and off for the client. These are bounded session/lifecycle checks, supplemented +by the policy harness, not internet crossplay or simulation-equivalence proof. +Initial sandboxed attempts could not connect over loopback and are excluded. + +Nineteen shield capture runs passed the activation and 5% frame-cap checks: +ordinary classic hit/recharge, classic overshield charge and enhanced overshield +charge at 30/60/120 FPS; enhanced first-person arms at all three caps; classic +and enhanced overshields with added lighting off at 60; enhanced ordinary hits, +crouching, Light Show, occlusion off, and an Elite at 60. Contact sheets and +representative frames were inspected. Green/pink surface and light layers agree, +the radial source follows crouching, ordinary hits release, and disabling glow +leaves the animated overshield surface intact. Off runs submitted no added lights +or occlusion updates. The unoccluded run retained light with zero occlusion +updates. The c40 Elite run exercised world specular draws; carousel's borrowed +template suppresses them, as authored. None of these checks establishes exact +mesh shadows or appearance on every map and GPU. + +The initial ordinary-hit fixture did not clear its damage-decay timer. Those +four captures are superseded by corrected hit/recharge runs and are excluded +from the nineteen accepted cases. Charge and first-person captures remain valid. +The final code differs from their manifest only by removing redundant overshield +activation checks; supplemental captures, transition runs and final harnesses +use the resulting implementation. Frame-cap averages include screenshot overhead +and initial shader compilation, and are not a general performance guarantee. + +The accepted-case index is `build/shield-accepted-results.json`. Local evidence +is in `build/shield-visual-results.json`, +`build/shield-decay-results.json`, `build/shield-supplemental-results.json`, +`build/plasma-visual/*shield-*`, `build/shield-menu/`, +`build/shield-network-verified/` and `build/shield-transitions-verified/`. +The corrected 60 FPS classic hit case is `60-1-shield-decay-normal-classic`. + +Cleanup removed copied maps, generated map caches, capture-only binaries and +temporary test executables. The 870 inactive test-save files (about 900 MiB +loose) were archived in `build/shield-inactive-saves.zip` (about 1.8 MiB), with +their original relative paths and SHA-256 hashes. All members were verified +before removing loose copies. Superseded full-size frames were trimmed while +their contact sheets and logs were retained. About 269 MiB of evidence remains; +`build/shield-cleanup.json` records the totals. Original maps, user saves, +previous playtests and other assignments were preserved. + +Milestone 3's [sustained performance report](dynamic_lighting_performance.md) +adds five-minute busy combat measurements at native 1440p for each frame cap, +with lighting off and on. Its remaining performance limits supersede any +inference of sustained frame-rate acceptance from the short captures above. diff --git a/docs/dynamic_lighting_compatibility.md b/docs/dynamic_lighting_compatibility.md new file mode 100644 index 0000000000..b1b4989fd5 --- /dev/null +++ b/docs/dynamic_lighting_compatibility.md @@ -0,0 +1,147 @@ +# Dynamic lighting Milestone 4: compatibility and multiplayer + +This pass covers representative map families, joining, respawns, inventory +changes and different local lighting settings. It does not reopen the sustained +performance investigation. Production code is unchanged from `98897e66`: +optional lighting remains off by default, host shield policy remains authoritative, +and Xbox, Custom Edition and MCC retain their existing paths. AMD/NVIDIA renderer +fixes and the network protocol are unchanged. + +## Method and multiplayer results + +Four sequential Windows loopback sessions used two hidden, rendered 1280x720 +windows at 60 FPS. Each peer had its own executable, config, data and saves. +All lighting preferences, including animated overshields, were on for one peer +and off for the other. A passive diagnostic build sampled the received host +policy, effective Shield Glow activation and local preferences once per second. +It did not modify gameplay, networking or light selection. + +| Map/case | Host/client lighting | Host shield policy | Two-player snapshots, host/client | Observed respawns per player, on both peers | +| --- | --- | --- | --- | --- | +| Xbox Blood Gulch | On / off | Glow + overshield | 92 / 88 | Player 0: 2 | +| CE Death Island | Off / on | Stock | 91 / 87 | Player 0: 4 | +| MCC Digsite Albatross (`DigsiteMP/1`) | On / off | Players choose | 76 / 72 | Players 0 and 1: 2 each | +| Xbox Blood Gulch, late join | Off / on | Players choose | 73 / 69 | Player 0: 1; player 1: 4 | + +All four accepted sessions exited normally, showed changing weapon inventories +in both logs, and met their lifecycle and policy checks. Policy samples after +tick 600 all matched the host's decision: 140 samples for Xbox, 138 for CE, +108 for MCC and 140 for late join. Forced-on and forced-stock policies overrode +the opposite client preference; Players Choose retained opposite local choices. +These are actual receiver/activation observations, not only launch settings. + +The existing [network comparator](../tools/net_compare.py) found no persistent +divergence in the three normal-join sessions, with 81, 80 and 65 paired seconds +respectively. Xbox and CE had no compared movement ticks outside rounding error +(2,223 and 1,584 samples). MCC had 20 of 1,756 movement comparisons apart and +two snapshot mismatches each for position, alive state, kills and deaths around +respawn events. Its largest transient position difference was 24.74 world units; +these recovered within the existing tolerances. This is not bit-identical +frame-by-frame simulation, and tolerances were not relaxed to obtain a pass. + +The late client started 32 seconds after the host. The host logged 19 solo +snapshots before the second player appeared at tick 600. Host-measured synchronous +movement drift was within rounding error for all 1,633 compared ticks. The two +once-per-second log streams have different phases, outside the comparator's +two-tick pairing window, so there are **no paired snapshot seconds** for this +case. Its pass covers joining, lifecycle, received policy and host drift; +it does not establish paired inventory/score equivalence at the same tick. + +MCC's map script validator refused the map's `host_spawn` script at +`debug_camera_load`. That existing refusal is retained, not bypassed to make the +map run. The result is bounded to the supported gameplay paths exercised here. + +Both single-process transition runs passed: Xbox c40 -> MCC Mercury Falling -> +CE Death Island -> Xbox Blood Gulch, with all lighting off and then on. Each +logged the MCC load, CE conversion and three clock resets, retained the expected +shield activation, and exited normally without exceptions. Seven captures per +run were retained; the contact sheets and multiplayer captures were inspected. +Startup/loading frames are black; the retained scene frames show rendering +continuing across the map families. These short visits do not establish campaign +completion or full visual acceptance of each map. + +## Tool corrections and reproducibility + +- [lighting_compatibility_build.py](../tools/lighting_compatibility_build.py) + builds a passive policy probe and restores the original source bytes, + configuration and normal Windows build even after failure. +- [lighting_compatibility_run.py](../tools/lighting_compatibility_run.py) + stages the two peers before starting either process and requires observed + deaths-to-respawns, changing inventories, actual policy and normal exits. + HSC object-list ordering differs from network player numbering; both peers + must observe the same network player respawn, whichever player the cue targets. +- [lighting_compatibility_transitions.py](../tools/lighting_compatibility_transitions.py) + exercises Xbox c40, MCC Mercury Falling, CE Death Island and Xbox Blood Gulch + in one process, with separate all-off and all-on runs. +- The network log judge now imports on Windows without POSIX `SIGHUP`. + POSIX launch/process-group tests remain enabled on Linux; five unsupported + cases skip on Windows. This does not port the POSIX launcher to Windows. + +Example commands, from a configured Windows checkout with local game data: + +```powershell +python tools/lighting_compatibility_build.py +python tools/lighting_compatibility_run.py --data-root C:/local/game --case xbox +python tools/lighting_compatibility_run.py --data-root C:/local/game --case ce +python tools/lighting_compatibility_run.py --data-root C:/local/game --case mcc +python tools/lighting_compatibility_run.py --data-root C:/local/game --case late +python tools/lighting_compatibility_transitions.py --data-root C:/local/game --profile-root C:/local/test-profile/saves --enabled 0 +python tools/lighting_compatibility_transitions.py --data-root C:/local/game --profile-root C:/local/test-profile/saves --enabled 1 +``` + +Run these sequentially, with Windows loopback access. Runners refuse existing +evidence folders. Retail maps, resources and captures stay local. Original data +and profiles are copied, never modified. Save archives include original relative +paths and verified SHA-256 hashes; copied maps/caches and binaries are removed. + +Pilot runs are excluded from accepted results. They exposed a misparsed config +log line, ineffective scripted damage on Xbox, malformed HSC command wrapping, +and a sandbox connection failure. The first late-join run also crashed when an +unguarded HSC `unit_kill` was given `NONE` after another death command removed +the unit. The corrected cue uses `unit_get_health`, whose existing implementation +safely returns -1 for a missing object, before calling the live-unit-only command. +The crash log is retained; no production damage or unit implementation was changed. + +The retained runtime probe originally also printed an unused end-of-frame light +count. That sampling point does not establish active lighting draws; the column +was not an acceptance criterion and was removed during final review. Policy +sampling is unchanged. These sessions establish compatibility with the settings, +not new visual acceptance of every emitter or proof that every optional light +was visible in every sampled frame. + +## Platform coverage and limits + +The unchanged production revision passed refreshed +[Windows, Linux, Android and web CI](https://github.com/chestahh/GulchCE/actions/runs/40261321949), +including the workflow's Chromium/Firefox and native WebRTC checks. These are +debug CI builds; release jobs are skipped on this branch. Local diagnostic and +restored normal Windows release builds also succeeded. + +Local rendered coverage uses Windows/NVIDIA. This is not an AMD hardware run, +full campaign completion, every custom-map variant, or a mixed-platform retail +internet game. Browser transport CI and synthetic MCC networking checks support +the result but do not replace those unperformed scenarios. The outstanding +[performance and memory limits](dynamic_lighting_stability.md) are unchanged. + +The final local regression selection passed **170 tests**, with five Windows +skips for POSIX launcher/process-group cases. It covered projectile/emitter, +muzzle, shield and occlusion modules, fragment-source sharing, GPU visibility +contracts, MCC networking/UI and the compatibility report's acceptance rules. +The combined review checked probe ownership, source restoration, config +isolation, observed lifecycle coverage, absent paired-snapshot coverage and +cleanup. It removed the unused light-count diagnostic and added a guard against +counting zero paired snapshots as a normal-join comparison pass. Final diagnostic +and restored normal release builds succeeded after these changes; production +source hashes match and the normal binary contains no policy probe. + +Local evidence is under `build/lighting-compatibility/`, with accepted sessions +`xbox-final`, `ce-verified`, `mcc` and `late-guarded`. Failed pilots remain clearly +separate. Logs, reports, manifests, captures and archived saves are retained; +no retail data is committed. + +Cleanup verified 664 archived save files (377,805,438 uncompressed bytes) in +18 archives. All staged maps/caches and per-run binaries were removed. Final +cleanup removed another 21,055,200 bytes of diagnostic executable/object and +temporary driver scripts. About 56.7 MiB of evidence remains in 254 files, +including failed-run diagnostics. Original maps/saves, toolchains and the normal +Windows build were preserved. `build/milestone4-cleanup.json` records the totals. diff --git a/docs/dynamic_lighting_optimisation.md b/docs/dynamic_lighting_optimisation.md new file mode 100644 index 0000000000..4e57581b63 --- /dev/null +++ b/docs/dynamic_lighting_optimisation.md @@ -0,0 +1,192 @@ +# Dynamic lighting performance follow-up + +This follows the [first sustained matrix](dynamic_lighting_performance.md). +The target is less redundant work with unchanged visual quality, defaults and +host policy. Field size (16 cubed), 1536 rays per refresh, eight admitted fields, +trace invalidation, temporal fades, light radii/colours and shader equations are +unchanged. CStencil and Modern remain outside scope. + +## Profile and changes + +`tools/lighting_performance_build.py --profile` adds CPU timers around tracing, +field reprojection, texture generation/upload and model binding. Binding time +includes any of the other operations it invokes and must not be added to them. +The test-only GPU fixture wraps draws in `GL_TIME_ELAPSED` queries every 32nd +frame. It polls availability before reading and skips sampling if its bounded +ring fills, rather than synchronising the CPU with the GPU. Query semantics are +from the [Khronos timer-query specification](https://registry.khronos.org/OpenGL/extensions/ARB/ARB_timer_query.txt); +the fixture is independently implemented. GPU rows classify other draws (0), +models with selected lights (1), selected world diffuse passes (2), and selected +specular passes (3). Model timing includes the complete material draw, not just +the additional lighting instructions. Query overhead can perturb rendering; +the sustained matrix uses a separate build without GPU queries or phase timers. + +Two 120-second profiles after 30 seconds of warm-up used native 2560x1440, +the same quality settings as the first matrix, and fifteen Heroic Carousel bots. +Before optimisation, mean trace/field/texture CPU times were 3.63/0.64/0.32 ms +per rendered frame. Sampled GPU model/diffuse/specular draws averaged +0.217/0.118/0.075 ms per sampled frame; other draws averaged 4.44 ms. +This identifies CPU tracing as a larger target than changing lighting shaders. + +Three conservative changes remove repeated work: + +- `plasma_occlusion.c` prepares history coordinates once per axis rather than + per cell. It keeps the exact coordinate arithmetic, sample accumulation order + and out-of-range fallback. Existing collision and fade logic is retained. +- `plasma_occlusion_gl.c` resolves uniforms once per linked program and uses + one immutable sampler instead of repeatedly looking up uniforms, assigning + sampler units and setting texture parameters on each model draw. A small + record in the backend's program entry is necessary because the backend owns + shader linking and lifetime; a feature-global cache keyed only by GL names + would be unsafe if names were reused. The feature owns the implementation. +- Equal diffuse/specular radii now share the same attenuation/visibility texture + upload. Their expressions are identical, including directional masks. Other + radii retain separate textures, and per-view invalidation still applies. + +The follow-up profile measured 2.09/0.39/0.25 ms for trace/field/texture work. +It also had fewer selected lights and refreshes, so neither those frame averages +nor the higher profile FPS establish an isolated speedup. Field CPU time per +update fell from about 0.107 to 0.086 ms in these samples; scenes still differ. +Sampled GPU model/diffuse/specular draws averaged 0.057/0.093/0.077 ms, with +3.26 ms in other draws. No lower-quality shader or reduced sampling budget was +introduced to obtain these numbers. +These profiles precede the final identical-texture sharing change; sustained +and final regression checks validate the combined implementation. + +## Acceptance + +The combined implementation is `e9fe5090`. Final self-review covered the complete +CPU, GL binding, integration, profiling and test changes, including allocation +fallback, cache ownership, per-view invalidation and teardown. No changes to +`source/`, settings defaults, host-policy code, network data or map loaders were +needed. There is no network-version change. + +The normal and capture/timing-only Windows release builds passed. All 58 focused +regression tests passed, including exact history-sample equivalence, equal versus +different specular extents, allocation fallback, program-owned uniform locations, +reserved texture units and the existing fade/door/chassis/activation contracts. +Android and web targets are absent from the local Ninja configuration; their +builds require CI and are not represented as local successes. + +All 21 final focused visual cases passed their runtime assertions and frame-cap +checks. At 30/60/120 FPS they cover crouched Needler holders, a shorter Grunt, +first-person AR lighting, Warthog chassis blocking, a moving door and enhanced +overshield charge. Additional 60 FPS cases cover disabled lighting, vertex-lit +models and CE Death Island. Contact sheets for all cases were inspected: +spill remains attached to the holders, the distant floor beneath them stays +dark, chassis blocking remains visible, and green/pink shield lighting follows +the animation. These are sampled 640x480 diagnostic captures, not a guarantee +of every frame or every map. Sustained tests use native 2560x1440 separately. + +The initial door attempts combined incompatible fixture modes and spawned no +projectiles. The initial CE attempt used a stale fixture filename. Those four +attempts are excluded, corrected and superseded by the final cases. The capture +runner now accepts both the original CE map filename and its historical fixture +name, without changing any engine loading path. + +A normal-build two-peer Windows smoke test completed with 37/33 two-player +snapshots and eight scripted firing events per peer, without logged assertions, +exceptions or shader errors. The host requested glow/overshield while both peers' +local shield preferences were off; other dynamic lighting was on for the host +and off for the client. This supplements the policy harness and unchanged policy +source; it is not internet crossplay or simulation-equivalence proof. + +Xbox c40 -> MCC Mercury Falling -> CE Death Island -> Xbox Blood Gulch +transitions passed with lighting off at 30 FPS and on at 120 FPS. Each run +completed all three switch commands, logged the MCC load and CE conversion, +returned to Blood Gulch and exited without exceptions. These are bounded +render/lifecycle checks, not full campaign compatibility claims. + +The [platform workflow](https://github.com/chestahh/GulchCE/actions/runs/40240939785) +passed Linux, Windows, Android and web builds and their configured checks. +The separate [MCC validation workflow](https://github.com/chestahh/GulchCE/actions/runs/40240939807) +also passed. Visual observations remain the Windows GPU captures described above. + +## Sustained follow-up + +The matrix uses the same native 2560x1440 setup as the first pass: an Intel +Core i7-14700K and NVIDIA RTX 5070 Ti, 8x MSAA, 16x anisotropic filtering, +1024-pixel shadows, per-pixel lighting and highest model detail. Each cap has +one disabled control and one enabled run, with fifteen Heroic bots and a +scripted player in Carousel. Each run has thirty seconds of warm-up followed +by five measured minutes. Runs are sequential, with no competing builds or +other test instances. Original player settings and saves are not modified. + +The timing-only build was produced before the implementation commit was made; +its manifest therefore names the parent commit. All seven recorded production +source/header hashes match `e9fe5090`, and its `profile` field is false. The +normal executable has been restored without the test instrumentation. + +The report retains raw timing and separately excludes the fixture's explicitly +marked screenshot frames from its pacing summary. Other stalls remain in the +reported results. Bot combat is not an identical replay, so comparisons with +earlier runs describe observed workloads, not an isolated percentage speedup. + +| Cap | Lighting | Average FPS | p99 frame time (ms) | 1% low FPS | Frames over 50 ms | Peak private memory (MiB) | +| --- | --- | ---: | ---: | ---: | ---: | ---: | +| 30 | Off | 30.00 | 33.532 | 29.55 | 0 | 701.6 | +| 30 | On | 30.00 | 33.539 | 28.71 | 0 | 719.6 | +| 60 | Off | 60.00 | 16.828 | 56.53 | 0 | 699.0 | +| 60 | On | 59.98 | 19.528 | 45.09 | 0 | 724.2 | +| 120 | Off | 119.63 | 10.298 | 86.86 | 0 | 717.6 | +| 120 | On | 105.96 | 16.387 | 52.80 | 1 | 765.5 | + +Each measured span is approximately 300 seconds. Fifteen marked capture frames +are excluded per run; raw summaries remain in each report. The 120-on case's +60.298 ms stall is retained, and no case recorded a frame over 100 ms. Bot logs +show continued combat, kills and respawns. All six cases exited normally with +no logged assertions, exceptions or shader errors. All six native-resolution +contact sheets were inspected: geometry, weapons, characters and combat effects +remain intact, with no obvious corruption. Sparse stills cannot establish +continuous temporal smoothness; the focused visual matrix supplements them. + +The earlier enabled runs averaged 30.00/58.79/84.56 FPS at 30/60/120 caps, with +p99 times of 33.402/21.788/22.282 ms. This follow-up demonstrates better observed +60/120 throughput and tails, but the disabled 120 control also improved from +103.68 to 119.63 FPS. Different scenes and execution conditions prevent +attributing the complete difference to these code changes. + +Thirty FPS remains supported by this workload. Sixty FPS is now sustained on +average, but its 19.53 ms p99 and 45.09 FPS 1% low leave frame-pacing acceptance +open. At 120, enabled per-minute averages were 100.95, 109.67, 109.02, 104.66 +and 105.51 FPS: there is still a material gap to the target. Do not mark +Milestone 3 or the 1.0 performance baseline fully accepted from these results. + +Disabled cases recorded zero selected feature lights and zero occlusion work. +Enabled cases reached the eight-field limit, selected up to 27/29/26 lights +at 30/60/120 respectively, and selected lights in 96.9/98.5/95.3 percent of +frames. Mean CPU occlusion updates were 5.01/4.57/2.46 ms. Those averages depend +on scene content and cache reuse; lower per-frame cost at 120 does not establish +better efficiency. The earlier phase profiles identify collision tracing as +the next area to investigate, without reducing ray coverage or changing fades. + +Memory also needs longer-duration investigation. The 120-on process's first +and last sampled minute averaged 706.0 and 762.2 MiB private memory, compared +with 699.4 and 715.3 MiB for its disabled control. These windows include +startup/shutdown margins and are not the gameplay timing window. Both enabled +and disabled runs grew, and neither allocation provenance nor a steady-state +plateau has been established. This is not a leak-free endurance claim. + +## Evidence and cleanup + +Local evidence is under `build/lighting-performance/optimised-{cap}-{off,on}` +and `profile-{before,after}-120`: frame/phase/GPU CSVs where applicable, +settings and build manifests, memory samples, reports, logs and PNG captures. +The combined sustained report is `build/lighting-optimisation-sustained.json`; +the visual, network and transition reports use the same optimisation prefix. +Retail data and captures are not committed. + +Final audit verified all recorded production hashes, restored normal-build +instrumentation state, local documentation links, six full run durations, +disabled-work counters and the eight-field bound. The implementation's final +58-test regression run and CI results above apply to the unchanged production +commit; subsequent edits only record acceptance evidence. + +Cleanup removed staged maps and generated map caches after each run. The final +audit removed 247 remaining disposable binaries, fixture objects and superseded +captures (131.8 MiB), preserving the earlier attempt logs and contact sheets. +All 618 archived inactive test-save files (about 1060 MiB loose) were verified +against their path/hash manifests. About 327 MiB of evidence and compressed +saves remains; `build/lighting-optimisation-cleanup.json` records the inventory. +No test game remains running. Original maps/saves, previous milestone evidence, +toolchains and the normal Windows build are preserved. diff --git a/docs/dynamic_lighting_performance.md b/docs/dynamic_lighting_performance.md new file mode 100644 index 0000000000..4d728cd636 --- /dev/null +++ b/docs/dynamic_lighting_performance.md @@ -0,0 +1,161 @@ +# Dynamic lighting: sustained performance acceptance + +This extends the short [visual acceptance runs](dynamic_lighting_acceptance.md). +The subsequent [profiling and optimisation pass](dynamic_lighting_optimisation.md) +records changes and follow-up measurements; the values here remain the original +baseline. +It measures a sustained combat workload; the earlier capture averages alone +were not evidence of sustained performance. Results are specific to the tested +hardware, quality settings and scene. + +## Method + +The Windows portable release configuration is `--portable --release --lto=off +--pgo=off`, based on `dynamic-lighting-test` at `409235b0`. The machine has an +Intel Core i7-14700K and NVIDIA RTX 5070 Ti. Native resolution is 2560x1440. +The test copies the user's relevant graphics preferences into an isolated +configuration: 8x MSAA, 16x anisotropic filtering, 1024 shadows, per-pixel model +lighting, highest model detail, HDR off and classic_honeycomb2 shield appearance. +The user's original configuration is read, never edited. + +Each case uses one hidden game instance, fifteen Heroic bots and the scripted +local player in a Carousel Slayer match. The score limit is raised to 10,000 +to prevent an early match end. Real bot movement, weapon selection, firing, +damage, deaths and respawns provide combat; no fixture forces light placement +or changes gameplay. This is a crowded multiplayer workload, not a claim that +every Covenant emitter or campaign encounter is exercised. + +Each frame cap (30, 60 and 120) is compared with all nine dynamic lighting +options off and on. Animated Overshield follows the comparison switch too. +Glow Intensity remains DEFAULT. Local matches use local preferences, leaving +the existing network host-policy implementation unchanged. V-sync is disabled +to let the selected cap control pacing. Thirty seconds of warm-up precede +five measured minutes. Cases run sequentially to avoid competing for GPU time. + +The [test builder](../tools/lighting_performance_build.py) installs the +[passive timing fixture](../tools/fixtures/lighting_performance.c) temporarily. +It records frame intervals using the engine's microsecond performance counter, +selected lights, scene lights and occlusion update work into a buffered CSV. +Occlusion work timing covers collision traces and visibility-field updates; +it excludes texture upload and GPU rendering. These are elapsed CPU-side times, +not GPU timer-query results. Occlusion update counts refer to the preceding +render window. A manifest records production source and executable hashes. +The builder restores all production sources and rebuilds the normal executable +in its finally block; ordinary builds contain none of this instrumentation. + +The [runner](../tools/lighting_performance_run.py) samples process private +memory and working set every five seconds and captures a frame about once a +minute. Both raw pacing and pacing excluding the capture frame plus two following +frames are reported. Real stalls are retained. The 1% low is 1000 divided by +the mean duration of the slowest 1% of frames; p95/p99 are frame durations. +Per-minute results expose deterioration hidden by a single overall average. +Configuration, frame data, memory samples, bot telemetry and images are retained +with each case. Bot matches can diverge, so these are comparable workloads, +not frame-for-frame deterministic image or speed comparisons. + +```sh +python tools/lighting_performance_build.py +python tools/lighting_performance_run.py --data-root --settings --fps 120 --enabled 1 --label combat-120-on +``` + +Desktop configuration belongs beside the executable. The runner stages its own +executable and configuration, uses separate data/save paths and removes its map +copies and binaries after each run. Test saves are archived losslessly with +original relative paths and verified SHA-256 hashes before loose copies are +removed. Original game data and saves are preserved. Windows local bot matches +still require working loopback networking. The initial sandboxed/configuration +pilot is excluded from acceptance. + +## Results + +The six normal-quality cases completed on 25 October 2026: thirty measured +minutes of combat, plus warm-up. Values below exclude fifteen marked capture +frames per case; the raw results remain in each report. Frame budgets are +33.33, 16.67 and 8.33 ms respectively. + +| Cap | Lights | Average FPS | p99 ms | 1% low FPS | Frames over 50 ms | +| --- | --- | ---: | ---: | ---: | ---: | +| 30 | Off | 29.92 | 33.44 | 23.39 | 1 | +| 30 | On | 30.00 | 33.40 | 29.78 | 0 | +| 60 | Off | 60.00 | 16.73 | 59.25 | 0 | +| 60 | On | 58.79 | 21.79 | 44.26 | 0 | +| 120 | Off | 103.68 | 14.83 | 54.53 | 3 | +| 120 | On | 84.56 | 22.28 | 41.37 | 1 | + +**Steady 30 FPS is supported for this workload. Locked 60 and 120 FPS are not.** +The off result also misses 120, so the entire deficit cannot be assigned to +dynamic lighting. Different bot battles prevent treating the on/off difference +as an exact isolated cost. The 30-off run includes an 839 ms stall, and 120-off +includes three stalls over 100 ms. They occurred outside capture exclusions and +remain in the results; they do not establish that enabling lighting cures stalls. + +The 120-on per-minute averages were 92.7, 98.1, 82.0, 65.0 and 85.0 FPS. +Recovery in the last minute argues against a simple continuously worsening +slowdown, but does not prove thermal stability or absence of leaks. Peak private +memory was 710.5 MiB at 30-on, 707.4 MiB at 60-on and 765.2 MiB at 120-on. +The 120-on first/last sampling windows rose from approximately 686.8 to 763.7 MiB; +120-off rose from 735.7 to 746.6 MiB. These memory windows use process elapsed +time and include startup/shutdown margins, unlike the gameplay-relative frame +window. Resource residency and longer-duration memory behaviour need separate +investigation before claiming a leak-free endurance result. + +Enabled runs reached the eight-field occlusion update bound; selected lights +peaked at thirty in the 120-on case and were active in about 95% of its frames. +All off cases recorded zero selected feature lights and zero occlusion work. +Mean CPU-side occlusion update time was 3.91 ms at 30-on, 4.44 ms at 60-on and +2.85 ms at 120-on. The latter is a substantial part of an 8.33 ms budget, before +other CPU work or GPU rendering. Lower per-frame work at 120 is not evidence of +greater efficiency: scenes differ and the existing trace cache can be reused. + +Bot logs confirm ongoing combat, kills and respawns in every measured minute. +Every case exited normally with no logged assertion, exception or shader error. +The six contact sheets were inspected, including disabled controls at every cap. +They show intact geometry, weapon/character rendering, projectiles and combat +effects, with no obvious corruption in the sampled frames. Sparse stills do not +prove continuous temporal smoothness, every damage colour, or every emitter's +appearance; the focused visual cases remain documented in milestone 2. + +### Follow-up and validation limits + +A seventh five-minute diagnostic kept native resolution and lighting enabled, +but disabled MSAA in its isolated configuration. It averaged 84.87 FPS, with +22.29 ms p99 and a 39.97 FPS 1% low; occlusion updates averaged 3.17 ms. +Thus disabling MSAA alone did not demonstrate a remedy for this workload. +Different combat sequences still prevent an exact MSAA cost comparison. +Its captures show no obvious rendering corruption. The case is retained as +`diagnostic-120-aa-off`, separate from the normal-quality matrix. + +Keep performance acceptance open at 60/120. Profile the CPU occlusion update +and GPU lighting passes separately, then repeat the same sustained matrix after +any optimisation. In particular, retain the existing corner/chassis blocking +and smooth transitions when reducing update work; simply lowering the budget +without visual regression checks is not an accepted solution. + +This assignment adds reproducible measurement tools and evidence, with no +production rendering change. Review covered fixture ownership, source restoration, +timing boundaries, capture exclusions, process lifetime and cleanup. The small +fixture stays outside ordinary build discovery; its temporary hooks collect +data without changing light selection, simulation or host policy. No speculative +production refactor was justified by these measurements alone. Lighting remains +isolated and off by default. CStencil and Modern remain outside scope. + +The evidence lives locally under `build/lighting-performance/baseline-{cap}-{off,on}`: +`report.json`, `frames.csv`, `memory.json`, settings/build manifests, logs and +native-resolution PNGs. Retail maps and screenshots are not committed. The +instrumented Windows build and restored normal Windows build both succeeded. +Cross-platform and network behaviour are unchanged; this local performance +workload does not repeat or replace the milestone 2 platform, host-policy, +two-peer and map-family transition checks. + +Final validation passed all three reporter regression tests, local documentation +link checks and production-source hash restoration checks. The normal executable +does not contain the timing CSV marker. Review found no further necessary +production changes within this measurement assignment. + +Cleanup removed staged maps, generated map caches, per-run executables/DLLs, +the dedicated measurement binary and its leftover object. The 337 inactive +test-save files (200.2 MiB loose) were archived with paths and verified hashes. +Approximately 204.6 MiB of raw results, logs, native captures and compressed +saves remains for diagnosis; `build/m3-cleanup.json` records the final inventory. +No benchmark process remains. Original data, user saves, earlier evidence and +the normal Windows build were preserved. diff --git a/docs/dynamic_lighting_release.md b/docs/dynamic_lighting_release.md new file mode 100644 index 0000000000..9228cbdca0 --- /dev/null +++ b/docs/dynamic_lighting_release.md @@ -0,0 +1,483 @@ +# Dynamic lighting 1.0 + +The GulchCE dynamic lighting 1.0 baseline was accepted by the project owner on +2026-10-27 and promoted from `dynamic-lighting-test` through `testing` to `main`. The known +performance and memory limitations below remain; acceptance does not establish +sustained 120 FPS or universal map compatibility. +CStencil and Modern shadows remain separate, later work. + +## Disabled desktop shader isolation + +Desktop and web model draws now select stock shader variants whenever no +optional model light is selected. This removes optional shader helpers and +samplers from those variants and skips their GPU setup. Enhanced variants are +compiled lazily, cached separately and selected using the existing effective +light mask, including host-controlled Shield Glow. Defaults remain off. + +This closes a gap in the previous disabled-path checks: no submitted feature +lights did not establish that the underlying shaders and sampler setup were +stock. Previously recorded disabled performance results used the extended +shaders and must not be treated as measurements of this corrected path. +No FPS or memory improvement is claimed without a new measured comparison. +First-use shader hitches and the unresolved sustained-performance/memory +limitations below remain; used shader variants retain context-lifetime caches. + +See the [rendering guide](reading/rendering.md#dynamic-lighting-10) for variant +ownership and the unchanged Android boundary. + +The focused Windows validation passed 125 tests covering shader variants, +source-cache reuse, light lifecycle, occlusion, host policy, Android exclusion +and MCC shader boundaries. Generated model GLSL was compared with the prior +revision for 67 real vertex programs, packed/unpacked inputs and per-vertex/ +per-pixel modes: enabled output was byte-identical, and disabled output matched +the prior translator with its optional additions excluded. Desktop, web and +Android preprocessing were checked separately. + +Six short rendered Blood Gulch checks at 1280x720 passed at 30, 60 and 120 FPS, +with lighting on and off. Disabled runs selected no optional lights and made +no occlusion updates; enabled runs reached enhanced model draws. Captures were +inspected on an NVIDIA RTX 5070 Ti. These checks are not new sustained-performance +measurements or AMD hardware coverage. The local Windows portable release +build passed; Android/web targets are unavailable in this local toolchain and +require the platform CI builds. + +The rendered two-peer Xbox check observed joining, weapon changes, two respawns +and host-forced Shield Glow on a client with its local setting off. All 140 +stable policy samples agreed with the host, with no shader errors or reported +state divergences. Its strict paired-snapshot verdict remained incomplete: +the once-per-second logs were offset by more than the comparator's two-tick +window, so zero snapshots were paired. The Custom Edition Death Island check +passed the full scenario, including 80 seconds of paired snapshots and host +stock-shield policy overriding the client's setting. MCC `DigsiteMP/1` also +passed, with 64 seconds paired, respawns, weapon changes and independent local +lighting under the host's `players` policy. Neither scenario reported shader +errors or snapshot divergences. Initial sandboxed attempts +could not establish local sockets and are excluded from gameplay validation; +the working checks ran outside that sandbox, with internet publishing disabled. + +## Android compatibility fallback + +Following reports of missing first-person geometry and dark models on multiple +Android device families, Android builds exclude the optional lighting modules, +material glow overrides, model-shader additions and extra sampler bindings. +The supplied clip shows these symptoms on a Custom Edition map; it does not +establish the underlying driver error. Source inspection found that the added +model shader code and sampler setup were present even with all toggles off. + +Android now links inert feature hooks that preserve stock light values and the +overshield surface reset. The Dynamic Lighting menu and its default config keys +are unavailable there; old saved values cannot enable the omitted code. Stock +lighting and effects remain, as do Animated Overshield surfaces. Network policy +and messages are unchanged: Android's lack of Shield Glow rendering does not +change the host's choice for other clients. Desktop and web implementations, +AMD/NVIDIA workarounds and Xbox/CE/MCC loading boundaries are unchanged. + +See [Android lighting availability](../port/android/README.md#lighting-availability) +for the build boundary. Device testing is required before claiming the reported +rendering failures are resolved; build and harness checks alone cannot do that. + +## Promotion to testing + +The 1.0 promotion combines `testing` at `87eb88e2` with the complete +`dynamic-lighting-test` history through `2e21f098`. It retains testing's +controller remapping, automatic button styles, player-only shield looks, +GPU frame pacing and desktop program-binary cache. The feature modules and +AMD/NVIDIA shader translation fixes are unchanged from the accepted branch. + +Two merge conflicts needed integration: shared fragment shaders now register +their source hash once with the upstream disk cache, and menu generation +retains both the lighting screen's help height and dynamic controller help. +The real-source cache harness checks hash registration, including a negative +mutation; generated-menu checks cover both help-widget contracts. No new +feature hook, network message, default or host-policy rule was introduced. + +The merged Windows portable release build passed. Focused lighting, menu, +controller, policy, map-boundary and network-comparator checks passed: 297 +tests, with nine skips (five POSIX process cases and four optional map-reference +checks whose local inputs were absent). Ordinary/full-LTO light-storage checks +and their corruption negative control also passed. Menu regeneration produced +only the intended lighting screens. + +Three hidden 22-second native runs loaded Xbox c40 at 1280x720/60 FPS. The +enabled cold run wrote 49 program binaries; the enabled warm run loaded all +49, and the disabled run loaded 48. Warm/off runs linked no new programs; +none reported rejected binaries, shader errors or a crash. Captures show the +opening cinematic rendering normally. This is a cache integration smoke +check, not a new combat or performance acceptance run. An initial local-game +fixture remained in menus and was rejected; the corrected fixture uses a +copied profile and direct map load. Both attempts retain their diagnostic logs. + +A hidden enabled transition check loaded Xbox c40, MCC Mercury Falling, CE +Death Island and Xbox Blood Gulch in one process. All three transitions reset +the simulation tick as expected; shield activation remained enabled, with no +exception or forced shutdown. The passive probe was then removed and the +normal build restored. Staged maps and generated map caches were removed; +test saves were archived and verified before removing their loose copies. + +The existing visual, multiplayer and host-policy evidence below remains +applicable to unchanged feature code. Local Android/web toolchains remain +unavailable; the testing push runs the platform and MCC workflows. Known +performance and memory limitations remain documented below. + +The first MCC CI run exposed an existing mock-header defect in testing's +texture-bridge harness: both the fixture and included bridge pull in its +unguarded `zlib.h`. Linux C99 rejects the duplicate `uInt` typedef under +`-Werror`; the Windows compiler accepted it. A follow-up adds the missing +mock-header guard without changing runtime code or suppressing diagnostics. +All ten texture-bridge cases and fifteen fragment-cache cases passed locally +after that correction; CI supplies the Linux confirmation. + +## Promotion to main + +The main promotion merges all of `testing` through `a83584c6` into main at +`08baa774`. The merge is conflict-free and its implementation is identical +to testing; only documentation differs, retaining main's release-checksum +instructions and recording availability on main. Dynamic lighting remains +off by default, with the existing host policy and compatibility boundaries. +Controller, HUD and upstream renderer updates already integrated on testing +are included in the same promotion. The main workflow builds and validates +the release packages; the known limitations below remain applicable. + +The final testing CI passed 1,757 engine/harness cases before exposing three +controller-artwork regeneration failures on Pillow 13. Its new RGBA thumbnail +reduction pass differed from the committed Pillow 12.3 output. The follow-up +sets `reducing_gap=None` in the artwork generators; all 28 controller/HUD +checks pass with both Pillow versions, preserving exact committed pixels. +No shipped artwork or runtime code changed. The main promotion also passed +174 changelog/release-note checks and generated its required player notes. + +## Player controls + +Open **Settings > Video Setup > Dynamic Lighting**. All lighting switches +default to **Off**; Glow Intensity defaults to **Default**. Saving applies the +pending choices, cancelling discards them, and Defaults restores the stock +choices for this screen. Saved choices persist across launches. + +| Menu row | What it controls | +| --- | --- | +| Projectile Lights | Existing plasma, rocket and Covenant projectile profiles, armed plasma grenades and flamethrower streams. | +| Muzzle Flash Lights | Extra short-lived weapon illumination, including the Warthog turret and both Scorpion guns; stock flash and explosion effects remain intact. | +| Weapon Glow | Energy swords, plasma charge/heat, Grunt/Hunter fuel rods, AR counters and Needler crystals. | +| Shield Emitters | Blue/orange Jackal shields and Covenant stationary shields, including damage colours. | +| Vehicle Lights | Supported Covenant running/engine glow and directional Warthog/Scorpion headlights. | +| World Emitters | Overshield/active-camouflage pickups and visible green teleporter surfaces. | +| Light Occlusion | Optional blocking for projectiles and emitters. Muzzle and vehicle lights always request collision blocking, including their chassis. | +| Shield Glow | Player/unit shield spill, subject to the host's shield-effects policy. | +| Glow Intensity | Default or Light Show intensity for Shield Glow; this does not enable it. | + +Weapon Glow and Shield Emitters consolidate the old per-effect menu rows. +Both rows offer only OFF and ON. Older saved dynamic-lighting preferences +reset to OFF once; later player choices persist. There is no CUSTOM state. +See the [emitter expansion walkthrough](reading/emitter_expansion.md) +for exact scope, lifecycle, budgets and map-asset limits. The historical 1.0 +acceptance results below predate these additions; they are not evidence for +the expansion's runtime acceptance. + +**Animated Overshield** remains in **Video Setup > Extra Effects**, also off +by default. First-person shield surfaces additionally depend on **Arm +Shields**. In multiplayer the host's **Shield Effects** policy remains +authoritative; **Players Choose** permits each player's shield preferences. +Other lighting choices are local presentation settings and do not change +damage, collisions or network simulation. A stock host policy can override +the local shield toggles; that is intentional. + +Frame interpolation is a separate setting and supplies smooth poses between +simulation ticks. Existing per-pixel lighting is also separate. Neither is +silently enabled by the lighting submenu. Custom maps must use a supported +tag/profile; this feature does not infer arbitrary modded weapon semantics. +Xbox, CE and MCC retain their separate loading paths. + +## Implementation and final review + +Start with the [rendering walkthrough](reading/rendering.md) and +[shield walkthrough](reading/shield_lighting.md). The +[implementation history](plasma_lighting.md) preserves earlier decisions and +validation; its initial prototype restrictions are historical. The +[emitter notes](covenant_emitter_lighting.md), +[compatibility report](dynamic_lighting_compatibility.md) and +[stability investigation](dynamic_lighting_stability.md) contain detailed +evidence and its limits. + +The Milestone 5 review follows the combined projectile, muzzle, held-emitter, +shield and overshield paths through settings, host policy, temporary light +ownership, rendering hooks, occlusion, shader generation and lifecycle +cleanup. Capture and profiling fixtures remain in tools, outside normal +builds. Bounded storage, salted object identities, authored-light precedence, +platform stubs, collision checks and shader-cache source comparisons are +necessary protections and were retained. + +Two feature-local simplifications have a concrete benefit: + +- `covenant_visible_profile` in + [covenant_lighting.c](../port/linux/game/covenant_lighting.c) returns its + validated profile to the caller. Admission no longer repeats object/tag + lookup after validation. With ten eligible projectiles and eight light + slots, the harness observes ten tag queries on initial admission instead + of twenty-six, and eighteen on a retained update instead of twenty-six. + The visibility/ownership validation is preserved; profile zero remains + valid. These are lookup counts, not a measured FPS improvement. +- `overshield_effect_find_values` in + [overshield_effect.c](../port/linux/game/overshield_effect.c) shares the + existing active body/arms lookup. Colour selection no longer scans the + effect array twice or computes unused fade geometry. Activation, host + policy, charge timing, fade equations and colours remain unchanged. + +No shared engine, network protocol, map loader, AMD/NVIDIA workaround or +shader-cache behaviour is changed by these final refactors. Existing shared +hooks remain necessary because feature modules cannot independently intercept +the engine's light submission, interpolated model draw and frame cleanup. +This pass adds no shared hook and does not merge map-family implementations. + +## Known limitations + +- Sustained 120 FPS is not established. The earlier eight-minute enabled + busy-combat run at native 2560x1440 averaged approximately 115.98 FPS at a + 120 cap. Short captures at 30/60/120 FPS are visual checks, not endurance + certification. +- Shader compilation/program linking can still hitch. A capture-free, + lighting-disabled run recorded a 51.229 ms frame containing 10.977 ms of + shader compilation and 36.805 ms of program linking. The earlier 412/221 ms + stalls were not reproduced, and their cause remains unresolved. +- Memory has not demonstrated a plateau. The enabled capture-free run grew + approximately 3.64 MiB between early/late windows, with a later fitted + trend of 1.52 MiB/minute. The disabled control also had a late approximately + 27 MiB jump near shader compilation. Allocation ownership is unresolved; + these observations neither prove a leak nor establish stability. The + completed shader-cache deduplication does not explain all remaining growth. +- Runtime evidence is representative, not exhaustive: Windows/NVIDIA runs + do not certify AMD hardware, all drivers, every custom map, internet play + or Android/web visual parity. Platform builds and targeted regression tests + establish narrower facts. See the linked reports for actual checks. + +The final optimisations above do not claim to fix these limitations. The project +owner's playtest acceptance completes the 1.0 sign-off with these limits documented. + +## Milestone 5 validation and delivery + +The final functional changes are in `7b1e8c02`; `152142a4` adds documentation +and corrects an overshield menu-location comment. The Windows playtest uses +`152142a4`, built with `--portable --release --lto=off --pgo=off`. + +| Check | Observed result | +| --- | --- | +| Focused local regressions | 205 passed; five POSIX process/launcher cases skipped on Windows. Includes ownership, off/reset paths, falloff/occlusion, shield policy and body/arms effects, fragment-cache and visibility contracts, settings and MCC networking. | +| Touch-menu unit | Passed separately with the installed Windows toolchain's explicit x86 target and CRT link flags. The generic pytest invocation did not supply those flags; no touch implementation change was needed. | +| Short rendered captures | Xbox Needler at 30/120 FPS, CE Needler at 60 FPS, and Xbox overshield charge at 60 FPS with Shield Glow on/off all passed the runner's checks. | +| Mixed-setting peers | Two hidden Windows instances at 1280x720/60 FPS, Xbox Blood Gulch, with opposite local lighting choices and a host-forced shield policy. Both observed two respawns of the same player and inventory changes. All 139 stable policy samples matched; 81 seconds of paired snapshots had no comparator divergence. | +| Map lifecycle | One enabled Windows process loaded Xbox c40, MCC Mercury Falling, CE Death Island and Xbox Blood Gulch, with three tick resets, expected shield activation and no exception. | +| Platform CI | [Windows, Linux, Android and web passed](https://github.com/chestahh/GulchCE/actions/runs/40266569136), including Linux tests, browser/native WebRTC checks and Chromium/Firefox web checks. [MCC validation also passed](https://github.com/chestahh/GulchCE/actions/runs/40266569124). | +| Delivered ZIP | Archive integrity and every packaged file verified; extracted executable started and displayed the Dynamic Lighting menu. All nine lighting booleans plus Overshield remained false, intensity Default and host policy Stock. No diagnostic fixture strings were present. | + +The five short visual scenes use 640x480 isolated captures. Frame-log averages +were 29.19/119.99 FPS for Xbox Needler, 59.96 for CE Needler and 58.80/60.00 +for shield spill on/off; all met the runner's five-percent tolerance. Image +inspection showed purple projectile spill, the retained overshield charge +rise and green-to-pink layer transition. With Shield Glow off, the independently +enabled overshield surface remained and the added spill disappeared. These +are scoped visual observations, not sustained performance measurements or +exhaustive aesthetic acceptance. The capture executable predates only the +menu-location comment; source hashes and that exact comment-only difference +were checked. The multiplayer/lifecycle probe and normal build use `152142a4`. + +Local Android/web targets are unavailable in this Windows configuration; +fresh CI supplies those build checks. CI uses debug builds on this branch, +while the local playtest is release. There was no new AMD hardware test or +retail internet game. The broader Milestone 4 map/policy matrix and prior +menu interaction evidence remain in the linked reports; this pass did not +repeat that entire matrix. The initial test selection exposed a harness +extraction dependency on the new overshield helper, which was corrected +before the final passing suite. No assertion or compatibility guard was +removed to obtain a pass. + +Review also confirmed that the final changes leave `source/`, platform +renderer code, map loaders, host-policy code and network version untouched. +The normal build was restored after each diagnostic build. No new shared +hook, gameplay mutation, forced policy or diagnostic is shipped. The review +retained necessary bounded caches, checks and platform stubs instead of +removing them solely to reduce code size. Fifty-three local documentation +links and the newly named functions were checked. + +Delivery is `GulchCE-dynamic-lighting-windows-152142a4.zip` under the primary +checkout's `build/playtest/`, with an adjacent `-PLAYTEST.txt` and `.sha256`. +The 13.4 MiB ZIP includes its own `PLAYTEST.txt`, stock configuration, +`BUILD.json`, source download links and licence notices; it contains no maps +or saves. Its SHA-256 is +`bce57d6b01ef3733c9f374257ba49070f1306eef04070d9e055cc0ecd724ff06`. + +Evidence remains under the active checkout's `build/milestone5-*`, +`build/plasma-visual/*-m5-*` and `build/lighting-compatibility/m5-*`. +All owned processes exited. Runners removed staged maps/caches; final cleanup +removed approximately 60.6 MiB of test binaries/objects and 186.7 MiB of +redundant capture frames. Representative projectile images, all shield/menu/ +network/transition captures, complete logs and manifests remain. All 167 +archived test-save files (180.1 MiB uncompressed) passed SHA-256 verification. +Approximately 50.3 MiB of diagnostic evidence remains, besides the delivery +ZIP and required normal Windows build/symbols. Original maps, saves, +toolchains, other worktrees and earlier milestone evidence were preserved. + +## Scorpion, Hunter and first-person AR additions (2026-10-27) + +Implementation and Windows playtest revision: `2522c432`. These additions use +the existing Muzzle Flash Lights, Fuel Rod Glow and AR Counter Glow options. +All remain off by default. See the [muzzle notes](muzzle_lighting.md) and +[emitter notes](covenant_emitter_lighting.md) for tag/marker evidence and tuning. +The existing performance and memory limitations above remain unresolved. + +Self-review covered the combined feature modules, seven marked shared draw +lines, harnesses, capture fixtures, generated menu help and documentation. +Scorpion triggers share the existing bounded pool but retain independent +pulses. A profile flag replaces the repeated Warthog-only occlusion name test. +The Hunter reuses the fuel-rod profile through its animated biped marker; +its model-less weapon remains excluded. The AR material lookup is shared by +its two helpers, and the exact output state is restored after the display +draw. World-model values and shared fade history are unchanged. No loader, +network protocol, host policy, shader translator or AMD/NVIDIA workaround +was modified. Broader renderer refactoring was unnecessary for this scope. + +Sixteen hidden Windows captures on an NVIDIA RTX 5070 Ti, driver 617.42, +used isolated data at 640x480, per-pixel lighting and the requested frame caps. +The three new cases passed at every cap; observed mean FPS was: + +| Case | 30 cap | 60 cap | 120 cap | +| --- | ---: | ---: | ---: | +| Scorpion, both guns | 30.00 | 59.99 | 120.04 | +| Hunter rods, Xbox c40 | 30.00 | 60.02 | 119.99 | +| First-person AR, Xbox Blood Gulch | 30.00 | 60.05 | 120.02 | + +The remaining seven cases were 60-FPS off controls for each addition, +Warthog and third-person AR regressions, and CE Death Island AR/Scorpion +captures. Off controls selected no added lights. Images inspected at all +three rates showed warm Scorpion flashes with a dark underside in the tested +orientations, green Hunter forearm spill and a brighter readable AR screen. +Both Scorpion triggers submitted independent pulses; Hunter captures reached +model diffuse and specular draws. These are short visual checks, not sustained +performance measurements, exhaustive occlusion coverage or new AMD validation. + +The focused regression suite passed 206 tests, with five POSIX-only cases +skipped on Windows. COFF/full-LTO light storage and the standalone touch-menu +unit passed. The generic touch/web pytest run hit Windows CRT/link and path +assumptions; the touch unit passed with explicit x86/CRT flags. Local Android +and web build targets remain unavailable, so CI supplies platform validation. + +Two-peer rendered checks passed on Xbox Blood Gulch, CE Death Island and +MCC DigsiteMP with opposite local lighting choices. Host policy matched all +386 stable samples, both peers observed respawns and inventory changes, and +the existing comparator accepted 81/81/64 seconds of paired snapshots. +One enabled process then loaded Xbox c40, MCC Mercury Falling, CE Death Island +and Xbox Blood Gulch: three tick resets, expected shield activation, clean +exit and no logged exception. This checks representative transitions, not +campaign completion or every custom model reusing a stock tag name. + +[Windows, Linux, Android and web CI passed](https://github.com/chestahh/GulchCE/actions/runs/40432901781), +including debug builds, Linux tests, browser/native WebRTC and +Chromium/Firefox web checks. [MCC validation also passed](https://github.com/chestahh/GulchCE/actions/runs/40432901683). +CI skips release builds on this branch; the Windows playtest was built locally +in release mode. +These runs validate the implementation revision `2522c432`; this appended +acceptance record changes documentation only. + +The normal release ZIP uses `--portable --release --lto=off --pgo=off` and +contains no game maps, saves, symbols or capture fixtures. Its extracted +executable started, displayed the Dynamic Lighting menu, and retained all nine +lighting switches plus Overshield off, Default intensity and Stock host policy. +Archive integrity and every packaged file were verified. The ZIP SHA-256 is +`8650c86a10a64967f29193308445e96cd2f982aa895fa5231db57a16831d449d`. + +Evidence is under `build/lighting-extension-*`, +`build/plasma-visual/*-extension-*` and `build/lighting-compatibility/extension-*`. +Capture manifests identify the working-tree sources before commit; their only +later source differences are two explanatory comments and the Fuel Rod Glow +configuration description. Runners removed staged maps and caches and archived +test saves with hash verification. Final cleanup removed another 220.9 MiB of +diagnostic executables and redundant images, retaining sixteen representative +images per capture case, full logs, manifests and save archives. The per-run +evidence totals about 107.0 MiB, besides contact sheets, small build logs, the +13.6 MiB ZIP and the required normal build/symbols. Original game data, saves +and earlier evidence remain untouched; all test processes exited. + + +## AR world display and fuel-rod colour tuning (2026-10-27) + +Implementation revision: `f76fc69c`; comparison baseline: `9cac0595` (the +previous `2522c432` implementation plus its acceptance documentation). The +existing AR Counter Glow and Projectile Lights options remain off by default. +The world-model display now shares the first-person emissive material boost. +Its spill module is byte-for-byte identical between the capture builds; +recorded steady world-light RGB remains (0.156, 0.4225, 0.65). + +The exact shared Grunt/Hunter projectile exhaust gets less red and blue in +its render submission, retaining the authored green channel and modulation. +Read-only Xbox c40 trigger references establish that both weapons use that +projectile. Runtime tests below exercise this shared projectile definition, +not separate AI firing sessions for each weapon. The source light datum, +stock flare, trail, impact and explosion remain unchanged. See the +[emitter](covenant_emitter_lighting.md) and +[projectile](covenant_lighting.md) notes for policy and tag evidence. + +The combined review covered both feature modules, declarations, shared hooks, +fixtures, tests and documentation. It removed the redundant material-helper +view argument, kept AR spill and renderer translation untouched, and added +only a four-line marked hook for the private render-colour copy. The new +map-scoped tag cache uses existing reset boundaries. No loader, host policy, +network contract or AMD/NVIDIA workaround changed. The existing performance, +memory and approximate-occlusion limitations remain. + +Focused regressions passed: 207 tests, with five POSIX-only launcher/process +cases skipped on Windows. Ordinary and full-LTO light-storage checks passed, +including their deliberate pointer-corruption negative control. The new colour +case covers off, invalid owners, unrelated tags/lights, modulation, missing tags +and map resets. Existing emitter coverage retains exact third-person/first-person +spill gains and checks material-state restoration. + +Hidden, serial Windows captures used 1280x720, an NVIDIA RTX 5070 Ti (617.42), +per-pixel lighting and Light Occlusion. Both old and new enabled tuning were +captured at each cap and visually reviewed. Measured short-capture means: + +| Case | 30 cap | 60 cap | 120 cap | +| --- | ---: | ---: | ---: | +| AR world display, before | 30.01 | 60.02 | 119.85 | +| AR world display, after | 30.00 | 60.02 | 120.02 | +| Native fuel-rod flight/impact, before | 29.30 | 58.33 | 119.99 | +| Native fuel-rod flight/impact, after | 29.67 | 59.99 | 119.71 | + +The 60 FPS disabled controls selected no feature lights and performed no +occlusion updates. The first-person AR control retained its existing appearance. +A separate paired 60 FPS probe sweeps the real fuel-rod projectile along a +controlled path to show its surface/model spill without an impact immediately +overwhelming it; the native-flight cases above also retain collision and impacts. +These short visual captures include readback and initial shader work, and are +not sustained-performance or AMD-hardware certification. + +Comparison PNGs and source-image hashes are retained locally under +`build/ar-fuel-comparisons/`; complete reports, source manifests and logs are in +`build/plasma-visual/*-ar-fuel-*`. Comparisons use matching scene, camera, +settings and simulation ticks. Only cropping, identical resizing and labels +were applied; interpolated fractions and stock particle phases can differ. + + +The additional CE Death Island world-display capture passed at 59.02 FPS. +An initial Marine fixture was rejected because that multiplayer map contains +no Marine tag; it was replaced by the map's stock player model, with no game +code change. Eighteen captures completed successfully overall. A hidden enabled +transition run loaded Xbox c40, MCC Mercury Falling, CE Death Island and Xbox +Blood Gulch, with three tick resets and no exceptions or forced shutdown. +This checks those map boundaries, not every custom asset or multiplayer scenario. +No new multiplayer session was required for these render-only changes; the +existing host-policy and networking harnesses passed. + +The Windows portable release build was restored after each diagnostic build; +its executable contains no capture-fixture markers. Local Android/web targets +remain unavailable. [Platform CI](https://github.com/chestahh/GulchCE/actions/runs/40438187298) +passed Windows, Linux, Android and web jobs, including the Linux/web tests and +Chromium/Firefox checks. CI builds debug on this feature branch; release was +built locally. The MCC Windows adapter job passed. The separate Linux MCC +validator reached its ten-minute limit installing dependencies before tests +started. The targeted [retry](https://github.com/chestahh/GulchCE/actions/runs/40438187337) +passed both MCC jobs; no source or workflow change was needed. + +Cleanup removed staged maps/caches, three temporary diagnostic executables, +fixture objects and approximately 892 MiB of redundant images/binaries. All +121 archived test-save files passed SHA-256 verification. About 147 MiB of +comparison images, representative frames, complete logs/manifests and archived +saves remain, plus the normal build. User maps, saves, previous playtest packages +and earlier milestone evidence were preserved. diff --git a/docs/dynamic_lighting_stability.md b/docs/dynamic_lighting_stability.md new file mode 100644 index 0000000000..64d6f5ea2c --- /dev/null +++ b/docs/dynamic_lighting_stability.md @@ -0,0 +1,243 @@ +# Reduced dynamic-lighting stability check + +The approved 20-minute measured combat plan completed at revision +`14c1ebe1ab3d8c0371b245131276378596b45e45`: five minutes each at 30 and 60 FPS, +then ten minutes at 120 FPS. All three processes exited normally with no +detected runtime errors. The earlier, larger matrix was not executed. + +30 and 60 FPS were sustained in this workload. **120 FPS is not accepted as +locked**, and memory is not proven to have reached a plateau. This pass makes +no production changes and does not complete the 1.0 performance milestone. + +## Method and boundaries + +The runs used the Windows timing build, an NVIDIA RTX 5070 Ti (driver 617.42), +2560x1440, 8x MSAA, 16x anisotropic filtering, 1024 shadowmaps, per-pixel +lighting, highest model detail and 90-degree world/viewmodel FOV. HDR and HDR +output were off. Each fresh process ran Carousel with 15 Heroic bots and a +scripted player, with a 30-second warm-up before its measured interval. + +Runs were sequential in hidden windows with isolated data/save folders. +Resolve/Fusion and other game instances were absent at preflight. No builds +or harness tests ran concurrently with the measurements. The environment was +not otherwise continuously controlled. + +All optional dynamic-lighting settings were enabled only in these isolated +sessions. The build collected frame timing and aggregate occlusion timing; +profiling, per-ray diagnostics, shader-resource diagnostics and trace +verification were disabled. Process memory was sampled every five seconds. +Periodic screenshots excluded three marked frames per capture from the +reported pacing; raw timings remain available. Memory measurements include +capture allocations and do not attribute allocations to a subsystem. + +There was no matched lighting-off control or deterministic replay. Differences +between caps or earlier sessions cannot be attributed solely to the recent +fixes, and this pass does not measure their FPS or memory savings. + +## Frame pacing + +| Cap | Measured seconds | Average FPS | 1% low FPS | p99 frame ms | Worst frame ms | Frames over 100 ms | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | +| 30 | 299.97 | 30.00 | 29.80 | 33.406 | 34.252 | 0 | +| 60 | 299.98 | 60.00 | 58.41 | 16.751 | 27.577 | 0 | +| 120 | 599.99 | 116.30 | 64.01 | 13.140 | 412.305 | 2 | + +Neither the 30 nor 60 FPS run had a measured non-capture frame over 50 ms. +The 120 FPS run's per-minute averages ranged from 114.60 to 118.34 FPS; +1.66% of its measured frames exceeded 1.5 times the frame budget. + +The two 120 FPS stalls were consecutive, at frame-log times 408.965 and +409.187 seconds (including warm-up), lasting 412.305 and 221.453 ms. Both +were unmarked for capture exclusion and remain in the results. Their aggregate +occlusion times were 191.428 and 3.052 ms respectively, with six updates each. +The first therefore overlaps a large occlusion timing sample, but these wall +times alone do not distinguish expensive tracing, scheduling stalls or other +causes. No causal attribution is made from this run. + +Mean occlusion time was 2.952, 2.890 and 1.555 ms at the three respective caps. +The maximum selected-light counts were 26, 27 and 26; the eight-update-per-frame +occlusion limit held in every run. Lower mean per-frame occlusion time at a +higher cap is not by itself evidence of lower total tracing cost. + +## Process memory + +Values below are process private bytes in MiB. Early means cover process +seconds 90-150; late means cover 240-300 for the five-minute runs and 540-600 +for the ten-minute run. These fixed windows precede shutdown and use the +process sampler's clock, not the frame-log clock. + +| Cap | Early mean MiB | Late mean MiB | Change MiB | Peak MiB | +| --- | ---: | ---: | ---: | ---: | +| 30 | 645.92 | 644.48 | -1.44 | 657.93 | +| 60 | 644.24 | 644.86 | +0.62 | 656.94 | +| 120 | 641.93 | 647.07 | +5.14 | 650.33 | + +The 120 FPS run's private-byte regression slope over process minutes 5-10 +was approximately +0.89 MiB/minute. No large runaway increase was observed +within the approved interval, but the modest upward trend prevents a claim +of flat memory or leak-free operation. These measurements do not identify +whether the retained memory is useful caching, fragmentation or a leak. + +## Preservation, review and validation + +This is validation of the existing [damage-owner and shader-cache fixes](damage_and_shader_cache_fixes.md), +not another renderer change. Production source hashes matched the diagnostic +manifest and approved plan, and `source/`, `port/` and `tools/` had no diff from +the recorded revision. The normal Windows binary was restored without the +timing fixture. Lighting defaults, host policy, AMD/NVIDIA visibility-query +paths and Xbox/CE/MCC boundaries remain unchanged. + +The reporter's four tests passed before the runs. Final report checks verified +three complete intervals, normal exits, no reported runtime errors or +unexpected network players, enabled test lighting and bounded occlusion +updates. Contact sheets from all three runs were inspected: sampled combat +showed coloured lighting with no obvious new visual regression. Still images +do not establish continuous animation quality or exhaustive material coverage. + +The preceding fix report records 128 regression tests, four-platform CI, +map-family transitions and a two-player host-policy smoke test. That evidence +applies to the unchanged implementation; it is not represented as newly rerun +here. This pass used NVIDIA hardware only and did not repeat AMD hardware, +Xbox/CE/MCC transition, internet crossplay or comprehensive co-op tests. + +The final review covered the measurement setup, capture exclusions, memory +windows, source restoration and report limits. No production refactoring was +needed for this validation-only assignment. The remaining performance question +is the 120 FPS shortfall and its stalls; memory plateau remains unproven. +No additional endurance runs are queued. + +## Evidence and cleanup + +Local evidence is under `build/lighting-performance/stability-reduced-30-on`, +`stability-reduced-60-on` and `stability-reduced-120-on`, with the approved plan, +aggregate results, summary and cleanup report in `build/lighting-stability-*`. +Retail captures and test data are not committed. + +No owned game processes remained at cleanup. Each runner removed its staged +maps, caches and executable copies. Final cleanup removed another 42,107,741 +bytes of diagnostic executables/configuration and the fixture object, including +the unused resource-diagnostic build prepared for the larger plan. All 111 +archived test-save files (62,968,332 bytes uncompressed) were verified against +their SHA-256 manifests. About 108 MiB of useful evidence remains (59 files), +including logs, timings, captures and save archives. Original maps/saves, +toolchains and the normal Windows build were preserved. + +## Focused stall and memory investigation + +A subsequent investigation used the same production code at `d84409ac`, on +the same NVIDIA hardware, resolution, quality settings and Carousel bot +workload. It ran eight measured minutes with lighting on, then four with it +off, sequentially, each with a 30-second warm-up. Both exited normally without +detected runtime errors or unexpected players. No further endurance matrix +was launched. + +The Windows-only test builder now accepts `--stalls`, recording rendering +thread CPU time and shader compilation/linking time (including status-query +synchronization), alongside `--resources` counts. Resource diagnostics also +count vertex-layout objects, samplers, mirror buffers and framebuffers. +The runner's `--no-captures` disables image allocations and readback without +dumping shaders. These are diagnostic measurements, not clean FPS acceptance +runs. No GPU query path or production behaviour was changed. + +### Findings + +| Lighting | Measured minutes | Average FPS | p99 frame ms | Worst frame ms | Frames over 100 ms | +| --- | ---: | ---: | ---: | ---: | ---: | +| On | 8 | 115.98 | 12.978 | 25.092 | 0 | +| Off | 4 | 119.91 | 9.900 | 51.229 | 0 | + +The original 412/221 ms pair did not reproduce. The enabled run still missed +the sustained 120 FPS target even without large hitches, so those two issues +must not be conflated. The runs have different combat histories and durations; +their averages are not a precise measurement of lighting cost. + +The disabled run recorded a 51.229 ms frame at frame-log time 267.881 seconds. +It included one shader compilation (10.977 ms) and one program link +(36.805 ms), with 46.875 ms of thread CPU time. Thus a newly encountered +shader/program caused a concrete hitch independently of optional lighting in +this sample. This does not establish the cause of the earlier, much larger +pair. CPU accounting is coarse (15.625 ms steps observed); it is useful for +large stalls, not a precise per-frame CPU budget. + +The enabled run performed no further shader compilation or program linking +after frame-log second 120. From then until the end, programs stayed at 89, +distinct fragment sources at 78 and retained source text at 530,663 bytes. +Full-state key entries increased from 547 to 592: 45 additional structs, +about 12 KiB before allocator overhead, based on the current 32-bit layout. +Those aliases do not compile more fragment shaders. Render targets (6), +vertex-layout objects (10), samplers (29), mirror buffers (4), framebuffers +(11) and immediate-vertex capacity (512) stayed constant throughout the +measured enabled interval. Texture entries varied between 226 and 290; +their guest payload was lower at the end than at the start. Counts and guest +payload do not measure driver-internal allocations. + +| Lighting | Early mean MiB | Late mean MiB | Change MiB | Process peak MiB | +| --- | ---: | ---: | ---: | ---: | +| On | 645.88 | 649.51 | +3.64 | 652.23 | +| Off | 645.16 | 645.15 | -0.00 | 674.17 | + +Early memory windows are process seconds 90-150. Late windows are 420-480 +for enabled and 180-240 for disabled; peaks include startup and the post-measurement +tail before exit. Private memory +fluctuated by several MiB, including downward steps, rather than increasing +monotonically. The enabled run's fitted slope over process seconds 240-480 +was +1.52 MiB/minute. Comparing the same early/180-240 windows gives +1.48 MiB +enabled and approximately zero disabled. The shorter control cannot establish +whether later growth is feature-specific. + +The control's flat comparison windows are not a flat whole session: private +memory rose from 647.08 MiB at process second 275.23 to 673.91 MiB at 280.25, +then stayed high until exit (674.17 MiB at 295.25). This late approximately +27 MiB jump was near the compile/link hitch; the frame and process logs have +different origins. Compiler/driver allocation is therefore a concrete target +for an allocation trace, but temporal proximity does not prove ownership. +It also cannot explain the enabled run's later growth without compilation. + +Removing captures did not remove the enabled run's upward trend. The later +increase was not caused by new shader compilation/linking, and the measured +cache entries do not account for its magnitude. Allocation ownership remains +unresolved: these observations distinguish neither allocator retention from +a leak nor engine allocations from driver allocations. The lighting collision +batch itself has fixed storage. Also, Windows write tracking deliberately +uses protected-page faults, so the earlier process fault-count spike is not +evidence of disk paging by itself. + +The useful next memory diagnostic is an allocation-stack trace spanning an +early and late window, rather than another broad FPS matrix. The concrete +compile/link hitch provides a separate target for evaluating shader warm-up; +no prewarming, asynchronous compilation, eviction or rendering changes are +justified as a fix for the original pair by this evidence alone. + +### Tool correction, validation and cleanup + +The old fixture marked periodic capture slots even when the screenshot +directory was empty. The game correctly skipped image allocation/readback, +but the reporter still excluded those frames. The builder now checks the +directory before marking captures, and the reporter retains all frames when +captures are disabled, including old binary markers. A regression test keeps +a real 200 ms hitch in a marked slot with captures disabled. + +Both investigation runs used the same diagnostic binary, built before that +marker guard was corrected. Capture-free summaries were recomputed from all +raw frames and saved separately as `capture-free-pacing.json`; no stall was +filtered away and no rerun was needed for that reporting correction. + +The final combined review covered diagnostic ownership, clock boundaries, +cache traversal, source restoration and capture-free reporting. All five +reporter tests passed; the final Windows diagnostic build and restored normal +Windows build succeeded. Production source hashes matched their manifests, +`source/` and `port/` were unchanged, and the normal binary contains no stall +fixture. These Windows diagnostic tools are not compiled into Android/web +or shipped in normal builds. No fresh non-Windows, AMD hardware, CE/MCC +transition or network run is claimed; unchanged implementation evidence from +the preceding fix report remains applicable. Host policy, off defaults and +AMD/NVIDIA and Xbox/CE/MCC paths remain unchanged. + +Evidence is in `build/lighting-performance/stall-investigation-120-1` and +`stall-investigation-120-0`, with `build/lighting-stall-summary.json`, build/test +logs and the cleanup report. All owned game processes exited. The runners +removed staged maps/caches and per-run binaries; final cleanup removed another +21,072,779 bytes of diagnostic executable/configuration and fixture object. +All 74 archived save files (41,978,888 bytes uncompressed) passed SHA-256 +verification. About 10.4 MiB of evidence remains in 32 files. Original maps, +saves, toolchains and the normal Windows build were preserved. diff --git a/docs/dynamic_lighting_tracing.md b/docs/dynamic_lighting_tracing.md new file mode 100644 index 0000000000..57c649e342 --- /dev/null +++ b/docs/dynamic_lighting_tracing.md @@ -0,0 +1,253 @@ +# Collision tracing and memory follow-up + +This follows the [occlusion/GPU optimisation pass](dynamic_lighting_optimisation.md). +The later [damage and shader-cache follow-up](damage_and_shader_cache_fixes.md) +records fixes for the crash and shader duplication identified here. Results +below describe the earlier implementation and remain historical evidence. +The assignment preserves current lighting quality, host policy, stock behaviour +when disabled, and off defaults. CStencil and Modern remain outside scope. + +## Design and review + +The feature's 1536 rays per refresh previously used the complete general +`collision_test_vector` service. A diagnostic build timed the existing collision +categories only while lighting was tracing, and counted retained shader programs, +fragment shaders, render targets and texture-cache entries once per second. +Inclusive collision categories overlap and must not be added together. These +diagnostic runs are separate from FPS acceptance. + +[plasma_collision.c](../port/linux/game/plasma_collision.c) now owns a synchronous, +depth-only batch. It uses the same structure BSP and model intersection routines, +ray vectors, front/back surface flags, breakable-surface state and nearest-hit +comparison. Cluster membership, object eligibility/bounds and model instances +are reused within one batch. Parent eligibility and sphere tests still gate +children; sibling traversal remains independent. Unused material, plane and +location results are not constructed. The shared collision implementation, +simulation, settings, host-policy and map-loading code are unchanged. + +Storage is fixed: 512 object records and 4096 cluster references. Overflow, +unsupported flags and malformed leaves fall back to the general query. Model +instances borrow tag/matrix pointers only during the batch; `end` clears them. +No state is reused across rendered poses, ticks or maps. The integration is a +small call-site change inside the existing feature-owned occlusion module. +No new shared-engine hook or network-version change is required. + +Self-review covered eligibility, ignored owners, vehicles, parent/child/sibling +ordering, duplicate roots, cache ownership, fallback and diagnostic restoration. +The existing field resolution, ray count, trace-refresh policy, temporal fades, +light colours/radii, attenuation and shader equations are unchanged. + +## Collision evidence + +The user later identified DaVinci Resolve running in the background and closed +it. Earlier timings and endurance measurements below are diagnostic history, +not the final clean acceptance evidence. The paired CPU benchmark, ten-minute +memory controls and six sustained FPS cases use fresh +processes after that change. Earlier exact ray comparisons remain correctness +evidence; background contention does not turn a depth mismatch into a match. + +A first interleaved comparison checked at least 55,261,436 rays in combat with +zero depth mismatches. Six focused 60 FPS comparison cases passed their runtime +checks: moving door, Warthog, shorter Grunt, disabled Needler, vertex-lit Needler +and CE Death Island. All five enabled cases recorded zero mismatches; the +disabled case correctly started no lighting batches. + +The subsequent paired-batch fixture executes both paths against exactly the +same rendered pose, with identical ray construction and ordering. Clocks wrap +complete batches; comparison and logging occur outside the timed sections. +The 120-second measured combat run, including warm-up and shutdown margins in +its cumulative checker, recorded at least 79,655,424 rays across 51,859 batches +with zero mismatches. Cumulative CPU time was 23,176.870 ms for the new path and +37,205.498 ms for the original: about 38% less tracing time, or 0.447 versus +0.717 ms per batch. The accelerated path executes first, so the reference may +benefit from warmed caches. This is a paired CPU measurement, not an FPS gain +claim or proof of equivalence for every map. + +The completed clean paired repeat recorded 77,265,408 rays across 50,303 batches, +again with zero mismatches. Cumulative CPU times were 23,347.742 ms accelerated +and 37,794.423 ms original: **38.2% less tracing CPU time**, or about 0.464 versus +0.751 ms per batch. These totals include warm-up/shutdown margins around the +120-second measured combat interval. The doubled-work comparison is separate +from timing-only FPS acceptance and retains the same cache-order limitation. + +All 61 final focused harness/reporter tests passed, including traversal, cache reset, +missing models, ignored owners, vehicle flags, malformed leaves, overflow and +negative controls. Normal Windows and diagnostic/capture builds succeeded. +Local Ninja has no Android/web targets; their required validation uses CI. +The [four-platform build](https://github.com/chestahh/GulchCE/actions/runs/40246436679) +and [MCC validation](https://github.com/chestahh/GulchCE/actions/runs/40246436634) +both passed for production commit `feb5bc04`. +The subsequent [benchmark-tooling build](https://github.com/chestahh/GulchCE/actions/runs/40247660080) +also passed; it changes no production game source. +The broader local Windows harness run had 1,010 passes and 67 failures in +unrelated test facilities: POSIX APIs/headers, compiler-wrapper macro and +deprecation conflicts, CRLF output expectations, and linking Unix `libm`. +The successful Linux CI test step includes the full harness and touch-menu +tests. These local failures are recorded rather than counted as passes. + +The test builder now refreshes the timing fixture's timestamp. Preserving the +source timestamp could otherwise reuse an object from a different diagnostic +variant. Its normal-build restoration remains in `finally`. Manifests record +the production and selected diagnostic sources. Builders' `--verify-traces` +option intentionally doubles collision work and must not be used for FPS +acceptance. `--resources` counts retained entries without per-ray clocks. + +## Memory investigation + +The initial three-minute diagnostic showed shader cache growth during warm-up +(469 linked programs around 30 seconds, 611 near the end). Volume-cache entries +rose from 29 to 31, with guest payload about 1.6 MB, while render targets stayed +at six. This identifies retained warm-up resources, not complete driver memory +accounting or a proof of no leak. + +An attempted concurrent memory pair discovered the other local session and is +excluded. The remaining process was stopped and both runs' diagnostics retained. +The runner now assigns explicit separate loopback addresses. The corrected +memory runs are sequential, ten minutes each, with lighting disabled/enabled. +Clipboard joining is disabled and reports reject unexpected extra players. + +A subsequent disabled control crashed around 218 seconds of gameplay. Its +symbolized stack runs through `projectile_collision`, `object_cause_damage` +and `object_get_and_verify_type`; the latter accessed address `0x8` while +resolving an object. No lighting batches ran in this disabled control. This +locates the failure in projectile damage, but does not establish its original +cause. The partial run is excluded from acceptance, its stack/logs retained, +and no unrelated damage or networking code was changed. The reporter now +retains early-exit reports, includes crash exceptions, and represents missing +memory windows as null rather than throwing a statistics error. + +Allocation review found fixed, reused feature storage: eight visibility +fields with up to three volume textures each, eight fallback emitter slots +with up to three textures each, and one shared radial falloff texture. +`plasma_occlusion_reset` and `ammo_counter_falloff_dispose` release their +textures; `plasma_falloff_dispose` releases the radial texture. Backend texture +cache entries age out through `xgpu_texture_cache_begin_frame`. The new +collision batch uses static storage and has no heap allocation. These are +code findings, not a measurement of all graphics-driver allocations. + +The existing backend's `fragment_shader_get` and `program_get` retain compiled +shader/program combinations for reuse. Its resource counters therefore help +identify cache warm-up, but do not prove that every byte of process growth +belongs to shaders. No shared renderer cache policy was changed in this pass. + +The clean disabled diagnostic uses `--dump-shaders`: generated GLSL is retained +instead of periodic screenshots, avoiding their readback and large image +allocations. The enabled resource run retains its usual screenshots, so these +two diagnostic runs must not be treated as a matched on/off memory-cost delta. +Both are separate from the timing-only acceptance cases. Exact SHA-256 grouping +of captured fragment sources already demonstrates duplicate compilation under +different cache keys with lighting disabled. This is evidence of redundant +retained shader objects, not a measurement of their complete driver footprint. +Both clean resource runs completed approximately 600 measured seconds after +30 seconds of warm-up, with continued 15-bot combat and normal exits. The +disabled run selected no feature lights and performed no occlusion updates; +the enabled run reached 28 selected lights and the unchanged eight-field bound. + +| Clean resource diagnostic | First memory window (MiB) | Last memory window (MiB) | Peak private (MiB) | Final programs / fragments | Maximum volume guest payload | +| --- | ---: | ---: | ---: | ---: | ---: | +| Enabled, periodic screenshots | 689.2 | 752.5 | 753.6 | 887 / 851 | 1,636,059 bytes (32 cached volumes) | +| Disabled, GLSL capture, no screenshots | 693.7 | 727.1 | 728.6 | 683 / 606 | 112,347 bytes (2 cached volumes) | + +The memory windows use process elapsed time: 45-105 seconds and 585 seconds +through the last sample, including shutdown margin. Resource counters use +gameplay elapsed time. Render targets ended at seven enabled and six disabled; +immediate-vertex capacity stayed at 512. The enabled volume cache ended with +29 entries / 1,586,907 guest bytes, demonstrating reuse/eviction rather than +one new visibility volume retained per update. Counts include stock textures; +guest payload is not GPU allocation size. Private memory continued to fluctuate +and grow late in both runs, so these samples do not establish a steady state. + +The disabled diagnostic's 606 fragment files exactly match its final cached +fragment count. SHA-256 grouping found **78 byte-distinct sources and 528 +redundant source copies** across 41 duplicate groups; the largest group contained +116 entries. The code compiles a new GL shader for each distinct full state key, +even when generated source is identical. `program_get` then keys links by shader +object IDs, so different fragment IDs also prevent link reuse when the vertex +shader is the same. This is a confirmed shared-cache inefficiency with the +feature disabled. It is not evidence that 87% of process memory is recoverable. + +A focused general-renderer follow-up should reuse byte-identical generated +shader sources, retaining full state-key lookup and exact source comparison +after hashing. That needs its own shader/program ownership and lifecycle review, +plus Xbox/CE/MCC and platform regressions; no shared cache implementation was +changed under this feature-owned collision optimisation. Remaining process +growth still needs allocation attribution beyond these resource counters. + +The initial disabled damage crash did not recur in either clean ten-minute +resource run, but recurred in the clean 30 FPS enabled timing run below. +Failed/interrupted controls and pre-Resolve timings are retained and excluded +from successful acceptance. + +## Final clean performance results + +These sequential runs followed closure of DaVinci Resolve. Each requested +300 measured seconds after 30 seconds of warm-up, with 15 Heroic bots and a +scripted player on Carousel at 2560x1440, 8x MSAA, 16x anisotropic filtering, +1024-pixel shadows and per-pixel lighting, on an i7-14700K / RTX 5070 Ti. +No other test game, build or harness ran concurrently. Timing manifests have +all per-ray, resource and trace-comparison diagnostics disabled. Screenshot +frames are excluded from pacing statistics and retained in raw evidence. +Combat is not a deterministic replay, so differences are not a pure measure +of feature cost. + +| Cap | Lighting | Measured seconds | Average FPS | 99th-percentile frame (ms) | Result | +| ---: | --- | ---: | ---: | ---: | --- | +| 120 | Off | 300 | 119.47 | 10.427 | Completed | +| 120 | On | 300 | 115.42 | 12.934 | Completed, below target | +| 60 | Off | 300 | 60.00 | 16.811 | Completed | +| 60 | On | 300 | 59.97 | 17.225 | Completed | +| 30 | Off | 300 | 29.96 | 33.385 | Completed | +| 30 | On | 240.6 | 30.00 (partial) | 33.387 (partial) | Failed: access violation | + +The failed run reached approximately 270.6 seconds of gameplay before the +same `object_get_and_verify_type` instruction accessed address `0x8`, through +`object_cause_damage` and `projectile_collision`. This reproduces the stack +observed with feature lighting disabled; it does not establish the exact +cause or prove that every possible lighting interaction is excluded. Its +partial 30 FPS average is not a completed acceptance result. Both symbolized +stacks and failed reports are retained. A queued repeat was cancelled before +launch; further endurance reruns cannot substitute for investigating this crash. + +## Final regression review and remaining work + +All 21 short visual cases passed their runtime checks. Contact sheets were +inspected for crouched Needler holders, shorter Grunts, first-person AR, +Warthog turret, moving door and shield charge/depletion at 30, 60 and 120 FPS, +plus disabled, vertex-lit and CE controls at 60 FPS. The sampled images showed +consistent weapon spill, chassis/door blocking and shield colour transitions +without an obvious new visual regression. These are sampled stills, not a +continuous animation inspection or exhaustive visual acceptance. + +A short two-player loopback session with feature lighting enabled on the host +and disabled on the client exited normally. Both logged two-player gameplay +and shooting with no detected runtime errors. Host shield policy was configured +to `glow_overshield` while the client's local policy was `stock`; this is a +policy integration smoke check, not a comprehensive network synchronisation +or internet/co-op test. No network format or host-policy implementation changed. + +The Xbox c40 -> MCC Mercury Falling -> CE Death Island -> Xbox Blood Gulch +transition sequence completed with lighting off at 30 FPS and on at 120 FPS. +Both exited normally without logged exceptions; the enabled comparison recorded +11,750,401 rays with zero mismatches. This checks these specific loading and +cleanup paths, not full map-family compatibility. The final focused regression +rerun passed all 61 tests in 14.83 seconds. + +The final review found no further justified production changes: batch ownership, +bounds/fallbacks and disabled behavior remain isolated to the feature module; +lighting equations and defaults are unchanged. The subsequent +[diagnostic-tool build](https://github.com/chestahh/GulchCE/actions/runs/40249519986) +passed on all four platforms. Remaining acceptance blockers are the intermittent +projectile-damage crash, unresolved process memory growth and performance below +the 120 FPS target in busy combat. The collision optimisation is complete; +Milestone 3 and the dynamic-lighting 1.0 baseline are not yet accepted. + +All owned game processes exited. Temporary map copies/caches and run binaries +were removed, and 932 test-save files (about 1.05 GB uncompressed) were preserved +in lossless archives whose SHA-256 manifests were verified. Final cleanup +removed another 128,492,247 bytes of diagnostic binaries and intermediate +captures. About 492 MB of logs, captures, shader sources, reports and archived +test saves remain as useful evidence under `build/`; the normal Windows build +and installed toolchains remain available. Original game assets and saves were +not changed. The compact combined results are in +`build/lighting-tracing-clean-sustained.json`, with final visual, network, +transition and cleanup reports alongside their respective test outputs. diff --git a/docs/geometry_flicker_83.md b/docs/geometry_flicker_83.md new file mode 100644 index 0000000000..f604bfacef --- /dev/null +++ b/docs/geometry_flicker_83.md @@ -0,0 +1,97 @@ +# Geometry flicker: issue 83 + +[Issue 83](https://github.com/chestahh/GulchCE/issues/83) reports disappearing +geometry on Windows and Linux with AMD, NVIDIA and Intel GPUs. Its attached +Blood Gulch clip shows sections of distant terrain appearing and disappearing +as the view turns. The report also names 343 Guilty Spark (`c10`). + +## Fix already in the requested base + +The investigation started from `origin/testing` at +`fc9c57cf3467502dc159a41ee7f54d6b01499945`. That revision already includes +OpenCE commit `521c8c8d5ab65094a31f960ff15c1191f64ef005`, "Stop the level +flashing: a portal corner on a clip line makes no NaN corner." + +The corrected visibility path is: + +1. `structure_visibility_traverse_cluster` in + [structure_visibility.c](../source/structures/structure_visibility.c) + intersects the visible screen region with a portal's outline. +2. `convex_hull2d_intersect` in [geometry.c](../source/math/geometry.c) + repeatedly calls `convex_polygon2d_clip_to_plane`. +3. A corner on the clipping line and a preceding corner just behind it can + produce a `0/0` intersection scale through floating-point rounding. + Clamping does not remove a NaN (a nonnumeric floating-point result). +4. Invalid corners contaminate subsequent intersections. An empty result + prevents traversal into the next cluster, so its surfaces are not drawn. + +The upstream correction selects the current corner when that scale is NaN. +It retains normal clipping and does not disable visibility rejection. This +CPU visibility defect explains why a GPU-independent failure can look like +a graphics-driver problem. The report's appearance is consistent with this +defect; the clip alone does not prove that every reported occurrence has the +same cause. + +This assignment preserves that implementation and its `port:` explanation. +It adds regression coverage and evidence rather than another renderer +workaround. No map loader, MCC adapter, shader, setting, network message or +simulation state changes. A network-version increment is not needed. + +## Regression coverage + +[test_polygon_clip.py](../tools/harness/tests/test_polygon_clip.py) compiles +the actual geometry functions and math helpers, without retail assets. Its +two upstream fixtures are portal outlines dumped from Sali Creek, not data +captured from the issue's video. + +The additional cases check that: + +- A valid intersection remains finite and nonempty when passed through + successive portal intersections. +- Fully visible polygons and their clipping flags remain unchanged. +- Fully hidden and edge-only intersections remain rejected. +- An in-place clip preserves the correct half of the polygon and updates + clipping flags correctly. + +Negative controls remove the NaN guard only in generated temporary test +copies. Both original fixtures and the successive-portal case then fail. +The existing independent control also detects suppressed intersection output. + +## Validation and limits + +The nine polygon-clipping tests pass on Windows with a 32-bit clang harness. +This includes the negative controls; their expected failures establish that +the tests detect the original defect. The Windows release build uses +`--pgo=off --lto=off` and succeeds with existing Expat import/link warnings. +After final review, all 31 focused tests pass: polygon clipping, GPU +visibility readback, Custom Edition geometry bounds, and shadow setup. + +Hidden-window runtime checks use Windows, an NVIDIA GeForce RTX 5070 Ti, +OpenGL 4.5 (driver 617.42), 1280x720, a 30 FPS cap, reversed depth enabled, +default optional graphics features, and scripted `look:1` camera input. +The first run enters local Blood Gulch gameplay. Its map-name console commands +do not leave the network session, so it supplies no map-transition evidence. +A separate solo run loads `c10`, then Custom Edition `deathisland`, MCC +`DigsiteMP/1`, and Xbox `bloodgulch` in the same process. Logs establish the +family transitions. MCC reports its existing rejection of the map's +`host_spawn` script at unsupported `debug_camera_load`; that limitation is +not changed here. + +Both processes exit normally. The runs retain 27 and 21 periodic captures, +respectively; sampled captures show rendered scenes in all three map families. +The `c10` observation covers the opening cinematic, not later campaign play. +Periodic stills do not establish the absence of a single-frame disappearance. + +These are short rendering checks, not campaign completion or a replay of +the original camera path. The map files and saves are isolated copies. +Disposable map copies and generated map caches are removed; test saves are +preserved in verified ZIP archives beside the logs and captures under the +worktree's `build/issue83/` directory. No retail assets are committed. + +The final review covers the unchanged clipping fix and its visibility caller, +the added tests, and this explanation. No additional production refactoring +is justified. Tests and documentation do not modify Android or web runtime +code; full Android/web and Linux builds are not part of this validation. +The original reporters' exact camera path and their AMD/Intel/Linux systems +remain unverified. Passing the synthetic tests is not proof of flicker-free +rendering on every map or GPU. diff --git a/docs/lightning_tick_shape_validation.md b/docs/lightning_tick_shape_validation.md new file mode 100644 index 0000000000..7ee10be86d --- /dev/null +++ b/docs/lightning_tick_shape_validation.md @@ -0,0 +1,101 @@ +# Lightning tick-shape integration + +This change incorporates [OpenCE PR 552](https://github.com/OpenCommunityEdition/OpenCE/pull/552), +commit `688eeb8a0a54da06103f0919bfdf7be0c16d952f`, with `git cherry-pick -x` +onto GulchCE `d0b597a59157d8ae4ca269df2aaad8f26b1d78e2`. The dedicated branch +is `fix-lightning-tick-shape`. The original author and commit provenance are +preserved. Validation below was performed on 5 November 2026. + +## Scope and lifecycle correction + +The inherited renderer consumes new local random numbers on every submission +of a lightning widget. That ties its flicker to rendering frequency, although +the game simulation advances at 30 ticks per second. The PR caches the seed +per lightning slot and split-screen window for a tick, retaining fresh marker +positions and camera-facing geometry each frame. + +The follow-up clears that render-only cache on unload and after saved-state +restoration. A new regression test failed against the imported PR: the real +post-load callback list left the old seed usable when the restored tick and +slot matched. The fix uses a reset owned by `lightning.c` and one entry in the +existing post-load callback list. Map initialization and slot reuse retain +their resets. No persistent object layout, save format or map adapter changes. + +This is an existing shared-renderer behavior fix, not an MCC conversion rule. +Xbox, Custom Edition and MCC keep their existing loading paths. No wire data, +simulation random seed or synchronized gameplay contract changes, so the +network version is unchanged. The additional reset cannot be handled solely +inside submission: restoring game state does not call `lightning_new`, and +tick and datum values alone cannot identify that restoration. + +## Automated checks + +- Windows x86 release built with LLVM clang 23.1.4 and + `--portable --release --pgo=off --lto=off`. The build has existing Expat + `LNK4217` import warnings; it is not a warning-free build. +- `python -m pytest -q tools/harness/tests/test_lightning_tick_shape.py + tools/harness/tests/test_coop_vehicles.py tools/test_mcc_checkpoint.py + tools/test_web_build.py`: 76 passed, 1 skipped. The skipped native socket + harness needs POSIX pthreads and is explicitly skipped on Windows. +- The lightning portion has 17 checks, including six deliberate-fault + controls. It covers tick zero, marker movement, all four views, simultaneous + bolts and the last pool slot, allocation refusal, slot reuse, map reset, + the actual post-load callback list, and missing-marker, texture and vertex + allocation failures. The checkpoint test failed before the reset was added. +- `python tools/test_checkpoint_timing.py`: passed at its 30, 60, 120 and + 990 FPS schedules, including pause and time rewind. +- Tests used the installed local pytest dependencies and Windows x86 runtime + libraries. The existing harness's Unix `-lm` argument was satisfied by the + pre-existing empty compatibility `m.lib` in the local test toolchain; math + implementations came from the Windows C runtime for these fake-world tests. + +## Native rendering and transitions + +Hidden 960x720 windows used OpenGL 4.5 on an NVIDIA RTX 5070 Ti, driver 617.42, +with V-sync off and isolated data/save folders. Original maps and saves were +not modified; no more than two game instances ran concurrently. + +A production executable completed b40 (Xbox) -> deathisland (Custom Edition) +-> mercury_falling (MCC package) -> c10 (Xbox), accepted save/revert commands +on b40 and Mercury, and exited normally. Captures were inspected for CE, +MCC after revert, and the return to Xbox. This establishes bounded rendering +and transition checks, not complete campaign compatibility. + +A temporary diagnostic build instantiated b40's authored bridge-lightning +object near the camera, selected its marker-based view and logged seeds and +submitted vertex hashes. It bypassed camera interpolation only for this +diagnostic view; production sources were restored after building the probe. +The scene is staged, not a traversal to the campaign's original bridge. + +| FPS cap | Draws after initial camera setup | Repeated tick/slot/view groups | Seed or geometry changes within those groups | +| --- | ---: | ---: | ---: | +| 30 | 1516 | 0 | 0 | +| 60 | 2956 | 1450 | 0 | +| 144 | 7216 | 1504 | 0 | + +Bridge captures were inspected at 30 and 144 FPS. A further 144 FPS run moved +the diagnostic camera, held game speed at zero for three seconds, resumed, +and reverted a checkpoint. It exited normally; across 1322 repeated groups, +seeds stayed stable within each restored-state epoch while geometry changed +with the moving camera. Up to 449 draws reused one tick's seed during the +time hold. The reset hook ran again after revert. Tick numbers were grouped +separately across resets because a revert legitimately revisits earlier ticks. + +## Remaining limits and retained evidence + +`ninja android` and `ninja web` were attempted but reported unknown targets: +configure found neither an Android NDK nor Emscripten. WSL is not installed. +Full Android/web builds and Linux execution remain unverified. The web graph +tests above do not substitute for a wasm link or browser gameplay. + +c10 loaded and rendered, but the staged monitor probe produced no lightning +draws at 30, 60 or 144 FPS. Guilty Spark's tendril appearance therefore remains +unverified. Real split-screen gameplay, device/browser rendering, and network +sessions were not exercised. Four-view seed isolation is harness coverage. + +Local `build/validation` holds build/test logs, runtime transcripts, probe +scripts and manifests, and `capture-results.json`. Captures and inactive test +saves are losslessly archived in `captures-and-saves.zip`; its manifest records +original paths, sizes and SHA-256 hashes, verified against every ZIP member. +Temporary map copies/links, game caches and duplicate executables were removed. +The production Windows build remains available. No retail assets are committed. diff --git a/docs/mcc_refactor_validation.md b/docs/mcc_refactor_validation.md new file mode 100644 index 0000000000..b9a685301a --- /dev/null +++ b/docs/mcc_refactor_validation.md @@ -0,0 +1,5160 @@ +# MCC refactor milestones and validation + +## Milestones and current position + +Updated 8 November 2026. Milestones retain the existing stage numbers, so +"Stage 6" and "Milestone 6" refer to the same work. Stages 1–8 are complete; +Stage 9's combined review, testing and cleanup are complete. Ruby co-op +recovery failed on both original main and the Stage 9 candidate; those failures +remain recorded. Milestone 10 fixes the demonstrated shared replica-lifetime +defect under a separated network agreement. Its final Ruby, Mercury and Xbox +checkpoint checks, rejoin and native/browser transport controls pass within +the limits below. Milestone 10's implementation, validation, combined review +and verified cleanup are complete. This qualifies the demonstrated recovery +repair without asserting full campaign or every-map compatibility. +The shared boat correction, Mercury's shared clock-recovery correction and +separately authorized console-syntax correction are implemented under +Milestone 11. Its combined review, final native/Internet checks, both CI +revisions, verified cleanup and archived-evidence replay are complete. On +7 November the user explicitly removed the old-client crossplay constraint +for both milestones; the 8 November request also supersedes the console deferral. +The stage evidence below records the changes, actual validation and limits. +The subsequent delivery plan adds Milestone 13 for host sharing, Milestone 14 +for Custom Edition and MCC browser playability, Milestone 15 for general MCC +HUD corrections and shared cinematic aim, and Milestone 16 for the upstream +contribution. Milestone 13 is complete within the validation limits +recorded below. CI through `a972f450a`, +native downloads, metadata-mismatch preservation, managed removal and Mercury +follow-on gameplay have passed within the recorded limits. The dedicated +map-only admission correction passes its native rerun at `f8432e2a3`. +Further initial-download and on-demand transition runs exposed host loading +that starved pending clients. The general MCC loading barrier at `a972f450a` +passes both native reruns within the recorded limits, and that commit's CI +passes. Final Xbox/CE native controls, all three native/browser networking +controls, combined implementation review and verified cleanup are complete. +Milestone 14's browser implementation and Stock-menu acceptance checks are +complete within the recorded limits below. The separate shared cinematic-state +finding is corrected under Milestone 15, alongside the three reported HUD +issues. Implementation, combined review, final validation and verified evidence +cleanup are complete within the limits below. Milestone 16 has not started. + +| Milestone | Scope and outcome | Status | +| --- | --- | --- | +| 1 | Establish executable regression coverage, CI and Workshop runtime baselines. | Complete | +| 2 | Reproduce the shared boat defect and establish the crossplay constraint. | Investigation complete; corrected in Milestone 11 | +| 3 | Remove redundant MCC resource ordering and bitmap ownership lookup work. | Complete | +| 4 | Replace repeated per-texture stream scans with a local per-tag cursor. | Complete | +| 5 | Correct HUD ownership, remove bitmap-name dependence and trim duplicate normalization. | Complete | +| 6 | Consolidate duplicate checksum work with exact compatibility and linkage proved. | Complete | +| 7 | Consolidate script resolution, reject unused checkpoint object handles before restoration, and audit state ownership. | Complete; console defect corrected alongside Milestone 11 | +| 8 | Retain justified HUD exceptions and support MCC-wide AI deselection through its real native service. | Complete | +| 9 | Review the combined branch and extend runtime, lifecycle and performance validation. | Review/testing/cleanup complete; recovery failure addressed in Milestone 10 | +| 10 | Correct shared co-op checkpoint recovery with explicit lifetime and network agreement separation. | Complete; bounded recovery checks pass | +| 11 | Correct shared boat controls, small client clock delays exposed by Mercury, and the separately authorized console lifetime defect. | Complete; bounded runtime, platform and network checks pass | +| 13 | Review PR #95, complete host-only MCC package sharing, campaign progression and host opt-in menus. | Complete; final review, native/transport controls, CI and cleanup pass within recorded limits | +| 14 | Make Custom Edition and MCC maps playable in browsers, including import/download, persistence and native/browser multiplayer. | Complete within recorded limits; Stock browser target validated | +| 15 | Correct MCC HUD text placement, ballistic counters and scope-mask scaling, plus shared cinematic aim synchronization. | Complete within recorded runtime/platform limits; final review, CI and cleanup verified | +| 16 | Establish Xbox a10 assertion provenance, fix any defect introduced by our work, then prepare the MCC-only upstream contribution and unified OpenCE agreement. | Planned after Milestone 15; validation gate added; previously numbered 15, originally 14 | + +The completed Milestone 10 gameplay implementation is `67968518222f3ee59361670323cfcd48486fa97e`, +with passing MCC and four-platform debug workflows and 87 focused local passes. +The comment-only follow-up `7ed70168a` also passes both workflows. +Its [validation record](#stage-10-shared-checkpoint-recovery-fix) distinguishes +the authenticated local native build from the exact-revision CI Web build, +pre-final checks from final checks, and passing transport from unmeasured +cross-log state equivalence. Its then-current agreements were base 32714, MCC 66 and +camera 32716/32717; historical verification used OpenCE 41/MCC 65. +All 21 structural HUD profiles remain with measured evidence and removal +conditions. On 8 November the user explicitly authorized the shared console +syntax correction alongside Milestone 11, superseding its earlier deferral. +Milestone counts are not an estimate of percentage effort remaining +and do not establish equal audit depth for every MCC module. + +All future changes remain evidence-backed, with general engine defects fixed +in the responsible implementation and MCC format defects fixed systemically +inside MCC-owned modules. Preserve Xbox/CE behavior, map-family ownership and +unrelated functionality. Milestones 10 and 11 may separate incompatible +network versions; the earlier crossplay-dependent deferrals below are historical +evidence. Each milestone includes design review, meaningful regression +coverage, the applicable platform/network checks, final review and cleanup. +Later integration checks supplement these checks; they do not postpone them. + +### Milestone 13: host sharing and campaign delivery + +Analyze the actual changes and discussion in +[PR #95](https://github.com/chestahh/GulchCE/pull/95), provide evidence-backed +recommendations and draft answers to the contributor's questions before +implementation. A draft response is not authorization to post it. Adapt the +reviewed contribution to this refactored branch, preserving contributor +attribution, rather than treating its older `testing` base or protocol numbers +as current. Complete the campaign manifests, follow-on missions and host menu +entry that the PR explicitly leaves out of scope. + +MCC transfers have one source: the host. Host sharing is opt-in and off by +default; honor the joiner's download preference. The user has explicitly +approved extending the PR to eligible Workshop packages as well as hand-placed +packages. Use one transfer/validation implementation for both origins. Preserve +Workshop attribution and links, apply content eligibility and redistribution +restrictions, and retain subscription/manual installation as an alternative. +Workshop presence alone does not establish eligibility or validate received +bytes. Review the host-local classification list, manifest identity, staging, +installation and failure cleanup. Campaign delivery must declare and validate +mission dependencies and progression. The agreed policy is to obtain and verify +the campaign manifest upfront, then download and verify each mission and its +required resources before that mission starts. Reuse matching verified local +content rather than downloading it again. The planner now includes campaign/mission JSON upfront with only the current +mission binary. The Mercury integration runs below verify follow-on download, +admission and bounded gameplay progression; component parsing alone does not +establish them. + +Offline/rehost limit: managed mission snapshots remain individually playable; +they do not form a complete campaign by combining folders. The campaign +contract in [`mcc_manifest.h`](../port/linux/src/mcc_manifest.h) contains ordered +names/titles, not future mission gameplay digests. Locally generated receipts +record the received current files and provenance, but cannot establish which +other snapshot is the intended next-mission revision. Consequently +`mcc_maps_next_mission` retains its missing-within-package refusal. Matching +JSON, Workshop IDs or a unique leaf-name candidate are insufficient evidence +to relax it. Connected clients follow each exact host-advertised identity; +offline/rehosted progression needs the complete Workshop/manual package. +Automatically linking downloaded snapshots would require an additional +authoritative per-mission identity or recorded transition contract and is not +implemented by M13. + +Keep host-delivered content separate from Steam-managed and manually installed +packages. Identify the host's exact package/dependency snapshot by content +hashes, reuse a matching local copy, and never overwrite another installed +version to satisfy a join. Received content is a managed copy, not a Steam +subscription or a promise of automatic Workshop updates. Show attribution, +storage use and removal controls without treating saves as disposable data. + +The agreed join flow detects missing or differing +content before gameplay and offers a size-labelled host download, the Workshop +page when applicable, or cancellation. Host-download acceptance starts the +validated transfer and resumes joining only after successful installation and +identity checks. Use the existing `network.map_download` client permission and +Download Maps menu switch for MCC as well as CE. Preserve its existing default +(on) and CE behavior; update setting/menu help to explain MCC host-only downloads. +For MCC, this permission allows the offer; accepting the prompt starts the +package download. If either host sharing or client downloads is off, omit the +host-download option, explain the applicable setting and direct Workshop users +to the Workshop page. A matching local +copy needs no download prompt. Workshop/manual installation must be rechecked: +the current Workshop revision may still differ from the host's snapshot. On +web, opening a Workshop page does not install files into OPFS; manual content +must be imported through the browser's package importer. Keep this distinction +explicit in the design and tests. + +The user has confirmed the sharing-disabled case: when the host has MCC map +sharing off, a Workshop package mismatch offers only the Workshop page as a +content-acquisition action, plus cancellation/dismissal. Omit the host-download +option and explain that the host has disabled sharing. Do not label a differing +package as older or newer unless reliable version information establishes that +ordering. If no valid Workshop reference exists, explain that matching content +must be obtained manually rather than presenting a broken Workshop action. +These rules are agreed; final wording and layout remain implementation details. + +The user has approved sharing required JSON metadata and optional PNG previews +as part of Milestone 13. Allow only recognized package metadata, including +`ModInfo.json`, `CampaignInfo.json` and referenced mission/map metadata, plus +explicitly referenced supported PNG previews. Do not transfer arbitrary JSON, +images or other Workshop-folder contents. Apply the same host-only sharing +permission and validated staging/install flow to these files. +This explicitly includes version-mismatch downloads: accepting the host's +version transfers its required JSON metadata and eligible optional PNG previews +alongside the applicable maps/resources. Do not retain stale metadata or artwork +from the client's differing package. Keep these files tied to the same host +snapshot and preserve the agreed mission-by-mission campaign delivery policy. + +Local folders such as `mcc_maps//` use the same eligible-content, +host-only transfer and client-permission rules without requiring Steam or a +Workshop ID. Dedicated servers must be able to configure sharing and eligible +packages without menus, with actionable validation/refusal logs. Serve an +explicit package snapshot, not arbitrary folder contents; include supported +metadata and previews when present. Simple standalone map packages need not +invent campaign JSON or thumbnails; campaign progression requires valid campaign +metadata. Use content identity rather than folder names to match existing copies. +When downloads are unavailable, show a valid Workshop page if the local package +has a Workshop reference; otherwise explain which package/content is required +and that it must be obtained from the server operator and installed manually. +Do not invent Workshop links or automatically fetch arbitrary host-supplied URLs. +Retain the existing exclusions for loose root maps, stock content and `_shared` +resource directories as transfer packages; report required unavailable +dependencies instead of silently copying global resources. + +Validate received metadata fields and package-relative paths; prevent traversal, +symlink/junction escapes and overwrites of existing installations. Bound file +counts, individual and total byte sizes, parsing depth and decoded image memory. +Retain the supported PNG subset and validate actual content, not just filenames. +The existing readers provide a starting point: JSON is limited to 256 KiB per +file, and PNG previews to 8 MiB and 2048 by 2048 pixels. Review aggregate budgets +and enforce receiving-client checks before accepting network-delivered files. +Treat descriptions as plain text; never execute metadata or automatically fetch +its URLs. Content hashes establish agreement with the host's manifest, not +safety. Keep optional preview failure separate from required-content admission: +reject invalid artwork and use the existing placeholder; invalid required +campaign metadata blocks installation with an actionable explanation. + +Validation must include malformed JSON and PNG inputs, parser/decoder fuzzing, +path escapes, oversized and excessive files, truncated or hash-mismatched +transfers, optional-image fallback and required-metadata rejection. Verify the +resulting menus and campaign progression. Exercise all host-sharing/client-download +setting combinations, differing-version metadata/artwork, local-only dedicated +server packages, and packages with and without Workshop references. These are +agreed implementation and +validation requirements, not a completed security audit or test results. + +Validate real transfers and resulting gameplay, host/client authority, +disabled settings, content changes, interrupted transfers, destination +collisions, hostile input, resource ownership and follow-on missions. +Preserve existing Xbox and CE behavior. Browser completion is an explicit +Milestone 14 gate, not inferred from this PR's CI or native transfer tests. + +### PR #95 review and draft contributor response + +Review source: [PR #95](https://github.com/chestahh/GulchCE/pull/95), its current +body/questions and issue discussion, inspected 8 November 2026. The PR targets +`testing`, is still a draft, and reports six commits at +`98130b623cc252f99ad063abf59b15040e438c9f`. Its author explicitly requests real +two-PC testing; the reported green CI and synthetic tests do not establish +that result. The issue discussion adds no technical question beyond the three +in the body. No response has been posted and no PR description has been edited. + +Five contribution commits were cherry-picked with original attribution and +`-x` provenance into the dedicated refactor branch: + +| Source commit | Refactor-branch commit | Contribution | +| --- | --- | --- | +| `9e74e1fe6be1ff8ad32dae779e373921e25e5637` | `46cba2bba` | Staging, explicit host list and transfer session | +| `a1a5b12dd337ab939b62e9ebab70d1beb4c4fd8e` | `2d4defa7f` | MCC wire/game integration | +| `1a12588c54e52d3e9d19086e19d122351aef6120` | `f041f08b0` | Documentation and CI | +| `4585f73da25c7f208bf98475eed52ef78b344779` | `5fd155415` | Longer staging/data-root paths | +| `686ba07a7ba9ccdd00e1ada7397026a98c87bddb` | `153c607fc` | Original Linux-only game-harness negative controls | + +The sixth PR commit, `98130b623`, merges the older `testing` branch into the +contribution. It was not cherry-picked over the refactored baseline. The +adaptation is committed through `a972f450a`, including the later metadata, +managed-storage, identity, UI and loading-barrier corrections. The original +cherry-pick messages describe the contribution at import, not the resulting +M13 contract; later commits and the evidence below record its adaptation. + +Review recommendations and their rationale: + +- Preserve the contribution's MCC-owned policy, list, transport/session and + staging separation. Its small shared hooks are needed because lobby holds, + cache admission and dispatch belong to existing engine call sites; keep CE + and Xbox implementations and message families intact. +- Retain the explicit exact-content/maker list. A folder name, Workshop ID or + received manifest is not a custom-content classifier. List the gameplay + digest of each approved mission and its used resources; required JSON has + its own agreement digest. Do not imply that a hash grants rights or proves + arbitrary data safe. +- Replace the older wire assignments, not the branch's newer join/camera + envelopes. The integrated agreement is base 32726, MCC 69, camera + 32728/32729; MCC transfer messages are 103/104. The PR's proposed 65 and + 102/103 are historical and conflict with subsequent branch work. +- Add an explicit client waiting/acceptance state, bounded paged offers, + backpressure handling and upload accounting for manifests as well as chunks. + Reject hostile fields and messages from other peers; invalidate offers when + session identities or host preparation change. Component regressions and + selective fault controls exercise these guards. +- Replace destination-by-host-name and file-by-file publication with exclusive + staging and atomic no-replace publication of a separate managed snapshot. + Same-name existing packages remain usable. Stage tests cover pre-existing + stages, path collisions, partial-file ownership and native junction refusal. +- Select resources from the validated loader result rather than copying nearby + files. Actual resource-reader tests establish that self-contained maps ignore + unused invalid siblings, required overrides are authoritative, and root/shared + selection differs from package ownership. Transfer tests cover Workshop + fallback paths; shared stock dependencies refuse an incomplete offer. +- Treat `ModInfo.json` as parsed metadata, not credit text. Use a bounded schema + and reference allowlist for JSON/PNG; compare required-JSON identity, discard + unsupported optional previews, and retain the gameplay probe before install. + Workshop packages and local map-only folders share this implementation. + +The user explicitly brought the PR's campaign manifests/follow-on missions, +Workshop delivery and host menu switch into M13. Campaign metadata is planned +upfront; mission binaries/resources are obtained as needed. Managed snapshot +attribution, storage use and safe removal are also required. Fetching from +other players remains excluded. Browser import/download/persistence is M14; +the MCC-only upstream protocol merge is now Milestone 16. Neither is implicitly completed +by adapting this PR. Mac remains outside the requested platform scope. + +**Draft response, not posted:** + +> The host-local `mcc_share.txt` list is an appropriate explicit classification +> source for this work. Keep exact gameplay fingerprints and maker credit, +> refusing unknown content. Workshop origin alone will not qualify a package; +> eligible Workshop and manually installed packages will use the same checks. +> +> We should raise the agreement for the new wire contract now. On the refactored +> branch the current numbers are MCC 69, shared 32726 and camera 32728/32729, +> with transfer messages 103/104. Your proposed MCC 65 and 102/103 belong to the +> older base, so they cannot be copied directly into this branch. +> +> Include the host menu switch in Milestone 13. It stays off by default. Clients +> keep Download Maps and additionally accept a size-labelled offer before MCC +> file transfer. We are also handling the campaign/Workshop/metadata and managed +> snapshot work you left out of scope, while preserving your contribution's +> attribution and MCC-only boundaries. +> +> We have component evidence for consent, refusal, file integrity, cancellation, +> resource selection and preservation of existing packages. Native Ruby and +> Mercury download, admission and campaign follow-on checks now include real +> gameplay using two processes on one Windows PC. Those local loopback runs +> do not satisfy your two-physical-PC request. The final local native/browser +> networking controls and platform checks also pass, with their limits recorded. +> The adapted expectations differ in three places: +> a same-name different version installs separately; eligible listed Workshop +> packages can transfer; and disabled downloads offer manual/Workshop choices. +> The validation record identifies the tested revisions, map identities, +> settings, logs and remaining limits. Browser MCC playability is separate +> Milestone 14 work, not a result claimed by these Xbox transport controls. + +### Milestone 13 implementation evidence + +Status at this documentation pass: **complete within the recorded limits**. +The final gameplay implementation is `a972f450a1da46c2dcdc15b3c30accd473f86941`; +this closeout changes documentation only. CI through +`a972f450a` is green. Native Ruby download/late-join, metadata-mismatch +preservation, Mercury's download and follow-on gameplay, Xbox/CE controls and +managed snapshot confirmation/removal have passed within the limits below. +The later Mercury run includes the combined review's attribution/UI corrections. +The first dedicated map-only run fails admission after verified installation; +the completion-to-admission grace correction passes its native rerun at +`f8432e2a3`. Subsequent initial-download and on-demand transition runs expose +a separate host-loading timeout. The general MCC loading barrier at `a972f450a` +passes the initial-download and on-demand reruns recorded below. Final Xbox/CE +native controls, three native/browser Xbox networking cases and verified +cleanup also pass. Earlier stages' runtime passes do not validate the changed M13 +transfer/identity implementation. All native pairs here are two isolated +processes on the same Windows PC, not tests across two physical PCs. + +The current implementation includes host-only opt-ins, client consent and +manual/Workshop alternatives; paged bounded manifests; independent gameplay and +required-JSON digests; JSON/PNG reference validation; local map-only packages; +validated package-resource selection; and exclusive stage publication into a +separate `dl_` snapshot. The ownership record/removal API in +[`mcc_share_storage.h`](../port/linux/game/mcc_share_storage.h) is an integration +contract: listing/removing user-visible managed copies and preventing removal +of the active package are covered by native storage and menu fixtures. Native +managed removal and the corrected dynamic confirmation label are both observed +in the completed `ruby_storage_final` rerun below. +No network manifest may supply a local ownership receipt. + +Recorded component runs: + +The native Ruby download exposed a real allocator-boundary defect before +publication: the adapter used libc `calloc` with engine `debug_free`. The +symbolized crash reached `mcc_share_identity_check` through `client_check`; +the correction pairs engine `malloc`/`free` and explicitly zeros the entries. +The adapter fixture now distinguishes these allocators, and a before-fix +mutation reproduces the mismatch. Its 43 cases pass. This is an MCC adapter +fix, not a change to the shared allocator. The corrected Ruby download and +late-join rerun passed as recorded below. Native consent inspection also caught clipped text and an +incorrect lobby return; the existing MCC wrapping and engine go-back services +now handle the prompt, with observable restoration covered in the adapter. + +The later integrated component selection passed 248 cases with five explicit +platform/privilege skips; its one failure was sandbox denial of junction +creation. Rerunning the complete staging and storage suites with junction +creation available passed 70 cases with one unavailable file-symlink skip. +These are overlapping selections, not additional totals. The Windows release +executable builds and corrected-commit CI passes. The final platform/runtime +results for the later corrections are recorded below rather than inferred +from this earlier selection. + +| Evidence | Actual result and limit | +| --- | --- | +| `build/m13-stage-results.txt` | 22 Windows native staging tests passed, including an actual junction refusal, no-replace publication, pre-existing stage preservation, nested cleanup and malformed/colliding paths. This predates the new local receipt-companion integration. | +| `build/m13-game-results.txt` | 34 Windows game-adapter/planner cases and fault controls passed before the later resource-selection/revision changes. Real wire/session/stage code runs over synthetic files; engine/UI/identity and metadata parser are explicit stubs. | +| `build/m13-resource-results.txt` | 183 Windows tests passed across `test_mcc_share_game.py`, `test_mcc_resources.py`, `test_mcc_validation.py` and `test_mcc_precache.py`, including actual resource selection/cache invalidation and two planner fault controls. This run includes the four-argument installed-snapshot callback and host revision cancellation; it predates final storage/menu integration. | +| `build/m13-campaign-boundary-results.txt` | 69 Windows native catalog tests passed. Two new cases verify that identical campaign metadata and Workshop IDs do not splice separately downloaded mission folders, with either one or two candidates. The real catalog also retains individual mission selection and existing complete-package progression coverage; metadata decoding is stubbed. This establishes the offline catalog boundary, not receipt validation or online follow-on gameplay. | + +These runs are overlapping development snapshots, **not additive counts** or +proof that the later combined implementation passes. The resource suite checks +real bounded map/resource readers; the game fixture's metadata decoder/schema +stubs do not validate actual PNG/JSON parsing. Their independent production +helper suites and final combined runs must be recorded separately. Native +fixtures also do not establish Android-device behavior or browser filesystem +support. The current browser publication helper fails closed; M14 must supply +and verify browser import/download, persistence and playable native/browser +sessions for both CE and MCC. + +The resource planning correction retains successful validation's exact selected +paths and restamps map/package/root/shared candidates through +`mcc_validation_resources`. It introduces no new selection heuristics and no +Xbox/CE reader changes. Required global dependencies are deliberately refused +with an explicit host diagnostic instead of offering an incomplete package or +redistributing stock resources. The detailed reading route and input limits +are in [the sharing guide](reading/maps_and_resources.md#mcc-package-sharing-between-machines) +and [NETCODE.md](../port/linux/NETCODE.md#mcc-package-sharing). + +Only verified task-owned fixture directories were removed after these runs: +0.51 MB for the first staging run, 41.9 MB for the game harness, and 148.1 MB +for the resource run (decimal sizes, rounded). Paths were resolved inside the +worktree and checked for reparse points before cleanup. Small result logs are +retained. These figures cover those component runs only, not the entire M13 +workspace or any final cleanup claim. Originals, saves and other agents' output +were outside this cleanup. + +Native runtime and platform evidence recorded on 8 November 2026: + +- `build/m13-runtime/ruby_allocator_fixed/results.json` records two hidden + Windows instances, Ruby's Rebalanced Workshop item `2915693904`, mission + `a10`, co-op, host sharing/client downloads enabled and an initially missing + client package with Workshop discovery disabled. The executable SHA-256 was + `3491b03288c018e0487957c4213c6d00bee23d5ead6130dbe626629740ee3ff8`. + The client accepted the offer, installed the managed snapshot, then joined + the game in progress at tick 2768. Its final recorded state at tick 9398 + contained both living players. Both processes exited with code 0. This is + same-machine loopback admission and bounded gameplay evidence, not a complete + mission, campaign transition, two-physical-machine or internet gameplay test. + Logs also retain late pregame keep-alive/weapon-deletion diagnostics and a + lens-flare-capacity warning; an exit code alone does not resolve those. +- `ruby_allocator_fixed/installed-audit.json` under that runtime directory + records a read-only SHA-256 comparison against the original Workshop source. + All 15 transferred files match: one map, 12 JSON files (including all ten + mission records) and two PNGs. The other two files are locally generated + `download.receipt` and `workshop_id.txt`. The 17-file snapshot totals + 275,925,015 bytes and remains retained for rejoin/removal validation. Original + Workshop files and all saves were left untouched. The run itself removed + 12 generated map caches totaling 1,535,115,264 bytes, with no cleanup errors. +- `ruby_storage_ui/results.json` records the initial menu inspection using + that snapshot. The menu incorrectly disabled removal because the main menu + itself has a running game clock. `cdbe0460b` corrects the gate to permit the + menu scene while still refusing an active network session; the focused menu + suite passed 20 tests. The subsequent `ruby_storage_removed/results.json` + run uses an isolated copy of the 17-file snapshot. Frame 01440 shows the + confirmation question after the first activation; frame 01920 shows + "Downloaded snapshot removed" after the second. The managed folder is absent + and the process exited with code 0. The original retained Ruby snapshot + remains present. The confirmation question worked, but its button still + displayed "REMOVE SELECTED": that separate dynamic-label defect is addressed + in the later correction below. The initial failed inspection remains evidence. +- `ruby_storage_final/storage-audit.json` and its retained frames verify the + corrected confirmation label and removal on executable SHA-256 + `1b5ca52e683dcb6b544d21bde3da06cc1307fa247230cdb3f67467e3a3f7e3b9`. + Frame 01440 shows the snapshot still present after the first action and the + button correctly labelled "CONFIRM REMOVAL". Frame 02400 shows removal after + the second action, with no managed snapshots remaining and the removal + button hidden. The process exits with code 0 and all 17 original seed files + rehash unchanged. This is native menu confirmation/removal evidence, not + consent-overlay, campaign or active-session removal coverage. +- CI at `17ce5d6e8` passed Windows, Android and web debug builds, Android package + importer checks, web smoke/rooms in Chromium and Firefox, and MCC HUD render. + Native WebRTC passed clean delivery at 320/320 in both browsers; the 10% loss + exercises recorded 711/960 Chromium and 720/960 Firefox. Linux build tests + had 2677 passes/27 skips and one failure from invalid UTF-8 in NETCODE.md. + MCC Windows had 2019 passes/17 skips/eight missing-fixture-stub failures; + MCC Linux had 2083 passes/21 skips/ten failures: those eight, metadata case + ambiguity and an oversized pytest identifier. These were corrected before + `cdbe0460b`. The first run is not reported as a green matrix. See + `build/m13-platform-final/logs/ci-17ce5d6e8-summary.json`. +- Corrected `cdbe0460b3ece923e278ddeda7f3fcf8802f6141` passes + [Build run 42486938113](https://github.com/chestahh/GulchCE/actions/runs/42486938113) + and [MCC run 42486938110](https://github.com/chestahh/GulchCE/actions/runs/42486938110): + Windows, Linux, Android and web debug builds and all three MCC jobs succeed. + Linux's build selection reports 2,678 passed, 27 skipped and seven subtests; + its MCC selection reports 2,100 passed/21 skipped. Windows MCC reports + 2,034 passed/17 skipped. Separate Linux preview sanitizer checks pass 38 + cases, and metadata/storage sanitizer checks pass 87 with two skips. Native + WebRTC clean delivery is 320/320 with each browser; intentional ten-percent + loss returns 737/960 in Chromium and 700/960 in Firefox. These are overlapping + job selections and transport controls, not additive coverage or MCC browser + download/gameplay proof. The retained receipt is + `build/m13-platform-final/logs/ci-cdbe0460b-summary.json`. +- The Windows build at `cdbe0460b` has executable SHA-256 + `3ef3dca26cd370bf5a32e0c2910946de17cc3a7b1148815b17b2506441988a7b`, recorded + in `build/m13-platform-final/logs/native-cdbe0460b.json`. This is a different + binary from the Ruby run above; that older runtime result does not validate + the complete current commit. The native cases below use this `cdbe0460b` + binary; none is relabeled as execution of later corrections. +- `mercury_campaign/content-audit.json` and `results.json` record Workshop + item `3021510694`, `mercury_falling`, both opt-ins enabled and an initially + empty client. The first download installs at 13:56:07 UTC, resolves its + gameplay identity and enters co-op with both living players. The owner-verified + host console executes `(game_won)` after fresh paired gameplay. The next + offer is visually present by 13:56:44; an explicitly observed Return input + accepts it between the 13:57:40.010 prompt capture and first staged file + creation at 13:57:42.567. No exact wall-clock input event was recorded. + `mercury2` installs at 13:58:16 and resolves by SHA-256. Frame 47040 displays + its downloaded title and correct thumbnail in the lobby. + Each snapshot contains ten files including its local receipt. All 18 + receipted content files match their recorded hashes; the 16 transferred files + also match the original Workshop files, while both generated sidecars contain + the verified item ID/title. The client staging folder is empty at completion and both + processes exit with code 0. First-file creation to receipt takes 249.515 + seconds for the first snapshot and 33.492 seconds for the second. The shared + 686,853,355 resource bytes have identical hashes in both snapshots and the + original; second-resource writes finish in approximately 5.46 seconds. + This supports local reuse, without claiming a measured network-byte saving. + The second mission does **not** enter gameplay in this run: the host remains + in its native campaign lobby/UI pause after installation. Logs retain + fresh-profile/no-audio diagnostics, authored animation normalization, + pregame-state messages and a client disconnect when the host exits; they are + not zero-error logs. No sharing/identity failure, assertion or access violation + was found. The later fixed follow-on run below supplies separate gameplay + evidence; it does not change this earlier run's outcome. +- `ruby_version_mismatch/content-audit.json` verifies a metadata-only mismatch: + the client has identical map bytes in a separate manual package, with + deliberate whitespace appended only to `campaign/a10.json`. The host's + version downloads into `dl_dddb5100a348fef34f7b`; all 15 original transferred + files match their Workshop sources. The older manual folder remains intact, + including its intentional metadata difference. Client samples span ticks + 2563–4813, with 76 samples; both processes exit with code 0. This demonstrates + that gameplay identity alone cannot bypass required-JSON admission and that + the existing package is preserved. It is not a semantic campaign-order-change + or full-mission test. +- `legacy-control-audit.json` records Xbox Blood Gulch and Custom Edition + Death Island Slayer controls with both MCC sharing switches enabled. + Each peer records 39 state samples spanning ticks 30–1170, with no MCC + transfer and no fatal diagnostic matches. These are bounded legacy-path + controls, not full matches or independent state-divergence comparisons. +- `5682cbee3` passes + [Build run 42489773343](https://github.com/chestahh/GulchCE/actions/runs/42489773343) + and [MCC run 42489773377](https://github.com/chestahh/GulchCE/actions/runs/42489773377). + Both workflow conclusions were verified on GitHub. A detailed job-count + summary is not yet recorded; earlier revisions' counts are not reused. + This validates that committed candidate, not the later admission correction. +- `mercury_follow_on_fixed/gameplay-audit.json` records the completed + 180-second `5682cbee3` Windows pair, executable SHA-256 + `54b697b50a6e78a95d91dbf00ba9906c6eddf6432014fac93cd8e865464a8ca0`. + The client starts with both previously verified Mercury snapshots, so this + checks matching-copy admission and progression, not another fresh download. + Both peers load `mercury_falling` at 14:25:43 UTC. The host invokes + `(game_won)` after 300 fresh ticks; the only console intervention is this + deliberate completion. Both resolve `mercury2` by SHA-256 and load it at + 14:26:21 (client) / 14:26:22 (host), through the normal ready-lobby path. + Each peer records exactly one tick reset: Falling spans ticks 30–330, + then Mercury II spans ticks 30–3210. The second segment contains 107 samples, + with both players living naturally from tick 570 through 3210 in 89 samples + per peer. No cinematic skip or player-state injection is used. The short + first segment remains in its authored intro and is not a two-living-player + observation. Frame 14400 shows normal first-person gameplay and the other + player marker without the sharing overlay. Both processes exit with code 0; + all 20 retained snapshot files, including receipts, and ten distinct + original Workshop files retain their audited SHA-256 values. Staging is + empty. No sharing/identity failure, assertion or access violation was found; + existing profile/audio/Bink and pregame diagnostics remain. This establishes + bounded two-mission loading and second-mission co-op, not an independent + state-divergence comparison or complete campaign playthrough. +- `dedicated_map_only/gameplay-audit.json` records the separate 240-second + pair on that same executable: a `--server` host with no local player and + only `mcc_maps/local_ruby/a10.map`, with no JSON, PNG or Workshop sidecar. + The downloaded map is 275,753,385 bytes, SHA-256 + `71cf81a69ddda9f29b2128629b315a7a5d1aa49968db314817207da264e17c9b`, + matching the host and original Ruby Workshop file exactly. The client + installs only that map and a locally generated 393-byte receipt, with empty + Workshop attribution, into `dl_120b363a0811b190f08c`; staging is empty. + **Content verification passes, but admission/gameplay fails.** The machine + joined at 14:28:37 UTC. At installation completion, 14:31:02, the server + refuses it because no player can join; the client's identity match follows + at 14:31:03, after removal. There are no client simulation samples and the + server continues with zero players. The client exits with code 0; the host + exits with code 1 after the bounded runner kills it at its deadline, not + through normal shutdown. Source tracing identifies the completion race: + successful transfer completion clears the downloading exemption before + identity rebinding/player admission, exposing the original expired + 15-second playerless-machine deadline. A bounded MCC completion-to-admission + grace correction is tested in the following rerun. This failed run is + retained and is not reported as successful dedicated gameplay. +- `dedicated_map_only_fixed/gameplay-audit.json` verifies that correction at + `f8432e2a3528e10d2b1faaa4097d7ac89793128c`, executable SHA-256 + `ac97e6f640fc2b4f4b8c9e6bb2b6fae9bd74231b2ca4c3be2a5d7c727a852889`. + The same map-only fixture installs and resolves at 14:42:11 UTC, when the + server adds its player, 128 seconds after machine admission. Both peers + load by 14:42:37. The client records 81 monotonic samples at ticks 30–2430, + with its player living throughout; the dedicated host records one player + in its health log. The original, host and downloaded map hashes match the + previous audit. Only the map and 393-byte local receipt are installed, with + empty Workshop attribution and empty staging. Both processes exit with + code 0: after the client finishes, the runner sends the server its ordinary + stdin `quit`, and it stops at 14:44:01. Each process removes six generated + caches totaling 767,557,632 bytes without cleanup errors. This passes bounded + dedicated admission/gameplay, not a full mission or independent divergence + comparison; it does not erase the earlier failing evidence. +- `mercury_on_demand_final/gameplay-audit.json` records a **failed** follow-on + case on that `f8432e2a3` executable, with only the first Mercury snapshot + seeded. Both peers run Falling at ticks 30–330. After the host's deliberate + `(game_won)`, it selects Mercury II at 14:45:09 UTC, holds the pending client + out of loading, then begins its own load at 14:45:10. The client times out + in `network_connection_idle` at 14:45:25, before host loading completes at + 14:45:29. No second snapshot or client second-mission tick segment appears; + the host's later ticks are solo, not co-op evidence. All ten seeded files, + including the receipt, retain their audited hashes. No offer acceptance is + recorded and no stage remains. Both normal exits do not make this a pass. +- `mercury_initial_loading/gameplay-audit.json` reproduces the same failure + without campaign progression, on `f8432e2a3`, starting directly with missing + `mercury2`. Frame 02880 shows the real 749.8 MiB consent prompt; frames 03840 + and 05280 show an accepted transfer at 3%. The host starts loading while + that client is pending at 14:50:18 UTC and reaches synchronous audio + conversion at 14:50:22. The client logs its genuine connection timeout at + 14:50:33. The private runner observes that log and stops its owned processes; + both exit codes of 1 reflect this bounded failed-fixture cleanup, not normal + shutdown or separate crash evidence. No installation or gameplay is claimed, + and no incomplete map hash was needed to establish the failure. Staging and + installed-package directories are empty after disconnect cleanup. The + timeout comes from the real connection deadline; the runner neither creates + that diagnostic nor injects a failure. These two reproductions justify an + MCC-wide host loading barrier for pending consent, transfer and admission, + rather than a special case for returning campaign players. The generalized + correction is tested in the following reruns; Xbox/CE loading policy remains + outside the MCC fix's scope. +- `mercury_on_demand_fixed/gameplay-audit.json` passes on + `a972f450a1da46c2dcdc15b3c30accd473f86941`, executable SHA-256 + `03322a73077d667a32737d6d5ecd101715c82784a001865b07b85201749ca5e2`. + Only the ten-file Falling snapshot is seeded. After first-mission ticks + 30–330 and the deliberate host `(game_won)`, the host waits while the client + considers the second offer. Frame 08160 shows the consent prompt. Results + record an owner-verified Return posting, but no exact wall-clock input time; + the observed prompt and new map creation bound acceptance. The new map is + created at 14:59:52.433684 UTC and its receipt at 15:00:24.732309, an interval + of 32.298625 seconds. Identity matches at 15:00:27, when the host first + signals second-mission loading; host/client loads finish at 15:00:46/47. + Both peers have a fresh second segment of 80 samples at ticks 30–2400, + including 62 samples with both players living at ticks 570–2400. Frame + 23520 shows normal first-person gameplay and the other player marker without + the sharing overlay. All 20 snapshot files, including receipts, and ten + distinct original Workshop files match their audited hashes. The first + snapshot is unchanged, staging is empty and both processes exit with code 0. + Shared resource writes cover 686,853,355 bytes in approximately 5.457 seconds; + their hashes match both snapshots and the original. This supports local + reuse, without claiming measured network-byte savings. The bounded result + establishes download, consent, installation and follow-on co-op, not full + campaign completion or an independent state-divergence comparison. +- `mercury_initial_fixed/gameplay-audit.json` passes on the same `a972f450a` + executable, starting directly with missing `mercury2`, without campaign + completion. The first-mission snapshot is seeded for resource reuse: this + differs from the entirely empty client in the failing initial-load fixture. + The new map is created at 15:04:02.482597 UTC and its receipt at + 15:04:34.749666, an interval of 32.267069 seconds. Identity resolution and + the host's first load signal follow at 15:04:37; both peers load at 15:04:57. + Each records 96 monotonic samples at ticks 30–2880, including 78 samples + with both players living at ticks 570–2880. All 20 snapshot files/receipts + and ten original Workshop files match their audited hashes, the seeded + snapshot is unchanged, and staging is empty. Both processes exit with code + 0; each removes six generated caches totaling 767,557,632 bytes without + cleanup errors. No timeout, sharing failure, assertion or access violation + is found. This verifies the barrier during initial admission with resource + reuse, not another full-resource download, complete mission or two-PC test. +- Final barrier revision `a972f450a` passes + [Build run 42492469757](https://github.com/chestahh/GulchCE/actions/runs/42492469757) + and [MCC run 42492469720](https://github.com/chestahh/GulchCE/actions/runs/42492469720), + recorded in `build/m13-platform-final/logs/ci-a972f450a-summary.json`. + Windows, Linux, Android and web jobs and all three MCC jobs succeed; the + release job is skipped. Linux MCC reports 2,145 passed/21 skipped, Windows + MCC 2,079 passed/17 skipped. Separate preview sanitizers pass 38 cases; + metadata/storage sanitizers pass 87 with two skips. Linux's main build + selection reports 2,678 passed/27 skipped and seven subtests. These are + overlapping selections, not additive totals. Native/browser WebRTC clean + delivery is 320/320 in Chromium and Firefox; intentional loss delivers + 717/960 and 719/960 respectively. The exact final web artifact is retained + for the browser runtime checks below. Build and transport success do + not establish MCC browser download/gameplay, which remains Milestone 14. +- `legacy-final-audit.json` and the individual `xbox_final/gameplay-audit.json` + and `ce_final/gameplay-audit.json` record the final `a972f450a` native + controls, using the same executable as the corrected Mercury runs. Both + MCC opt-ins are enabled. Xbox Blood Gulch Slayer has 44 monotonic samples + per peer at ticks 30–1320; CE Death Island Slayer has 39 per peer at ticks + 30–1170. All four processes exit with code 0. There are no MCC transfer or + identity events, connection timeouts, assertions or access violations. + Each client does log a reliable-endpoint failure, internal networking error + and host departure when its host ends the timed run; those shutdown + diagnostics are retained, not described as error-free logs. Each process + removes six generated caches totaling 767,557,632 bytes without cleanup + errors. These are bounded legacy-path controls on one PC, not complete + matches or independent state-divergence comparisons. +- `build/m13-platform-final/logs/internet-a972f450a-summary.json` records all + three final native/browser cases on the exact `a972f450a` native executable + and CI web artifact: native host/browser client, browser host/native invite + join, and browser host/native server-browser join with look input. Their + run directories under `build/stage11-fix/internet/runs` are respectively + `native-host-final-a972f450a1da-v3`, + `browser-host-invite-final-a972f450a1da-v6` and + `browser-host-browse-look-final-a972f450a1da-v6`. Each records a cached second + round with 49 samples per peer and 47 paired seconds, WebRTC transport proof, + no comparator problems or divergences within its recorded tolerances, + native exit code 0, closed browser contexts and no cleanup errors. These + are Xbox Blood Gulch networking controls, not MCC browser transfer/play. + The browser client uses a null renderer; its evidence concerns state and + transport. Both browser-host cases render through real headless SDL/WebGL + and retain visual evidence of the observed command/round transition. + Local broker/loopback testing and tolerant comparison do not establish + two-physical-PC behavior, exact state equality or full-match compatibility. + +The final combined review then found a sidecar-only lifecycle defect: +`mcc_identity_prepare_host` cached Workshop attribution with map/resource +stamps, so a changed `workshop_id.txt` could disagree with the advertised +origin without changing either content digest. The real identity/Workshop +reader regression fails before the correction (`origin-before.log`). +Preparation now refreshes advisory attribution separately, rejects stale +prepared settings/offers and advances the existing revision that cancels active +offers. Gameplay and required-JSON digests remain unchanged, and unchanged +preparation retains its hash/revision fast path. The focused identity/adapter +selection passes 60 checks (`origin-after.log`), with eight unrelated mutation +controls deselected. No new network layout or Xbox/CE implementation is involved. + +Two UI follow-ups have 66 focused menu/adapter passes in +`build/m13-ui-final-results.txt`. The generated removal button now has one +dynamic text owner, preventing the renderer's static string binding from +overwriting "CONFIRM REMOVAL". The download progress overlay is suppressed +while consent is pending/visible, resumes after acceptance and clears on +disconnect; a faulty-guard control fails. These counts overlap the identity +and earlier component selections. The later combined local selection records +89 passes in `build/m13-final-identity-ui-results.txt`. The native confirmation +label is verified separately by `ruby_storage_final`, and the later Mercury +runs verify their visible consent/gameplay transitions. The final browser +networking cases and cleanup are recorded separately. Each CI/runtime result +above validates its own recorded candidate. +Browser playability remains Milestone 14 work. + +Earlier completed-run cleanup archived 266 BMP captures losslessly into +`build/m13-runtime/completed-screenshots.zip` (106,967,746 bytes). The adjacent +JSON records each original path/size/SHA-256; all ZIP contents were reread and +verified before removing 326,875,164 loose bytes. Four selected menu/lobby/game +captures remain loose. The failed `ruby_native_read` run's verified owned +incomplete stage was removed (15 files, 275,922,109 bytes), retaining its logs +and cleanup inventory. No active Mercury output, saves, installed Ruby snapshot +or original/hardlinked map inputs were removed. These bounded cleanup figures +do not describe the entire worktree's disk use. + +The final native/component cleanup receipt is +`build/m13-runtime/cleanup-final-summary.json`, linked to the per-file +`completed-cleanup-4.json`, `completed-cleanup-5.json` and +`component-cleanup-6.json` inventories. It removes 1,308 duplicate map paths +representing 111,549,211,014 logical bytes, reclaiming 4,192,861,352 unique file +bytes after accounting for hardlinks. It losslessly archives 1,404 save/capture +files from 1,114,825,697 to 144,907,310 bytes, verifying CRC and every member's +SHA-256 before removing loose copies. Four released component directories add +1,347 removed files and 134,716,129 bytes, with useful result logs retained +outside them. This pass's total net saving is 5,297,495,868 file bytes; these +figures are not additional to the linked inventories or estimates of allocated +filesystem clusters. Native runtime evidence retains approximately 410.6 MB, +including 333.2 MB of verified archives and 29 selected screenshots totaling +35.6 MB. Original Workshop/main-checkout maps, saved games, useful diagnostics, +the current build and toolchains are preserved. Browser-run cleanup is recorded +separately, rather than counted in these native totals. + +The final browser receipt, +`build/m13-platform-final/logs/internet-a972f450a-summary.json`, records complete +cleanup of all three owned runs: 2,554,260,480 bytes of disposable copies and +caches removed, plus 56,932,352 bytes of restored map copies after rehashing +their originals. Closed browser profiles retain their storage and saves in +verified lossless archives: 2,697,247,651 loose bytes become 416,811,089 archive +bytes, with each run's `profile-archive.json` preserving original paths and +hashes. The three run directories retain 558,504,712 bytes of evidence, saves +and archives; the final web ZIP/site and current build remain available. +All owned native processes, browser contexts and helpers are stopped. These +browser totals are separate from the native/component cleanup above. + +The final combined review covers the resulting PR adaptation, MCC modules, +shared integration hooks, declarations/build/settings/menu wiring, documentation +and regression fixtures across the milestone's commits. It includes independent +module review and the final documentation-to-code check. Evidence justified +corrections to native file/allocator boundaries, portable metadata identity, +advisory-origin invalidation, confirmation/consent UI ownership, bounded +completion admission and the general MCC loading barrier. The last two fixes +address reproduced lifecycle failures without replacing Xbox/CE loading policy; +their failing runs and successful reruns remain recorded. Required safety checks, +meaningful fault controls and map-family boundaries were retained. No further +unsubstantiated trimming was warranted. Final required checks run against +`a972f450a` after those corrections; this documentation closeout requires only +UTF-8, relative-link and evidence-consistency checks, which pass. + +The [PR review and unposted draft response](#pr-95-review-and-draft-contributor-response) +remain available for the user. Completion means the agreed native M13 delivery +and its bounded checks are complete, not proof of every map, full campaigns, +two-physical-PC interoperability or Android-device play. MCC/CE browser +playability, persistence and native/browser gameplay remain Milestone 14; +the MCC-only upstream protocol contribution is now Milestone 16. + +### Milestone 14: Custom Edition and MCC browser playability + +The user requires both Custom Edition and MCC maps to be playable in web +browsers. This includes loading and playing locally, receiving shared content, +and native/browser multiplayer. Review the necessary general browser/platform +changes separately from MCC compatibility logic; preserve the established +Xbox, CE and MCC ownership and loading boundaries. + +The starting web build explicitly disables Custom Edition because its tag +address window conflicts with the C heap. Its existing filesystem is WasmFS +backed by the site's Origin Private File System (OPFS), mounted at `/data`; +this is persistent browser storage, not the ordinary Downloads folder. See +[web startup](../port/web/src/web_main.c) and +[web limitations](../port/web/README.md#limits). +Establish an evidence-backed memory/loading design for each map family before +claiming that filesystem access makes those maps playable. + +Provide appropriate browser import and discovery for user-supplied CE maps, +resources and MCC packages/campaign manifests. Implement and verify downloads +through the browser filesystem, with bounded staging, integrity checks, +installation, cancellation and quota/write-failure handling. MCC downloads +remain host-only. Existing native CE sharing includes peer seeding; preserve +its established policy when supporting the browser rather than assuming CE +is host-only. Keep `maps`, `custom_maps` and `mcc_maps` separate. + +Completion requires actual CE and MCC browser gameplay and visual/audio +checks, not only compiling WebAssembly or saving downloaded bytes. Test +native-host/browser-client and browser-host/native-client roles, browser peers, +campaign follow-on missions, save/reload, browser reopening and retained +content, failure cleanup and map-family transitions. Include representative +Chromium and Firefox runs and native Xbox/CE/MCC regression controls. Record +tested maps, browser versions, resource limits and unsupported cases precisely. +Run the required platform and networking checks after the combined review. + +The following records development findings and their later resolution; failed +attempts retain their original verdicts. The initial browser memory candidate keeps +the existing 2,176 MiB linear memory and Xbox window, ends the ordinary heap +at CE's linked tag address (`0x40440000`), and gives MCC one validated 64 MiB +window in its existing accepted address range. CE initialization follows the +page's arguments and OPFS/configuration setup. MCC reserve clears reused +storage; invalid releases cannot relinquish another allocation. Independent +review found no blocking ownership or initialization defect. Native allocation +branches and the established CE loading/sharing implementation remain intact. + +On the working implementation after `b26f35fd0`, the isolated Windows-hosted +Emscripten 6.0.10 build completes, including strict Wasm linking. Portable +Python staging replaces shell-specific SDL/bootstrap copy commands; the SDL +source remains pinned to 3.4.16 with its existing checksum. Allocation exhaustion +returns failure (`ABORTING_MALLOC=0`) so loader cleanup can run. Existing native +configure arguments remain `--portable --release --pgo=off --lto=off`. +Ninja subsequently regenerated `build.ninja` for the changed build scripts; +the graph's bytes changed without changing those options. + +The real production memory fixture passes in Node and in headless Chromium +151.0.7922.34 and Firefox 153.0. Each browser refuses a 16 MiB memory, then +preserves CE/Xbox boundary bytes while four worker threads exhaust the ordinary +heap with 32 allocated 32 MiB blocks. The fixture also checks invalid MCC +addresses/sizes, exclusive ownership, wrong releases, alternate bases and +zeroed reuse. All four browser cases exit zero without page errors or stderr; +the receipt is `build/m14-web/memory-browser-results.json`. Web CI now runs +both the Node fixture and the two-browser fixture. Build/CI preflight reports +93 passed and one explicit Windows POSIX-socket skip; this overlaps earlier +component checks and is not an additional unique-test count. + +These are memory-layout checks, not CE/MCC gameplay or resource-headroom +evidence. Large converted resources, browser graphics/audio storage, imports, +download persistence and actual map-family transitions still require their +runtime gates. Owned browser contexts, loopback servers and fixture outputs +are closed/removed; the SDK, browser toolchains and current Web build remain +for the continuing milestone. + +The first bounded CE browser gameplay control passes in Edge 157.0.4341.42: +`custom_maps\deathisland`, Slayer, one browser host with its real WebGL renderer +and audio enabled. The 100-second probe records 87 player-state lines and 99 +frame samples advancing from 6 to 2,831, with no page errors or fatal result. +The retained third screenshot independently shows the rendered environment, +weapon and HUD. The final thirty audio samples report a running 48 kHz context +and nonzero signal (maximum peak 0.00300729, RMS 0.00099579); this establishes +audio activity, not an exhaustive listening/quality test. All seven original +Xbox/CE map and resource inputs retain their recorded hashes. + +Evidence is `build/m14-runtime/ce_memory_probe_5/{result.json,audit.json, +browser.log,frame-3.png}`. Its closed profile remains available for a later +persistence check; this run itself does not establish reopen/save restoration, +host downloads, multiplayer agreement, MCC gameplay or measured heap headroom. +The earlier four probes retain their actual failed/incomplete outcomes: two +fixture setup failures, an observer's invalid non-exported `HEAP32` access, +and a menu-only run missing a stock carousel fixture. They are not CE gameplay +passes. The two started but inactive profiles are preserved as verified ZIPs +before their loose copies are removed; no original maps or player saves are +discarded. Milestone 14 remains in progress. + +The initial Mercury 2 solo browser probe (`build/m14-runtime/mercury_solo_memory`) +establishes conversion/loading and simulation progress only: 30 player-state +lines through tick 901 in 180 seconds, with unchanged original Workshop inputs. +Its near-blank scene and repeated `mcc textures: upload failed, GL error 500` +are a visual failure, despite the probe's simulation-only success flag. The +MCC-owned uploader was issuing texture-swizzle parameters that +[WebGL 2 removes](https://registry.khronos.org/webgl/specs/latest/2.0/). +Its browser path now puts decoded BGRA bytes into RGBA order in the temporary +upload buffer and omits those parameters; compressed 3D or unaligned base +dimensions use the existing decoder under the +[WebGL S3TC restrictions](https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc/). +The legacy uploader is unchanged. Actual-function boundary regressions failed +all nine initial Web cases before the correction, with 29 existing/native cases +passing; all 44 expanded upload/bridge checks then pass, including cube faces, +mips, volumes, direct compressed upload, decoded fallback, channel values and +immutable source pixels. Together with bitmap flags and HUD meter checks, the +focused run passes 89 tests. These tests use a recording GPU boundary. A separate +asset-free Edge 157.0.4341.42 WebGL probe confirms the extension's shifted-level +rule: a 12-pixel base with 6/3/1-pixel mips uploads, while 1/2/6-pixel level-zero +bases are refused (`build/m14-web/s3tc-browser.json`). Its disposable browser +context is closed. + +The corrected Mercury 2 visual rerun reopens the same retained profile and +OPFS origin in Edge 157.0.4341.42 (`build/m14-runtime/mercury_visual_reopen`). +Over 180 seconds it records 106 player-state lines, frames reaching 4,340, +nonzero audio activity, no page errors and no texture-upload failures. The +primary's inspection of `frame-3.png` confirms the scene, vehicle, textures +and HUD render. The browser closes normally; this is one solo map/reopen +control, not campaign completion or multiplayer evidence. It reuses the +previous isolated OPFS profile at its original origin after explicitly +refreshing the test's code cache; this verifies retained imported content, +not the service-worker update UI or checkpoint restoration. + +A separate pregame probe (`build/m14-runtime/mercury_memory_probe`) never +reached MCC loading: validation left a temporary stock lobby map selected, +and an expired countdown repeatedly took the deferred-start branch instead +of sending its ordinary heartbeat. The MCC-owned update now keeps an active, +unpaused, nearly expired countdown alive for the full existing `map_pending` +condition, including deferred selection/validation and downloads. It does not +start stopped timers, shorten longer timers, or alter legacy-only sessions. +Regressions exercise the real countdown/start/heartbeat branch for forty +seconds: four relevant cases failed at the existing fifteen-second silence +limit before the correction; the resulting UI/network suite passes 81 tests. +Cancellation, failure, changed revisions and inactive/session transitions are +covered. The combined pregame rerun reaches 43 player-state lines through tick +1,454, confirming that the heartbeat correction gets beyond validation into +the game. Its still-broken textures predate the upload correction and are not +counted as a visual pass. + +The combined implementation subsequently passes 2,559 unique component checks +with 19 explicit skips, plus 70 Node browser-site checks. The initial broad run +reported four Windows junction-creation permission failures and one CI-wiring +failure; the targeted elevated filesystem rerun and corrected workflow resolve +all five. These totals merge per-case XML results, rather than adding overlapping +runs. Actual read-only Mercury header/geometry and available CE resource checks +are included. Missing JDK/local optional fixtures and platform-specific cases +remain explicit skips; CI must supply the relevant platform coverage. + +The final browser transaction component matrix passes 35 Chromium/Firefox +WasmFS/OPFS cases. Independent review found and corrected two additional +boundaries: a transferred Workshop sidecar must not also be journaled as a +generated companion, and asynchronous page requests need stable argument +storage plus generation checks before decoding as well as completion. The +tests reproduce rehosting and proxy execution delayed beyond the C deadline. +These are component results, not network download gameplay results. + +A Firefox 153.0 Ruby's Rebalanced `a10` probe records 96 player-state lines +and frames advancing from 5 to 3,871 in 180 seconds, with nonzero audio activity +and no page or texture-upload errors. The reviewed screenshot shows Captain +Keyes in the opening sequence. This establishes loading, rendered cinematic +output and simulation, not complete controllable gameplay or campaign progress. +Evidence is `build/m14-runtime/ruby_firefox_solo`. Separate hidden native +controls load Ruby `a10` and Mercury 2, reach their 150-tick markers and exit +zero (`native_mcc_controls/results.json`). These use read-only original +Workshop inputs and isolated saves. + +The initial implementation and test portability follow-up are committed as +`397aceefe` and `55fc7df9c`. On the latter, the +[all-platform build](https://github.com/chestahh/GulchCE/actions/runs/42500292426) +passes Windows, Linux, Android and Web, and the +[MCC validation workflow](https://github.com/chestahh/GulchCE/actions/runs/42500292444) +passes all three jobs. The first Web CI attempt exposed a standalone fixture +using a Windows pthread stub on Linux; the follow-up uses the real POSIX +header there. This CI result predates the admission correction below. + +The first complete large host-to-browser download exposes a separate MCC +admission defect. `build/m14-runtime/mcc_native_host_final` receives Mercury 2 +and its package resources/metadata: ten files, 786,191,316 bytes. Every payload +hash matches its source, the committed snapshot survives complete browser +reopening, and all original inputs remain unchanged. Nevertheless, it **fails +gameplay admission**. The staged content probe blocks browser game updates +for about 26 seconds; the host's 20-second last-heard bound expires during it. +An additional installed-identity probe then blocks for about 25 seconds, +independently exceeding the 15-second post-download admission grace. The host +starts alone. The retained `admission-audit.json` correlates both logs and +does not count publication/persistence as a multiplayer pass. + +The same synchronous identity probe runs on ordinary installed-package joins, +including when sharing is disabled. The correction therefore belongs to the +MCC compatibility engine's validation/admission lifecycle. Independent owned +checks now keep network updates running and publish SHA/CRC/resource-selection +facts only while the complete candidate snapshot remains unchanged. Actual +loading still fingerprints its opened content independently. Installed-file +checks use a bounded validation hold independent of download permission; +download verification retains the existing transfer lifetime. A successfully +published snapshot is bound locally before successful `DONE`. + +The new reliable admission contract requires base agreement 32730, MCC 70 and +camera agreements 32732/32733. Independent review corrected a stale-publication +retry loop and a backpressure gap between validation and a download offer. +The first cold installed-package run with both sharing settings off then found +an outer integration omission: the server's pregame dispatcher dropped message +105 before it reached the tested adapter. A minimal joined-machine stream +route now handles that MCC message before the ordinary ingame/loaded gate. +A regression compiles the real stream and datagram dispatchers; removing this +hook reproduces the missing acknowledgement/hold. Unjoined, unmapped, +incapable and datagram senders remain refused, and ordinary gameplay data +retains its loaded-state gate. Client ingress already has the required route. + +This cold-join run also repeated native exit `0xC0000005` after the test's +owner-checked close request. It remains under separate investigation and is +not a clean-exit result. Steam moved the original Workshop packages from `C:` +to `E:\SteamLibrary` during the run. A relocation audit verifies 39 recorded +inputs (1,238,151,561 bytes) against their original hashes, including 36 moved +Workshop files and three unchanged Xbox inputs. Historical path-check failure +is preserved; future private configurations use the verified new paths. +Runtime completion gates remain open. + +After combined primary and independent review, the corrected Windows release +and isolated Web builds pass. The resulting admission/sharing/resource, +protocol, storage, UI and build regression run reports **607 passed, 3 skipped** +(`build/m14-ingress-combined.xml`). Skips are Linux sanitizer coverage, an +unavailable Windows file-symlink privilege and a POSIX-only socket harness. +All 204 relative links in the changed documents resolve. The preceding run's +81 UI fixture errors were a missing newly required real header; the fixture +now includes it. Two safely rolled-back storage fixture installations failed +transiently with no established cause. Full and long-path reruns plus 100 +bounded repeat installations pass; added failure diagnostics retain native +error codes without retrying operations or weakening assertions. Subsequent +all-platform CI and real multiplayer results are separate completion gates. + +The CE native-host/browser-client download control passes on the initial +browser candidate: four files totaling 183,811,669 bytes, including resources, +match their original hashes and survive complete browser reopening. The +download receipt remains present. A cached second round yields 47 paired +seconds, zero tick offset and no comparison problems or divergences, with +1,074 drift samples and none apart. Its native process exits zero. The earlier +late-join run remains failed overall because its diagnostic sample phases +were not aligned; thresholds were not relaxed. Evidence is +`build/m14-runtime/ce_native_host_download_cached/result.json`. + +#### Admission fixture portability and bounded conversion progress + +The subsequent `cdba` CI build compiles all four platforms, but its Linux +reader job reports nine failures (2,222 passed, 21 skipped). One is a standalone +fixture ABI error: Linux's 64-bit `long` enlarged the copied distributed header +and padded its test envelope, so the real adapter correctly refused the packet +size. The fixture now uses the production header's fixed 32-bit fields and +asserts its 12-byte header and 216-byte envelope. A private wide-field negative +control reproduces the exact missing-ACK assertion before this correction and +passes afterward (`build/m14-lp64-fixture-proof.json`). The other eight failures +come from checkpoint fixtures missing declarations/definitions for newly +registered MCC handlers; those independent handlers now have explicit fixture +stubs while the real checkpoint dispatcher and its assertions remain intact. + +The focused identity, admission, real outer ingress, checkpoint and agreement +run then passes **52 tests** (`build/m14-load-contract-final.log`). Its ingress +fixture also checks message 106 on the real server dispatcher: joined reliable +pregame traffic reaches its handler; unjoined and datagram traffic do not, and +ordinary data retains the ingame/loaded gate. These are overlapping component +checks, not an additional unique total or a completed rerun of CI. + +The conversion-progress contract uses base **32734**, MCC **71**, and camera +**32736/32737**, with message 106 independently bound to the admitted identity +and game round. Review checked the five-second send/receive advancement limit, +thirty-second host progress-idle bound, four-minute absolute bound, terminal +peer retirement and map/session cleanup. The client's established 75-second +pre-start transport-silence bound remains separate. Required shared additions +only route authenticated MCC messages before the ordinary loaded-player gate +and connect MCC-owned state to start/completion/timeout events. Headless +conversion has the same network lifecycle; no pulse runs frame, widget, +simulation or network-dispatch callbacks against incomplete tags. See +[the protocol contract](../port/linux/NETCODE.md#mcc-package-sharing). +Final platform and actual network/gameplay validation of this revision remain +pending; these source and component findings do not complete Milestone 14. + +The actual installed-package rerun on `cdba8dc1a` +(`build/m14-runtime/mcc_installed_optouts_off_fixed`) admits the browser with +both sharing/download opt-ins disabled and no new download. Identity resolves +about 85 seconds after joining. Both machines then load Mercury 2; the native +host finishes first and removes the browser exactly sixty seconds later, while +the browser is still converting valid content. The browser subsequently finishes +conversion but cannot send its loaded acknowledgement to the disconnected host. +This is an admission pass and an overall multiplayer failure, not synchronized +gameplay evidence. The loading-progress extension above addresses this distinct +failure; its actual paired rerun is still required. + +The same run's retained debugger trace establishes a separate shared shutdown +defect. A detached `p2p_thread` calls `platform_log` through lobby withdrawal +while the main thread is already in CRT exit; the fault occurs inside the +runtime's stream lock. The MCC window destructor on the main thread's stack +does not establish an MCC allocation defect. The focused platform correction +owns both P2P workers through existing thread handles, requests stop under the +service lock, waits outside that lock, and withdraws the listing and router +mapping after worker completion. UPnP cancellation prevents subsequent owned +router requests; a third-party HTTP operation already running still has to +return. This is not a guarantee of bounded shutdown against a stalled router. +Actual-source tests and independent ownership review cover this correction. +See `shutdown-debugger.log` and +`admission-loading-shutdown-audit.json` in that run's evidence directory. + +The final focused shutdown suite passes **20 tests**, including actual OS +threads stopped during polling and UPnP completion, renewal-handle reaping, +ordinary work before exit, allocation/exit-hook failures and retry after a +failed start. Three isolated mutations removing either worker wait or the +post-select stop check fail their regressions. Router tests exercise the real +owned wrapper functions with cancellation during discovery, mapping scans, +address lookup, conflict retry and permanent-lease fallback. A mapping created +just as cancellation arrives remains owned and is removed. The actual static +P2P initializer is included in the fixture: native compilation caught its old +positional fields shifting when handles were added, so socket initialization +now names its fields. The normal Android generator emits the cancellation +import; the browser has a matching no-op. Standard Linux and Windows CI now +invoke `tools/test_p2p_shutdown.py`. + +The resulting native build passes. Three sequential, isolated public-host +controls then load the selected map, simulate and use the same owner-checked +`WM_CLOSE` procedure as the failing run. Xbox Blood Gulch and CE Death Island +each record ticks 30–840; MCC Mercury 2 records ticks 30–211. All three withdraw +their listing and exit **0**, with original inputs and the executable hash +unchanged. These are single-host exit controls, not paired-network validation, +and UPnP is disabled during them. The private launcher initially counted an +absent standalone tick log; `native_shutdown_fixed/shutdown-audit.json` counts +the actual `native.log` records and explicitly corrects that field. Evidence is +under `build/m14-runtime/native_shutdown_fixed`; the tested executable SHA-256 +is `a0625660e6880e0b839d13b94e83d92f5fc490b257543f93777a5ff0ed426b51`. +Final platform and paired native/browser checks remain required. + +The next installed-package pair, `mcc_installed_profile_loading`, uses the +normal `mccprobe` browser profile with both download opt-ins off. It has no +missing-`lastprof.txt` errors. Timestamped logs measure 59 seconds for the +identity resource check and 89 seconds for conversion; the native host waits +69 seconds after becoming ready, beyond its old sixty-second loading timeout, +and both machines then enter the mission. The browser's own player becomes +live at tick 579 and remains live through tick 1479 (31 samples). Reviewed +`client-07.png` shows its first-person weapon, HUD and mission geometry. The +native host withdraws its listing and exits zero. The installed snapshot is +reused without a download, originals remain unchanged, and all 42 exported +save/profile files (41,980,396 bytes) retain their hashes after browser reopening. + +This pair still **fails overall**: the unchanged strict judge finds zero paired +state samples because host logs occur at ticks 30/60/... and browser logs at +39/69/..., outside its two-tick pairing window. The source reporting cadence +stores the first actual report tick and subsequently adds thirty, retaining +that initial phase difference. No timestamps, states or judge tolerances are +adjusted. The separate drift counters (652 samples, five apart) do not replace +the missing state-field comparison. Loading also reports an incomplete +framebuffer and prior GL errors 506/502, retained as a separate graphics issue. +`installed-profile-audit.json` distinguishes these failures from admission, +loading, save persistence and clean-exit successes. The next paired run needs +real aligned observations and the graphics correction; this is not final +multiplayer compatibility evidence. + +Cleanup removed the controls' eighteen generated caches (2,302,672,896 bytes) +after each process exited, preserving all saves. The two closed installed-join +failures lost only their twelve generated caches (1,535,115,264 bytes); their +verified screenshot archives save a further 75,781,164 bytes while preserving +every capture and one loose native frame per run. Logs, debugger evidence, +original maps, active browser storage and future fixture seeds remain. + +Steam relocated the original MCC installation and Workshop packages from +`C:\Steam` to `E:\SteamLibrary` during these tests. A separate relocation audit +verifies all 39 recorded source files (1,238,151,561 bytes) against their original +hashes. Future fixtures use the new source paths; historical receipts remain +unchanged. This relocation was not test cleanup. The first installed-package +run's premature `sourcesUnchanged` flag is superseded by the explicit audit, +not accepted as proof after its old-path lookup failed. + +After the combined source/integration review, the local loading/shutdown +regression set passes **663 unique tests**, with three explicit skips: Linux +sanitizers, Windows file-symlink privilege and the POSIX socket harness. +The initial sandbox run could not create three directory junction fixtures; +their separately authorized reruns pass without weakening assertions. Merged +per-case receipts are in `build/m14-loading-shutdown-summary.json`; overlapping +component batches are not added to this total. The wire-format check and 262 +relative documentation links also pass. + +Browser checkpoint testing now uses an actual `mccprobe` player profile selected +through Profiles and Campaign. In `mcc_lifecycle_5`, Mercury 2 saves at tick +1,081, reverts from tick 1,441 to 1,126 and resumes simulation. The observed +Save and Quit action reaches the main menu. That helper nevertheless fails +because it waits for a network precaching message absent from this menu path; +the failed receipt is retained. `mcc_lifecycle_6` explicitly continues from that +closed run: both transient and profile-owned 20 MiB save files retain identical +hashes and timestamps across browser closure/reopening. Normal Campaign Continue +restores ticks 1,126 through 1,246, rather than starting a fresh map. In the same +browser worker, CE Death Island then advances from ticks 31 to 182 and Xbox +Blood Gulch from 30 to 180, with matching load markers and inspected rendering. + +The final Xbox-to-MCC return in that sequence is a **failure**: Mercury converts, +loads and restores tick 1,126, then reports a texture-upload GL error `506`, +preceded by a prior GL error `502`. It does not establish a successful final +gameplay/visual transition. The browser is closed, all original CE inputs are +unchanged, and saves, screenshots and the independent partial-evidence audit +remain under `build/m14-runtime/mcc_lifecycle_6`. The graphics cause and corrected +transition still require validation; checkpoint persistence alone does not +complete Milestone 14. + +The MCC standalone loading controller inherited the preceding scene's color +and depth attachments while drawing into a backbuffer-sized viewport. The +existing loading effect then paired that inherited depth surface with its +back/front buffers; the first resume log records an incomplete framebuffer +immediately after MCC loading begins. The MCC controller now selects the +backbuffer without a depth attachment before each draw. Its temporary surface +reference is released, and the next ordinary scene installs its own matching +targets. The Xbox/CE loading effect and shared renderer remain unchanged. +An actual-controller regression fails on stale attachments before the change; +the resulting loading/network/texture checks pass 72 tests, including disabled +and headless paths, repeated draws and reference cleanup. + +`mcc_lifecycle_7` reaches the restored MCC checkpoint, CE and cached Xbox +gameplay without the earlier framebuffer/upload diagnostics, but remains a +failed fixture: its observer required a cold Xbox precaching message that a +cache hit does not emit. The next observer accepts the exact current-map +diagnostic from checkpoint validation as alternate identity evidence. It still +requires fresh, increasing living-player samples after that identity, rejects +duplicate epochs, and retains the original failed receipt. + +The corrected `mcc_lifecycle_8` passes on the graphics candidate WebAssembly +SHA-256 `0a697221789f95db573082acf1f87d9603b93638eff18eee848ff334a5634cf5`. +Both 20 MiB save exports are independently rehashed before and after complete +browser closure/reopening; their bytes and timestamps match. Normal Profiles +selection and Campaign Continue restore Mercury ticks 1,126–1,246 from the +prior saved state. The same browser worker then runs CE Death Island at ticks +30–181, cached Xbox Blood Gulch at 30–180, and returns to Mercury at 1,126–1,276 +after accepting its saved checkpoint. Independent screenshot review confirms +the CE/Xbox weapon, HUD and environment and Mercury's Warthog, vehicle HUD and +textured scene. All four original CE inputs retain their hashes; the browser +closes normally. Evidence, including exact phase markers and save hashes, is +`build/m14-runtime/mcc_lifecycle_8/independent-audit.json`. + +This run has no upload error `506` or incomplete-framebuffer diagnostic, but +the final return still reports **prior GL error `502`** before an MCC upload. +Its origin remains under investigation; the run is not described as entirely +GL-clean. This is one Edge solo checkpoint/lifecycle control, not Firefox, +multiplayer or complete-campaign evidence. It uses the graphics candidate +before the subsequent combined sampler/resource-optimization rebuild. + +The combined current component suite passes **885 tests with eight skips** +(`build/m14-candidate-combined.log` and `.xml`). Skips cover Linux sanitizer +coverage, unavailable Windows file-symlink privilege, a POSIX socket harness +and five POSIX/Linux launcher/process-lifecycle checks. This overlaps earlier +batches and is not added to them. Independent review checks the final graphics +and Web-only reader changes, ownership, bounds and documentation; combined +platform builds and paired gameplay results follow below. + +The combined native and Web builds at `5aff08a4d` pass. The +[platform workflow](https://github.com/chestahh/GulchCE/actions/runs/42511946653) +and [MCC workflow](https://github.com/chestahh/GulchCE/actions/runs/42511946635) +are green: Linux, Windows, Android and Web, including Chromium/Firefox +WebRTC transport and the MCC reader, adapter and rendered-HUD checks. +`build/m14-combined-ci-results.json` records exact jobs and selected test +summaries; overlapping platform suites are not added into a unique total. +The local runtime receipt, `build/m14-runtime/final-combined-build.json`, +binds that source revision to the native executable, SDL library and all +29 site files. Runtime preflights and closing audits verify those files and +the private helpers, including their transitive dependencies. + +`mcc_installed_aligned` passes the unchanged strict judge for **47 paired +seconds**, with zero tick offset and no divergences under its existing +tolerances (maximum position difference 0.536 units and aim difference +7 degrees). Browser player one lives from ticks 570 through 1,500. Both +download opt-ins are off; the existing snapshot is reused without a transfer. +Native shutdown exits zero, original inputs remain unchanged, and 42 exported +save/profile files (41,980,396 bytes) retain their hashes after reopening. +The actual admission resource check takes 18 seconds versus the preceding +59-second case. Conversion takes 97 seconds versus 89, including 61 seconds +in its separate resource stage; this is not an aggregate loading-speed gain. +The host safely waits 78 seconds for its client. The prior GL502 diagnostic +remains, without upload506 or incomplete-framebuffer failures. See its +`installed-aligned-audit.json` for exact settings, timings and limits. + +`mcc_falling_download_follow_on` exercises the actual consent prompt, then +receives the missing Mercury Falling mission with metadata and previews. +Its new verified snapshot contains 731,791,026 bytes; the bitmap/sound pair +accounts for 686,853,355 bytes and is also present in the existing snapshot. +Staged composite verification takes 15 seconds. The first mission passes +**47 paired seconds**; after the host's normal `game_won` command, Mercury II +passes **63 paired seconds**. Both windows include a living browser player +and reviewed first-person screenshots. Mercury II resolves to its existing +verified snapshot without a second mission download. Both snapshots, original +inputs and all 42 exported save/profile files survive the closing/reopen audit. +Native shutdown exits zero. Local resource reuse is established by the +implemented receipt/hash path and observed installation; transport byte totals +were not collected, so no measured wire-byte saving is claimed. + +The private helper's final result remains **failed**: it expected a separate +Continue button, whereas the actual campaign returned to the correct lobby +and used its normal countdown. After independently collecting the successful +second comparison, the primary authorized an ordinary, owner-checked close; +the obsolete helper gate reports that close as premature. No fictitious +button press or modified comparison is used. `campaign-progression-audit.json` +preserves this distinction and both mission results. This is a bounded +campaign handoff, not completion of either campaign; GL502 remains recorded. + +The two closed paired runs remove 1,535,115,264 bytes of generated native +caches and 3,735,053,104 logical bytes of redundant hardlink aliases (no +physical-byte saving attributed to those aliases). Verified screenshot +archives reclaim another 120,175,146 bytes. Separately, the completed combined +regression fixtures retain all 2,711 files, including six synthetic saves, +in a verified 61,399,082-byte archive before removing their 315,766,634 loose +bytes. Lifecycle5–8 retain all twelve save exports and command screenshots +in a verified 25,072,003-byte archive before removing 270,616,451 loose bytes. +Active browser content and current builds remain for the remaining runtime +matrix; their final cleanup is not claimed here. + +#### Browser identity-check read cost + +A private synthetic benchmark identifies OPFS read overhead in the incremental +MCC checker. Emscripten 6.0.10 implements each read-only OPFS Blob read through a +worker proxy and `Blob.slice(...).arrayBuffer()`. The stdio refill can issue two +backend reads. This is source evidence for an I/O cost, not a reason to omit +either CRC or SHA verification or extend admission deadlines. + +The controlled experiment compiles the actual resource checker, SHA and CRC +implementations, changing only its read-buffer size and adding scoped counters. +Two generated 32 MiB resources and a 5,632-byte generated MCC map have an +independent Python CRC/SHA oracle. No retail assets are used. Each candidate +runs on a 256 KiB fixture-worker stack. The production validation worker requests +that size, but the platform thread wrapper enforces a 1 MiB minimum. The fixture +retains the production 2 ms and 4 MiB thresholds checked between reads; a final +read can cross the byte threshold by less than one chunk, as with the former +16 KiB reader. Three rotated OPFS trials per size and browser, MEMFS +controls, cancellation and injected read failures run serially in isolated +profiles. All other task builds, games and heavy I/O are idle during the +authoritative run, 2026-11-08 18:30:46–18:31:52 UTC. + +| Browser | 16 KiB median | 32 KiB median | 64 KiB median | +| --- | ---: | ---: | ---: | +| Edge 157.0.4341.42 | 4.730 s | 2.314 s | 1.394 s | +| Firefox 153.0 | 3.714 s | 2.736 s | 2.254 s | + +Actual backend calls fall from 8,194 to 4,098 to 2,050. Edge's measured read +time falls from 4.479 s to 1.156 s while SHA remains about 0.222 s and CRC about +0.016 s. Firefox's read time falls from 1.940 s to 0.604 s; SHA remains its +larger remaining cost. MEMFS controls show no meaningful improvement. All +24 complete checks match the independent identity; all six cancellations and +six read failures leave identity outputs unpublished. At 64 KiB, observed +cancellation takes 2.85 ms in Edge and 1.24 ms in Firefox. The time budget is +checked between reads, so an individual blocking read can exceed 2 ms. + +Accordingly, only `HALO_WEB` uses a 64 KiB buffer in +[`mcc_resource_check.inl`](../port/linux/game/mcc_resource_check.inl); native +builds retain 16 KiB. Byte framing, checksum algorithms, slice limits, +cancellation ownership and all network deadlines remain unchanged. The real +checker regression runs both native and browser reader branches against +independent CRC/SHA values around 64 KiB and 128 KiB boundaries, odd tails, +cancel/restart and failed-read recovery. + +Evidence is retained under `build/m14-check-bench`: `clock-fixed/results.json`, +`clock-fixed/summary.json`, source/artifact receipts and `report.txt`. Earlier +runs are explicitly superseded: the private fixture's direct floating-point +clock cast saturated on an epoch-sized worker timer, exercising only the byte +limit. The corrected fixture wraps through a 64-bit integer to match the +production 32-bit clock. Production clock code is unchanged. The final timing +run also occurs after a separate cleanup ended at 18:26:07 UTC, removing that +earlier contention concern. All six closed synthetic profiles are removed +(545,122,024 bytes); logs and fixtures remain reproducible from source. + +These are first-open/reopened reads after fixture creation, not guaranteed +cold-cache measurements or full-game performance. The combined installed-package +and post-download runs above subsequently exercise this reader in actual games; +their receipts own those results. No timing guarantee or completed multiplayer +gate follows from the benchmark alone. + +#### Shared renderer diagnosis and final map-family controls + +The retained prior GL502 errors are now explained by a shared renderer defect, +independently reproduced with CE Death Island as the first loaded map, without +MCC content. A private instrumented copy observes four `glDrawArrays` failures +while creating the water-ripple mip targets (128, 64, 32 and 16 pixels). On all +four draws, active sampler three's texture ID exactly equals the framebuffer's +color attachment: 5311, 5315, 5317 and 5319. These are forbidden sampling/output +feedback loops, not an MCC texture format rule. The isolated diagnostic retains +its source patch and receipts; all 919 recorded normal source/object/artifact +hashes remain unchanged by instrumentation. + +`prepare_draw` deliberately selects sampled textures before render targets: +resolving a sampled target can itself change the framebuffer. However, allocating +a new target in `render_target_get` then overwrote the active texture binding +with the output image. Invalidating the binding cache did not restore the actual +sampler for that draw. Commit `4c7355ae1` saves and restores that unit's actual +2D binding around allocation. Existing cached lookups, resolve ordering, +intentional feedback copies and map-family routes remain unchanged. Callers +consume returned IDs or bind explicitly; none requires the incidental binding. +The two extra GL operations occur only on new target allocation. This fixes the +shared renderer contract and changes neither simulation nor network agreement. + +The actual-function regression fails six cases and passes three before the fix; +all nine pass afterward. The combined renderer/loading/texture/presentation and +CI selection passes **157 tests**. Normal Windows and Web builds pass, recorded +in `build/m14-binding-native-build.log` and `build/m14-binding-web-build.log`. +The immutable `build/m14-runtime/combined-build-4c7355ae19e0.json` binds the +production revision to all 29 site files, SDL and the native executable +SHA-256 `33f0afc4daaf3104fc87ec95857dbc20e80dcaa4d5802f655345c423e58a1a16`. +Private diagnostic builds are not used for final gameplay validation. + +The final normal browser run, `mcc_gl_final_4c7355_2`, passes Mercury 2 → +CE Death Island → Xbox Blood Gulch → Mercury 2 in one worker with GL debug +enabled. Living-player samples span ticks 1126–1290, 30–180, 30–180 and +1126–1290 respectively. Each phase has its own current-map evidence and reviewed +rendered scene. There are no GL502/506, upload or incomplete-framebuffer errors +in either game or raw browser logs. The normal artifacts and original CE inputs +retain their hashes. This is a graphics/lifecycle control, not a new checkpoint +persistence assertion; `mcc_lifecycle_8` retains that evidence. Existing Bink and +recorded-animation diagnostics and four intentionally blocked external requests +remain recorded, so this is not an assertion that every warning disappeared. +The preceding attempt's profile-menu observation timeout is retained separately. + +Three final hidden native controls use that same executable with GL debug: +Xbox Blood Gulch, CE Death Island and MCC Mercury 2 each record twenty living +samples through ticks 30–600, withdraw their public listing and exit zero, with +no GL errors and unchanged originals. The Mercury screenshot was reviewed. +The private launcher omitted creating Xbox/CE capture directories, so these two +native controls establish simulation/shutdown, not new native visual evidence; +their browser scenes are covered above. Receipts are under +`build/m14-runtime/native_renderer_final`. + +#### Final Custom Edition sharing and browser storage checks + +On `5aff08a4d`, the browser-host/native-client Death Island run downloads all +four files (183,811,669 bytes), preserves the trust record and passes separate +strict comparisons of **61 and 47 paired seconds**. The first has one transient +aim mismatch, no sustained divergence and maximum position difference 0.003; +the cached round has no mismatches and maximum position difference zero. +Screenshots, original hashes, reopening/persistence and native exit zero are +verified. Its original helper verdict remains failed because it searched native +stdout instead of the actual native debug log for the completion message. +`ce_browser_host_download_cached_final/independent-audit.json` verifies both +rounds and the completed transfer; offline negative controls reject the old +log selection and a missing completion message. + +The separate CE host-sharing-off and client-download-off browser controls pass +their actual prompts with zero CE arrivals before or after reopening. They retain +normal native exits and unchanged inputs. Their evidence directories are +`ce_share_off_final_2` and `ce_download_off_final`; the earlier negative-case +observer failure remains recorded. + +The final `ce_browser_pair_4c7355ae19e0` uses two Chromium/Edge browser peers and +the normal combined renderer. It receives the same complete four-file package +and passes **59 paired seconds** after downloading, then **47 paired seconds** +in the cached round. Both have zero position differences and no mismatches, +problems or divergences under the unchanged judge; maximum aim differences are +12 and 2 degrees. Actual data-channel counters record 195,921,200 bytes sent by +the host and received by the client, including protocol/game traffic. Both +rendered scenes are reviewed; there are no page or GL errors, and reopening, +payload hashes, original inputs and all normal artifacts pass their audits. +Both contexts close. Two-peer coverage does not establish a third peer's optional +CE seeding behavior; the existing CE policy is preserved and MCC stays host-only. + +The separate final Firefox **153.0** CE Death Island control closes the +remaining actual-rendering browser gap. It records 92 living-player samples +through ticks 33–2760 over 90.903 seconds, with rendered frames advancing from +7 to 2974. Reviewed first and final captures show the shoreline, water, sky, +weapon and HUD. Thirty late audio observations have a running context and +nonzero signal (peak 0.08303, RMS 0.02229). There are no GL, upload, framebuffer, +page or fatal errors, and original inputs, helpers and normal build artifacts +retain their hashes. The browser closes normally. This is solo gameplay, +rendering and audio-activity evidence, not a full Firefox CE networking matrix +or an exhaustive listening test. `ce_firefox_final_4c7355ae19e0/independent-audit.json` +records the result. Verified cleanup removes 767,557,632 generated cache bytes +and 240,744,021 duplicate imported bytes, preserves all 38 saves and 41 separate +exports, and leaves 33,992,254 bytes of useful evidence. + +The `4c7355ae1` Web CI failure was in the fault-injection fixture, before the +intended lost-COMMIT operation: its global one-second deadline expired during +ordinary BEGIN. A deterministic 1.5-second BEGIN delay reproduces that failure. +Commit `fa00317d5` changes only the two test files, retaining the production +30-second allowance for ordinary operations and applying one second only around +the deliberately lost/delayed BEGIN or COMMIT. The test also requires COMMIT +actually to be reached. Production storage code, its deadlines and its uncertain +completion fencing are unchanged. Independent review and all **35 actual browser +cases**, **85 component checks**, and **21 wiring checks with one POSIX skip** +pass. The slow ordinary BEGIN remains a regression. Before/after receipts are +`build/m14-storage-timeout-before.json` and `-final.json`; the normal runtime +artifacts remain those of `4c7355ae1` rather than being relabeled as rebuilt. + +The corrected [Build run 42517549228](https://github.com/chestahh/GulchCE/actions/runs/42517549228) +passes Linux, Windows, Android and Web debug builds and their required checks. +Linux's broad selection reports 2,678 passed, 27 skipped and seven subtests; +subsequent selections also pass. Web runs all 35 storage scenarios on Chromium +145.0.7632.6 and Firefox 146.0.1, plus the memory/import suites and native WebRTC +controls. Both browsers return 320/320 ordinary messages; the deliberate +ten-percent datagram-loss controls return 720/960 and 730/960 respectively. +These transport controls are distinct from loaded-map gameplay. The +[MCC run 42515942272](https://github.com/chestahh/GulchCE/actions/runs/42515942272) +passes readers, Windows adapters and rendered HUD checks on the unchanged +production revision. The fixture-only follow-up does not trigger that +path-filtered workflow. Exact job metadata and full selected logs are retained +in `build/m14-final-ci-results.json`, `build/m14-binding-ci-results.json` and +`build/m14-final-ci-*.log`. Branch-skipped release jobs and asset-dependent skips +are not runtime passes; overlapping suite totals are not added together. + +The first Firefox-host/native-client Ruby `a10` run, +`mcc_ruby_browser_host_final`, presents the ordinary local-package consent +prompt without an invented Workshop link. It transfers the complete +275,753,385-byte map, locally generates its 393-byte receipt and loads both machines. +The map-only fixture supplies no JSON or thumbnails. Original/build hashes, +normal native exit and browser reopening pass. However, the 900-second private +test limit expires after roughly 217 seconds of the authored opening cinematic, +before player one becomes live. Its **overall failure is retained**; cinematic +simulation is not substituted for the live-player requirement. A separate +observer defect also searched native stdout instead of the actual debug log for +the successful installation marker. The corrected observer keeps the strict +judge's original network logs and thresholds. Subsequent cached gameplay uses +the exact verified downloaded map/receipt and records its own result. + +The first cached attempt, `mcc_ruby_browser_host_cached_final`, exercises the +normal two-peer Space skip vote and reaches living-player gameplay, but still +fails the unchanged judge. It includes 43 compared cinematic samples with +player zero's unit aim 90 degrees apart, and only ten paired live-player samples +after the skip, yielding 291 drift observations against the required 300. +The private helper had counted cinematic time toward its gameplay duration. +This verdict remains failed, despite correct content reuse and native exit zero. +The stored unit aim is distinct from the separately synchronized cinematic +camera; the observed difference is not dismissed as an allowed camera offset. + +The strengthened control, `mcc_ruby_browser_host_gameplay_final`, starts its +explicit gameplay interval at the first paired post-skip state where both +players are alive and retains every subsequent state, including any deaths or +mismatches. It requires at least 45 seconds of that interval and the unchanged +strict judge, including at least 300 drift observations. Private regressions +reject counting the intro, stale/repeated tick epochs or discarding bad rows. +The actual interval spans ticks 1380–2820, **49 paired observations over 48 +seconds**, with zero position difference, maximum aim difference 10 degrees, +1,163 drift observations (nine apart), and no problems or divergences. Both +rendered local-player views are inspected. The full-log judge separately passes +90 paired observations on this run, including the intro; its one transient +alive mismatch and one riding mismatch remain recorded. The earlier failed +cinematic comparison is not replaced by this later result. + +Both download opt-ins are off in the successful cached control. Its native +client receives only the prior audited map and receipt as an explicitly recorded +fixture seed, with no network retransfer or newly installed content. Original +inputs, helpers and normal artifacts remain unchanged; browser reopening and +native exit zero pass. The source review finds that inhibited controls preserve +local desired aim while ordinary object corrections synchronize transforms, +not that internal aim. The relevant shared implementations are unchanged from +Milestone 13. The intermittent cinematic discrepancy therefore needs a separate +scope investigation; this run establishes the measured gameplay result, not +universal cinematic unit-state agreement. + +`mcc_ruby_browser_pair_final` then transfers the complete local Ruby package +from Chromium/Edge to Firefox 153.0 after the observed consent prompt, with no +package files written before acceptance. Its installed snapshot contains the +275,753,385-byte map and a locally generated 393-byte receipt; local publication +also writes the browser commit record. No JSON or thumbnails are invented for +this map-only folder. Both machines use the +normal two-peer skip vote. The explicit live-gameplay comparison passes +**49 paired observations**, with maximum position difference 0.001414 units, +maximum aim difference 2 degrees, 1,347 drift observations (six apart), and no +mismatches, problems or divergences. Primary raw replay produces the same result. +The separate full-log comparison passes 123 paired observations under the +unchanged judge, retaining one transient position mismatch (8.971 units) rather +than treating it as zero-error or bit-exact simulation. + +Its original overall verdict nevertheless remains **failed**: after gameplay +and the first storage audit, Firefox's fresh `about:blank` profile launch times +out at 180 seconds with `RenderCompositorSWGL failed mapping default framebuffer`. +No game page or worker loaded in that failed startup. The owned startup processes +terminate themselves; no user process is stopped. A separate normal same-profile, +same-origin plain-HTML reopen succeeds and rehashes every previously +hashed package, receipt, commit and save file unchanged. The independent +`independent-firefox-reopen.json` supplies that persistence proof without rewriting +`result.json`. Chromium's ordinary closing/reopening audit and all original/build +hashes also pass. This separates actual transfer/gameplay and recovered storage +verification from the browser-launch fixture failure; it is not a claim that +the first launcher attempt succeeded. + +#### Separate shared cinematic-state finding + +A native-only, ownership-matched control reproduces the inhibited-player state +discrepancy without any browser. The host first reaches a living player zero +with local index zero and machine zero; only then does the native client launch. +The client initially has neither unit at tick 602. Across 31 paired living-unit +observations at ticks 630–1530, the host's player-zero aim is 0/0 degrees and +the client's is 122/−86 degrees; body facing also differs (0 versus 36 degrees), +while positions match exactly. The unchanged judge reports a sustained aim +divergence. Zero client-on-foot drift is expected in this intro-only diagnostic, +but is not waived into a gameplay pass. Both processes exit zero and the four +original map inputs and frozen executable retain their hashes. + +An earlier native control has no such difference over 32 paired observations, +but the client owns player zero in that run, so it does not reproduce the same +ownership and creation ordering. The initial native fixture's missing carousel +failure and original empty-log diagnostic are also retained, with the latter's +actual stderr evidence judged separately. These are distinct observations, not +retries selected to erase a failed result. + +Source inspection traces the shared gap: input-inhibited player controls keep +their local desired facing/aim/look vectors with zero buttons, throttle and +trigger. Ordinary object corrections replicate transforms, not those internal +vectors, and actor aim replication excludes player-owned units. Co-op camera +presentation is synchronized separately. The relevant `network_coop.c`, +`network_objects.c`, `network_actors.c`, `players.c` and `units.c` are unchanged +from Milestone 13 (`b26f35fd0`); no older binary was run in this investigation. +The evidence establishes that browsers are not required to expose the problem. +It does not establish harmlessness, full cinematic pose agreement or a safe +correction based merely on copying body-forward into aim. + +This remains a separate shared co-op follow-up, outside the browser implementation +delivered here. Before upstream delivery, investigate authoritative inhibited +player state across creation, scripted changes, late joins and checkpoint +restoration, then validate a focused fix against ordinary input and all affected +map families with the required network-version review. Do not hide this finding +with an MCC/map-name exception or a relaxed comparison. Evidence is under +`build/stage11-fix/runtime/m14_ruby_native_cinematic_late/independent-audit.json` +and the two preceding native diagnostic directories. Verified archival retains +all saves and captures; the three directories total 3,980,721 bytes, separately +from the `build/m14*` inventory. + +#### Final manual-download guidance and Stock-menu acceptance + +The final opt-out control exposed an MCC prompt-lifetime defect. With host +sharing off, the Workshop-only guidance appeared correctly, but the host's +ordinary 15-second playerless-client timeout replaced it with a generic closed +game error. `mcc_host_off_prompt_before` retains both observed screenshots and +its original failed observer verdict. The fix belongs to the MCC sharing +adapter: when there is no download path, leave the unjoinable session normally +and retain only copied guidance and Workshop origin until the main menu opens. +No host timeout or shared admission behavior changes. New sessions, map loads, +dismissal and repeated disconnect clear that detached state; stale acceptance +and Workshop actions cannot act on another session. + +Eight initial adapter cases fail before the correction. The completed sharing, +identity, admission and Workshop batch passes 198 tests with one POSIX-only +skip on Windows. A further regression rejects forcing the PC main-menu root: +detached guidance has no lobby history and dismissal now queues the engine's +normal selected-menu transition. The final menu/sharing batch passes 311 tests. +The Windows touch wrapper's POSIX `-lm` assumption fails separately; compiling +and running the same production touch test for x86 MSVC passes. That launcher +limitation is not presented as a product failure or a skipped runtime pass. + +`mcc_host_off_prompt_fixed` (Edge) and `mcc_client_off_prompt_fixed` (Firefox +153.0), on `f819da8a2`, retain the correct Workshop-only prompt beyond the old +timeout. Firefox's ordinary Escape dismissal returns to the main menu. Both +cases leave MCC content absent, close the native process with exit zero, +preserve source/build hashes and pass storage reopening. External-resource +warnings remain recorded. These are opt-out and lifecycle controls, distinct +from the completed transfer/gameplay evidence above. + +The menu audit also finds obsolete desktop/Android filters on Map Sharing in +the Stock settings generator. Removing that filter exposes client downloads, +host sharing, MCC package options and managed-download removal on web; Steam +Workshop discovery remains desktop-only. The additive menu wiring uses the +existing MCC services and does not depend on the optional Gulch frontend. +Generated Stock main-menu and in-game routes are checked on desktop, Android +and web. All three browser reachability cases fail before the correction and +pass afterward; no XML is edited by hand. + +`mcc_menu_stock_host_off` explicitly sets `HALO_MENU_FRONTEND=off` and +`HALO_MENUS=pc` on the normal `ad3cfe859` artifacts. The actual Edge/native-host +pair verifies Workshop-only guidance, ordinary dismissal, and keyboard routes +through Settings, Network Setup, Map Sharing, MCC Packages and MCC Downloads, +then back to the main menu. Screenshots show campaign and collection controls, +no desktop-only Steam discovery, and an empty download list without a removal +action. The run passes WebRTC transport, no unintended download, reopened +storage, unchanged input/artifact hashes and normal native exit. Exact artifacts +are recorded in `build/m14-runtime/combined-build-menu-parity.json`; its native +SHA-256 is `4fa2c6385196cbc3807ebdff9479f144b39b230e5b36ef3b4be086c690a73aa0`. +This is Stock/OpenCE functionality in the refactored fork; the actual upstream +branch still requires its own validation in Milestone 16. + +The user subsequently limits browser acceptance to Stock/OpenCE: Gulch does not +host the browser build, and its Modern and styled menus are desktop features +with prior desktop coverage. Unstarted Classic PC/Xbox browser runs are cancelled. +The already-running Modern opt-out test closes normally after two navigation +steps; its passing refusal/storage verdict is not a complete styled-menu audit. +The separately committed `8325b12a4` restores Modern links to existing stick +dead-zone and Discord editors, with 132 focused tests and local Windows/web +builds passing. That Gulch-only change and its menu-specific tests are excluded +from the MCC upstream contribution. No further styled-menu browser checks are +required by this milestone's agreed scope. + +The final MCC/Stock revision has green +[four-platform CI](https://github.com/chestahh/GulchCE/actions/runs/42525526884) +and [MCC CI](https://github.com/chestahh/GulchCE/actions/runs/42525526813). +Linux's broad batch passes 2,678 tests, skips 27 and passes seven subtests; +separate batches remain separate rather than inflating a unique count. +Web passes 70 and 30 Node tests, 24 Python checks, the real browser storage and +memory/import checks, and Chromium/Firefox transport: 320/320 replies each, +715/960 and 708/960 with deliberate ten-percent datagram loss. Branch-skipped +release builds and asset-dependent skips remain limits. Full selected job logs +are retained as `build/m14-stock-ci-128868283440.log` and +`build/m14-stock-ci-128868283414.log`. + +Final primary-agent review covers the combined browser memory/import/storage +implementation, admission/loading ownership, graphics corrections, prompt +lifetime, menu wiring, protocol declarations, tests and documentation. Earlier +independent reviews are recorded separately; no subagents are used for this +final pass. The review retains separate CE/MCC implementations, bounded +identity-specific waits, untrusted-input checks and failure evidence. It finds +no additional justified production rewrite after the documented corrections. +The cinematic finding above remains a separate shared-engine follow-up; this +completion does not claim complete campaigns, every browser/device, or universal +cinematic agreement. + +All final test games are closed. Each prompt/menu run removes its verified +map aliases and generated native/browser caches, then verifies lossless archives +before removing loose saves/captures. The formerly retained seed removes +1,867,526,552 logical bytes of aliases, with all its saves preserved in a +3,336,710-byte archive; alias removal is not claimed as physical-byte savings. +Completed prompt/menu harness fixtures remove 770,535,876 bytes of temporary +binaries and generated data, retaining diagnostics and synthetic saves in a +verified 7,348,275-byte archive. Cleanup receipts remain beside their evidence; +original Workshop packages, original maps and active user saves are untouched. +Another 31 inactive save/export directories preserve all 1,112 files in a +verified 14,622,564-byte archive before removing 847,804,268 loose bytes. +`build/m14-runtime/final-inactive-saves.json` records the original paths and +hashes for restoration. The final `build/m14*` inventory retains approximately +2.86 GB, chiefly diagnostic archives/captures and the 128 MB current web build; +the separate native cinematic evidence remains approximately 4 MB. Current +native builds and installed toolchains remain usable. The final document review +checks 567 local links across the milestone's changed Markdown with none missing. + +### Milestone 15: MCC HUD corrections and shared cinematic aim + +The final production implementation is `e818c391a1f0ce2f98706fbad13afee2e8aae692`. +This milestone corrects three MCC compatibility-engine defects and one shared +co-op state defect. No map-name, Workshop-ID, weapon-name or resolution-specific +selector was added. The work remains on `mcc-code-refactor`, performed by the +primary agent only. Milestone 16 has not started. + +#### Causes and implementation + +The supplied screenshots establish symptoms. Bounded map-tag inspection, +actual-source regression tests and paired native captures establish these causes: + +- Ruby's converted message offset is 65 rather than the existing recognized + stock value of 60. Its weapon panels nevertheless select the native safe + frame. Infinite Evolved's custom ballistic parent rearranges numbers inside + an otherwise matching panel and misses the complete-layout fingerprint that + recognizes its battery/grenade panels. The recognized active **unit HUD** now + supplies the common corner frame for messages and weapon panels during that + player's draw. Authored offsets, center/edge anchors and unknown custom unit + HUDs retain their existing treatment. This extends the existing explicit + stock-layout compatibility exception without adding fingerprints. +- Scope screen effects bypass ordinary HUD placement. Their MCC bitmap group + declares half-size display, but this renderer used raw bitmap dimensions. + An MCC-owned scoped transform applies that flag once, separately from the + 2:1 MCC placement canvas. Size and texture-coordinate changes preserve the + complete mask. Untagged/generated fallback bitmaps remain in native units. + Xbox and CE rendering remain outside the MCC transform. +- The native Ruby intro trace records a late client attaching the host's unit + two ticks before input inhibition arrives. Relayed input changes its aim; + inhibition then preserves that local aim. Unit snapshots carried body axes + but no desired/current aim or look, and player units are excluded from actor + control replication. The shared snapshot now carries five distinct direction + vectors while input is inhibited or the unit is suspended, plus host suspension + state. Body-forward cannot substitute for these authored directions. + Correction reconciles orientation even at an already matching position and + bypasses ordinary input-prediction history for a scripted pose, retaining the + co-op BSP guard. Complete bounded decoding and direction validation precede + application. Client predictions carrying host-only pose/suspension fields + are rejected. Ordinary input snapshots omit the extension and retain their + tested byte representation. + +The HUD logic lives in [mcc_hud_draw.c](../port/linux/game/mcc_hud_draw.c). +Its minimal, `port:`-marked shared hooks supply the current player's unit and +bracket the synchronous screen-effect draw. MCC modules alone cannot establish +those draw boundaries. Borrowed pointers and frame selections are released at +end-of-draw, with no tag mutation, allocation or persistent per-player cache. +The pre-existing message/component fallbacks remain necessary for unknown unit +HUDs; removing them would not be justified simplification. The HUD work changes +rendering only. + +The cinematic fix belongs in the existing shared unit-state implementation, +[network_distributed.c](../port/linux/game/network_distributed.c): suspension, +input inhibition and authored unit aim already exist across Xbox/CE/MCC. This +corrects missing replication of that contract, rather than introducing MCC +semantics into legacy code. It adds 30 direction bytes only to scripted live +unit snapshots. Bounds and maximum packer size include the extension. It adds +no independent lifetime table. The shared network agreement changes from 32734 +to 32738, MCC from 71 to 72, and camera agreements from 32736/32737 to +32740/32741. Admission tests reject the previous agreements. Milestone 16 must +carry this contract into the unified upstream version. + +#### Rendered checks + +Private evidence is under `build/m15/inventory/` and `build/m15/runtime/`. +Each controlled HUD fixture records its executable hash, settings, map identity, +commands, captures and cleanup. Test-only equipment selection is not a gameplay +correctness test. Original Workshop maps and legacy map files remain unchanged. + +| Check | Observed result | +| --- | --- | +| Ruby `c20`, objective and assault-rifle ammo, 1280x720 | The message moves from the inconsistent MCC corner frame to the panel's native frame, leaving clear separation below the bullet rows. Both normal and high-resolution HUD settings were reviewed. | +| Infinite Evolved `a30`, ballistic and battery weapons | Ballistic panel moves from approximately (50,20) to (114,55), level with the grenade counter. The previously correct battery panel retains its position. Authored digit arrangement is preserved. | +| Ruby pistol 2x, 1280x800 and 1024x768 | Circular mask changes from about 800 to 400 pixels high at 1280x800; it is centered and about 384 pixels high at 1024x768. | +| Ruby sniper second zoom, 1280x720 | Rectangular mask is centered at about 580x360 pixels with the authored 10x indicator. | +| Infinite Evolved sniper 2x, 1280x720 | Oversized near-screen-filling mask becomes about 580x360 pixels, aligned with the existing scope ticks. | +| Xbox Blood Gulch and CE Death Island pistol scope | Before/after mask dimensions and HUD placement retain their established behavior. | +| Descent custom HUD | Before/after captures with the authored letterbox cleared retain the custom top-center shield, right ammo, left grenades and radar placement. This controlled scene is not a campaign-progression test. | +| One process: Ruby → CE Death Island → Xbox Blood Gulch → Ruby | Four independently observed map loads, equipped scoped weapons and reviewed captures; masks and frames remain correct after each transition. | + +Matched labels include `ruby-help-baseline`/`ruby-help-fixed`, +`hie-ballistic-baseline`/`hie-ballistic-grenades`, +`hie-battery-before`/`hie-battery-after`, +`ruby-scope-baseline-v5`/`ruby-scope-fixed-v1`, `hie-scope-before`/`hie-scope-after`, +`descent-hud-before-v2`/`descent-hud-settled` and `hud_transitions_v3`. +The old probe's grenade inventory differs from the later fixture; those +counts are not attributed to the rendering fix. + +Earlier attempts remain failed: Mercury's first requested weapon was absent; +the later vehicle-opening fixture rejected equipment insertion. Neither proves +Mercury scope behavior. Initial Descent captures retained an animated letterbox; +settled captures replace them for visual acceptance. An overlong transition +console expression was split into bounded commands. No production accommodation +was added for those test-fixture failures. Split-screen active-HUD selection, +custom anchors and view reset are exercised by actual-source tests; no rendered +split-screen session is claimed. Pickup text and every custom HUD are not +exhaustively captured. + +#### Cinematic and network evidence + +Read-only instrumentation in `cinematic_trace_baseline` records 31 paired living +host-player samples with matching positions but persistent aim mismatches, +reaching 166 degrees. `cinematic_fixed_trace_v2` records 31 paired samples with +zero position/aim mismatches and matching desired/current directions and body +orientation. These intro-only observations lack a living client for the strict +drift judge and are not themselves a full networking pass. + +Production native controls use the unchanged strict comparison thresholds: + +| Case | Post-intro/gameplay result | +| --- | --- | +| Ruby late join, normal two-player skip vote, checkpoint/revert | 61 seconds, 122 player pairs, zero position error, maximum aim difference 3 degrees; 1,827 drift samples, none apart. No judge problems/divergences. Checkpoint taken and reverted; both peers continue for 900 ticks. | +| Xbox `b30`, early join, natural intro, checkpoint/revert | 61 seconds, 122 player pairs, maximum position difference 0.003742 and aim difference 4 degrees; 1,830 drift samples, none apart. Both engine save/revert acknowledgements are required and observed. No judge problems/divergences. | +| CE Death Island MP, 50 ms receive delay and 1% loss | 61 seconds, 122 player pairs, zero position error, maximum aim difference 8 degrees; 1,793 drift samples, none apart. No judge problems/divergences. | +| Xbox Blood Gulch MP | 61 seconds, 122 player pairs, maximum position difference 0.001 and aim difference 2 degrees; 1,830 drift samples, none apart. No judge problems/divergences. | + +The full Xbox `b30` trace retains one transient position/riding mismatch at a +transition; the strict judge reports no persistent divergence. It is not a +bit-exact or zero-transient-error claim. CE validation uses multiplayer maps, +as clarified by the user; an authored CE campaign is not a requirement. + +The Stock-menu Firefox host/native-client installed-content control at +`9f3be1501` passed real local-broker WebRTC, both normal skip votes and 49 seconds +of post-cinematic comparison: 98 player pairs, maximum position difference +0.012042 and aim difference 6 degrees; 993 drift samples, 68 apart, mean +0.00009916 and maximum 0.022914. The unchanged judge reports no problems or +divergences. Existing content is reused, with sharing/download off; this is not +a fresh-download test. A preceding transfer attempt was ended normally before +completion and remains unsuccessful. The exact final-code rerun `m15_ruby_browser_final` also passes: 49 paired +seconds, 98 player pairs, maximum position difference 0.041534 and aim difference +6 degrees; 1,328 drift samples, 40 apart, mean 0.00006588 and maximum 0.022913. +There are no judge problems, divergences or harness errors. Both skip votes, +real WebRTC, normal native exit, browser storage reopen audit and unchanged +original inputs are recorded. The combined artifact receipt binds the native +binary and browser site to `e818c391a1`. Native `b30`/CE/Xbox MP controls ran on +`206978e1e`; the final follow-up only rejects prohibited host-owned fields in +client predictions, with ordinary predictions covered by actual-source tests +and the final browser/native run. The earlier native Ruby skip run used +`9f3be1501`. These are local-broker tests, not public-NAT tests. + +An early-join Xbox `a10` natural-intro control encounters a +`structure_bsp_get_cluster_pvs` cluster-index assertion at a scene/BSP transition. +The retained pre-M15 **refactored-branch** binary reproduces the same assertion at the same transition +(`xbox_natural_baseline_v1` versus `xbox_natural_revert_v1`). Neither counts as +natural-completion coverage. The independent `b30` control supplies that check. +This establishes that the assertion predates Milestone 15, not that it predates +the refactor or our MCC support. Its root cause and introducing change remain +unproven. Milestone 16 owns the provenance investigation and any correction +required for a defect introduced by our work; its diagnostic was not suppressed. +This milestone does not claim complete campaigns, every map, +physical Android-device play or public-NAT coverage. + +#### Combined review, regression checks and preservation + +The final primary-agent review covers both MCC draw scopes, legacy neutrality, +shared pose ownership and bounds, protocol admission, fixtures and reader guides. +It found two additional real edge cases: untagged screen-effect fallback bitmaps +must retain native scale, and the shared prediction decoder must reject host-only +pose fields. Each was reproduced by a failing regression before correction. +Negative controls separately remove each authority guard and must fail. No new +framework, tag fingerprint or broader engine refactoring was justified. + +The final focused run passes **617 tests** covering MCC HUD layout, normalization, +view/mask ownership, wire/admission, pose codec and authority, checkpoint recovery, +elevator correction and CI wiring. The browser JavaScript suite passes 70 tests. +A broad Windows run records 4,296 passes, 653 failures and 21 skips; it is not +reported as green. Two missing CI registrations and fourteen stale elevator +fixture failures were corrected. Sandbox-dependent filesystem controls pass on +rerun (123 passes, two skips). The remaining broad failures come from Linux-only +harness assumptions on this Windows host. Linux CI supplies the supported run. +An initial Linux fixture compilation failure for missing `` was fixed; +no production-code change was needed for it. + +Final native and web builds succeed with the preserved native configure options. +[Final Build CI](https://github.com/chestahh/GulchCE/actions/runs/42534584182) +passes Windows, Linux, Android and web, including its browser checks. +[Final MCC CI](https://github.com/chestahh/GulchCE/actions/runs/42534584004) +passes reader/validator, Windows adapter and software-GL HUD jobs. Both are for +`e818c391a1`. Rendering captures use private observation builds; +network acceptance uses production builds. Versioned receipts distinguish these +and do not relabel earlier captures as executions of later binaries. + +The cleanup plan records original paths, sizes and SHA-256 values for every +owned target. A verified lossless archive preserves **3,248 files** (6,428,696,350 +uncompressed bytes) in `build/m15/inactive-evidence.zip` (**1,016,091,936 bytes**). +It retains inactive saves, browser profiles/exports, raw captures and the useful +pre-fix observation binaries. Every archive member was rehashed before removal +of its loose copy. Ten selected captures also remain as convenient lossless PNGs. +Another **100 verified disposable files**, totaling 4,688,577,006 logical bytes, +were removed: generated native map caches, fixture copies/hardlinks and temporary +observation-build outputs. This logical total is not an allocated-space claim. +Restored prior-milestone seed files were removed only after preservation/hash +checks; original maps, prior archives, active builds and toolchains remain. +No game or test Firefox process was active during cleanup. Exact target absence +and protected original hashes are rechecked. `cleanup-plan.json`, +`cleanup-result.json` and retained per-run receipts distinguish final cleanup +from the additional caches already removed after each native run. + +Milestone 15 is complete within these stated limits. The Xbox `a10` +BSP assertion is a Milestone 16 validation gate; no broader campaign or every-map +compatibility claim follows from these bounded checks. Milestone 16 remains +planned and has not begun. + +### Milestone 16: MCC-only upstream contribution + +#### Xbox a10 provenance and regression gate + +Before finalizing the upstream contribution, complete the Xbox `a10` +early-join co-op natural-intro investigation authorized by the user. The current +evidence proves only that the assertion exists before Milestone 15 on the +already-refactored branch. Do not label it an upstream or pre-refactor defect +without further evidence. + +1. Identify and record the exact commit immediately before Stage 1. Reproduce + the same scene/BSP transition there and on the completed refactored branch, + using identical original map hashes, comparable build options, settings, + input and join timing. Run each revision with matching peers; do not mix + incompatible network agreements or weaken admission to permit comparison. +2. Trace the invalid cluster index from its producer to + `structure_bsp_get_cluster_pvs`, including active BSP identity, unit/object + lifetime, host/client ordering and the first invalid state. Stale references + and transition ordering are hypotheses, not established causes. Check the + test fixture itself and distinguish a failed setup from game behavior. +3. Locate the introducing change through source history and controlled revision + comparisons. If the pre-refactor revision also fails, use an appropriate + pre-MCC or OpenCE baseline where necessary: predating the refactor alone + does not prove that our earlier MCC work is uninvolved. Record limitations + if historical builds or timing prevent a conclusive comparison. +4. If our MCC support or refactoring introduced the defect, correct its actual + producer/lifecycle contract in the responsible implementation. Add a failing + regression against the real implementation and demonstrate the corrected + transition. Preserve diagnostics and bounds checks; suppressing the assertion, + clamping the index or skipping visibility work is not a demonstrated fix. + Apply shared-engine versus MCC-owned boundaries according to the evidence. +5. Validate any correction across Xbox campaign transitions/recovery, CE + multiplayer and affected MCC maps, including host/client behavior and the + required native/browser transport and platform checks. Version changed + simulation or wire agreement and carry required fixes into the upstream + contribution. Keep unrelated fork-specific fixes out of that contribution. + +Completion requires either an evidence-backed correction of our defect with +passing affected checks, or evidence establishing an unrelated pre-existing +cause and an explicit disposition. An inconclusive baseline run does not close +the gate. Retain useful traces and failed outcomes, preserve original maps and +saves, and clean verified test outputs under the two-game limit. + +#### Upstream branch and protocol integration + +After Milestones 13–15, create `GET-YOUR-MCC-HERE` against the then-current +OpenCE `main`. The completed `mcc-code-refactor` branch is the source of the +contribution, including its MCC documentation and regression tests. Preserve +provenance and exclude unrelated fork features, settings, assets and integration +such as optional shoulder-camera mode. Preserve authored MCC camera semantics +required by the maps. Include shared fixes and browser foundations needed for +MCC correctness; distinguish any CE-only browser work as a separate upstream +dependency or contribution rather than silently expanding the MCC-only scope. + +Integrate MCC messages and admission into OpenCE's network agreement, removing +the separate MCC protocol/version layer while preserving map-family validation +and MCC-owned semantics. Audit message layouts, dispatch, identifiers, +simulation changes and old-peer refusal; changing a version constant alone is +insufficient. Use the then-current upstream network version plus one for the +combined agreement and account for any upstream movement before integration. +Revalidate the resulting branch across the required platforms and map families. +Keep reviewable commits and all meaningful tests/documentation; the complete +branch does not require presenting it as one oversized upstream PR. + +### Milestone 6: checksum consolidation + +Consolidated repeated CRC32 calculation and table construction in +[`mcc_checkpoint.c`](../port/linux/game/mcc_checkpoint.c), +[`mcc_script_threads.inl`](../port/linux/game/mcc_script_threads.inl), +[`mcc_resources.c`](../port/linux/game/mcc_resources.c) and +[`mcc_resource_check.inl`](../port/linux/game/mcc_resource_check.inl). +The existing `crc_checksum_buffer` in [`crc.c`](../source/memory/crc.c) was +evaluated; the already-linked port-prefixed zlib service was selected after +checking initialization, integer widths and standalone-tool linkage. + +Old/new and independent-oracle checks establish unchanged seeds, complements, +empty and chunked results, resource ordering/framing, checkpoint bytes and +failure behavior. Required platforms and consumers pass. The saved per-check +storage and isolated checksum timing are measured, with their practical limits +recorded in [Stage 6 evidence](#stage-6-checksum-consolidation). + +### Milestone 7: scripts and state lifecycle + +Review script resolution/execution, campaign and checkpoint restoration, +script-thread and named-object ownership, and failed-load/unload cleanup. +The relevant routes include `mcc_scripts`, `mcc_script_runtime.inl`, +`mcc_script_threads.inl`, `mcc_checkpoint`, `mcc_campaign` and +`mcc_object_names`. These are investigation areas, not established new defects +or promised deletions. Keep host/client authority and saved-state contracts +explicit when evaluating a change. +Stage 6 also retained a baseline assertion when a checkpoint captured a +sleeping temporary console expression. Investigate that expression's syntax +lifetime separately from CRC validity; the recorded standalone-save controls +pass. Stage 7 reproduced this on Xbox, CE and MCC and isolated a shared +syntax-lifetime defect. Its correction was deferred pending a shared +save/ownership design, then explicitly reopened alongside Milestone 11; +see [Stage 7 evidence](#stage-7-scripts-and-state-lifecycle). + +Complete when reviewed paths and ownership rules are recorded, demonstrated +defects/redundancy are addressed within scope, and affected save/revert, +restart, failure and unload behavior has been checked. Retain supported code +when no practical benefit from changing it is established. Any unresolved +semantic or compatibility question must have an explicit disposition and the +evidence needed to revisit it. + +### Milestone 8: compatibility exceptions and known gaps + +Review the 21 retained HUD structural profiles and other content selectors +encountered in the affected MCC paths. The immediate HUD question is whether +validated authored information or usage context can reliably distinguish +native and MCC safe margins. A replacement needs intended matches, near +misses and actual stock/custom HUD checks, including Ruby and Descent. +Record retained exceptions' rationale, activation/cleanup, regression evidence +and removal conditions; do not remove a profile merely to shorten the table. + +Separately diagnose Quarantine's `life_lost_0` refusal at `ai_deselect`. +Establish the operation's intended semantics and implementation boundary +before enabling it. A systemic MCC fix must benefit any map using those +semantics; accepting an unproven no-op or a map-specific bypass is insufficient. +Complete this milestone with validated fixes where justified and explicit +retention/deferral decisions where evidence or supported scope is insufficient. +An investigation completed with a deferral does not mean the defect is fixed. + +### Milestone 9: combined review and extended validation + +Review the resulting implementation across all stages, including code, tests, +integration and reader documentation. Reconcile the MCC boundary inventory in +`CODINGSTANDARDS.md` with the work actually reviewed: identify changed, +reviewed-and-retained, and unaudited/deferred areas. Further code changes need +their own demonstrated benefit and must receive affected regression checks. + +Extend representative Workshop checks with save/revert/restart, two-instance +co-op, repeated load/unload and failed-load recovery across map families. +Use Ruby's Rebalanced and other maps selected for the affected behavior, with +isolated saves and at most two hidden game instances. Compare loading cost +and memory retention under matched conditions; distinguish intended bounded +storage costs from leaks and do not infer speed gains from fewer lines. + +Complete when the final combined state has passed the applicable platform, +network and runtime checks, evidence and remaining limits are recorded, and +temporary outputs are cleaned. Full campaigns, live split-screen, Android +devices and browser-map gameplay remain unverified until specifically tested; +build success alone does not close those limits. This milestone prepares the +branch for delivery review; PR descriptions and merging remain separate. + +The combined review and planned runtime observations have completed. Platform +and representative runtime checks pass, but Ruby co-op recovery does not meet +the all-passing compatibility criterion above. It also fails on original main; +repairing the shared recovery path required a separate contract/version review +under the then-standing OpenCE-crossplay constraint. This exception is recorded, +not silently accepted or converted into a passing check. Final documentation +and cleanup are complete. Findings and coverage are recorded in +[Stage 9 evidence](#stage-9-combined-review-and-extended-validation). + +### Milestone 10: shared co-op checkpoint recovery + +Follow up the [Stage 9 recovery finding](#saves-restarts-and-co-op-findings): +after a team-wipe revert, Ruby B40's host has a living player unit while its +connected client lacks the corresponding player-unit binding. The failure +reproduces on original main and current in the OpenCE Crossplay profile. +The [Stage 10 investigation](#stage-10-shared-checkpoint-recovery-investigation) +now confirms that the client retains the same full handle as a dead object +while the host has restored its living version. This is shared-engine work arising from MCC validation; +it is separate from the explicitly deferred console-syntax lifetime defect. + +1. **Establish the cause.** Trace checkpoint restoration, authoritative object + descriptions, client object replacement and player attachment in + `network_coop`, `network_objects` and `network_distributed`. Capture object + identifiers, lifetime, inventory and player ownership across the failure. + Add a minimal regression exercising the real implementation and retain + Ruby as the runtime reproduction. Compare original and current behavior + without weakening the strict judge or discarding failed observations. +2. **Establish the recovery agreement.** Evaluate the recovery extensions behind + the GulchCE Third Person session profile as evidence, not a proven remedy. + Correct the responsible shared engine contract where demonstrated; preserve + Xbox/CE/MCC ownership and host authority. Validate object + descriptions before replacing client state. Correct supported behavior + must not require enabling a cosmetic feature. Review messages, simulation + agreement and required version separation before implementation. The user's + 7 November policy change permits excluding old peers; enforce that boundary + at discovery and admission. Do not add a map-specific bypass. +3. **Validate the resulting behavior.** Demonstrate failure before and recovery + after the fix, including actual player reattachment and restored inventory, + not only a successful load. Cover repeated team wipes and checkpoint + reverts, ordinary co-op, join/rejoin, map/session transitions and failed-load + cleanup, plus stale/malformed descriptions and unaffected live objects. + Use Ruby's Rebalanced, Mercury and representative Xbox/CE paths, + both host directions, and matching/mixed builds where their contracts + permit. Check the existing optional profile as well as the default profile. + Run affected regression suites, all required platform builds and native/web + transport checks. Validate claims of OpenCE crossplay against an identified + upstream executable on the map families/contracts it supports; a + main/current GulchCE pair alone is insufficient. + +Complete the repair only when its root cause and compatibility strategy are +established, the combined implementation is reviewed, and applicable checks +pass with evidence and cleanup recorded. An investigation ending in a +compatibility-dependent deferral leaves the repair milestone open and Ruby's +recovery sign-off withheld. Stage 9's historical failures remain recorded. +The policy change permits agreement separation; isolation, host authority, +meaningful validation and cleanup remain required. + +### Milestone 11: shared boat control initialization + +Use the [Stage 2 evidence](#stage-2-boat-proof-and-preserved-crossplay) and +[boat investigation](mcc_maps.md#shared-engine-investigation-7-november-2026) +as the starting proof. The three-point boat controller leaves two temporary +water-friction control values uninitialized; both physics paths can consume +them for accepted inputs. The bounded harness demonstrates non-finite forces +and incorrect finite friction with MCC inactive, and the existing MCC +initialization prevents both. This proves a shared producer defect, not that +stock Xbox maps contain affected boats or that full vehicle behavior is tested. + +1. **Establish the repair agreement.** Recheck the responsible engine + and simulation contract against the designated upstream revision. The + unconditional correction changes accepted Xbox/CE simulation, including + client prediction of a driven vehicle. Preserve host authority and document + the required agreement, version separation and rollout before implementation. + The user's 7 November policy change permits excluding incompatible old peers; + it does not establish compatibility with an unmodified upstream build. +2. **Correct the producer systemically.** Under the reviewed, version-separated + contract, initialize exactly the three temporary records in the existing + three-point branch, preserving its arithmetic, active controls and other + point-count paths. Retain required `port:` markers for shared source edits. + Preserve the working MCC correction; retire its helper/hook only when the + shared implementation demonstrably replaces it for every supported MCC + path. Do not select the fix by map identity, route legacy maps through MCC + code, or attach correct initialization to an optional camera/cosmetic mode. +3. **Validate behavior and agreement.** Preserve the existing regression + coverage and demonstrate failure before the fix and success afterward. + Check finite and non-finite stale controls, observable forces and resulting + motion in both physics paths, zero/reverse propeller values, scratch bounds, + unpowered controls, alternate point counts and unaffected controllers. + Exercise the Mercury2/Doozy reproduction and relevant installed Workshop + maps, plus Xbox/CE controls and supported-input fixtures where stock maps + lack boats. Test actual driving, client prediction and seat replication in + both host directions, with matching/mixed builds where their contracts + permit, and verify map-family transitions. Run affected regressions, all + required platform builds and native/web transport checks. Support crossplay + claims with an identified upstream executable on supported map contracts; + a main/current GulchCE comparison alone is insufficient. + +Complete the repair only after the new agreement and combined change +are reviewed, applicable checks pass, and evidence and cleanup are recorded. +Convert the twelve strict legacy expected failures to ordinary passing +regressions only when the authorized correction fixes those paths; preserve +their behavioral coverage and historical failures. A compatibility-dependent +deferral leaves this repair milestone open. This remains separate work after +Milestone 10. Implementation, validation and verified cleanup are complete; +the Stage 11 record below includes Mercury's subsequently authorized shared +clock correction and the console lifetime repair, with their actual limits. + +#### Former deferral: unconditional shared boat fix + +Stage 2 retained the MCC correction and twelve strict legacy expected failures +under the user's earlier crossplay requirement. That constraint was explicitly +lifted on 7 November for Milestone 11. Preserve this evidence and the working +MCC path until the separately validated shared correction replaces it. + +## Stage 1: validation baseline + +Stage 1 of `mcc-code-refactor` establishes repeatable checks before changing +engine or MCC compatibility behaviour. It changes test tooling, CI and this +documentation only. Xbox, Custom Edition and MCC implementations, simulation, +network version and map-family boundaries are unchanged. + +## Revision and build + +The baseline is main commit +`db1697c9b0c46289596f22213a5bef8ee327be24`, checked on 7 November 2026. +The isolated worktree is `build/mcc-code-refactor` under the original checkout; +all paths below are relative to that worktree. The original working tree was +left untouched. Do not reuse another checkout's executable as this baseline. + +The Windows build used clang 23.1.4, MSVC 14.44.35207 headers/libraries, Windows +SDK 10.0.26100.0, SDL 3.4.16 and these options: + +```powershell +python configure.py --portable --release --pgo=off --lto=off +ninja windows +``` + +The build completed all 1,007 steps. Existing Expat import warnings remain in +the log. `build/windows/halo.exe` SHA-256 is +`f1ec0dca876aa3cf746a4095ac9115cc026902f4679d1c3941deb20928c85d56`; +the adjacent SDL DLL is +`47d508b4232cf9462096bdb6f613a330d9a94a7eb09c305fad073430c6531920`. +These identify a baseline, not a reproducible-binary guarantee. + +## What the CI change makes executable + +[mcc.yml](../.github/workflows/mcc.yml) now explicitly runs the previously +unlisted avoidance, cameras, Chicago shader, damage-tag, environment-shader, +HUD-layout, movement, particle and seat tests on Linux and Windows. The +Windows job also runs its memory reservation and startup-order checks. +[test_mcc_ci.py](../tools/test_mcc_ci.py) checks that MCC test modules have +an executable CI route, including modules discovered through the harness +directory. It distinguishes a pytest module from a standalone Python runner. + +[test_mcc_hud_meter_render.py](../tools/test_mcc_hud_meter_render.py) must run +directly: passing it to pytest executes no GPU checks. Its separate Linux +job builds the project's checksum-pinned SDL version, then uses Xvfb and Mesa +software GL. The job needs clang, SDL3, NumPy, Pillow and SciPy. The shared +[HUD GL builder](../tools/test_hud_ammo_thresholds.py) now includes the +production shader emitters and missing renderer state needed by the current +translator, and preserves 32-bit colour words on an LP64 Linux host. + +Two existing harness problems were reproduced and corrected without changing +production code. The pause-menu harness's unused counters failed clang 23's +warnings-as-errors build; they now assert upload/deletion balance, restoration +and diagnostics. The Windows startup fixture assumed the loader would honour +a preferred DLL address despite ASLR policy. Its fake DLL now explicitly +claims an allocation in the MCC window. The test still checks early reservation, +deferred diagnostics and preservation of a conflicting allocation. + +## Run installed Workshop maps in place + +Use [mcc_native_smoke.py](../tools/mcc_native_smoke.py) on Windows. Supply a +disposable data folder containing a privately sourced Xbox `maps/ui.map`; +`maps/loading.tga` supplies the loading artwork when available. Keep installed +Workshop maps and resources in their Steam folders. No MCC map copy, junction +or alternate Python discovery implementation is needed. + +```powershell +python tools/mcc_native_smoke.py ` + --executable build/windows/halo.exe ` + --data-root build/stage1/data ` + --output build/stage1/workshop-final ` + --workshop --steam-root C:/Steam --campaigns --seconds 60 ` + 2915693904/a10 2962107814/a10 3021510694/mercury2 ` + 3675162225/halo 3003419983/spasm_playground ` + 3021510694/mercury_falling 3675162225/ring_mp +``` + +The engine resolves these virtual `mcc_maps//` names through its +normal Workshop discovery. `--steam-root` requires `--workshop`; omit it to +use the engine's normal Steam discovery. `--campaigns` enables campaign mission +discovery. Local `mcc_maps` invocation remains supported without these flags. +The tool accepts an optional `mcc_maps/` prefix and either slash convention. + +Each case gets a fresh save/log folder and records its effective `HALO_*` +settings, executable hash, elapsed time, exit status and cache cleanup result. +Inherited `HALO_*` overrides are cleared. The copied executable gets a fresh +configuration; rendering uses a hidden 640x480 window, with audio and internet +discovery disabled. `HALO_NULL_RENDERER` must be absent: its presence enables +the null renderer even when its value is `0`. Elapsed time includes loading +and the bounded wait; it is not a performance benchmark. + +`run_case` temporarily writes and restores the disposable data root's +`init.txt` through atomic replacement. If the file existed, its original bytes +are retained as `init.original.txt` in the case output for recovery if restoration +fails. A launcher error stops the remaining cases. Do not run two instances +against that data root or console port. +The runner refuses an occupied console port and reports console initialization +or socket-access failures. Before sending a script it checks Windows' TCP +connection table for the exact connection and launched process ID. A passing +result requires the expected loaded-map +log, an exact unique console output line after 150 simulation ticks, a normal +exit and no recognized fatal diagnostic. An echoed command is insufficient. + +Only generated regular `saves/z/cacheNNN.map` files inside the fresh case are +removed; linked directories/files are refused. Saves, configuration and useful +logs remain, while copied test executables/DLLs are removed. The caller must +archive inactive saves if necessary and remove its own disposable asset copies +when finished. Never delete original Workshop packages or player saves. + +## Reproduce the asset-free and optional fixture checks + +Use a Python environment with pytest, PyYAML and the prerequisites named by +the workflow. Initialise the x86 MSVC compiler environment on Windows. The +complete workflow commands are authoritative; a useful local MCC selection is: + +```powershell +$mccTests = Get-ChildItem tools/test_mcc_*.py | + Where-Object Name -ne test_mcc_hud_meter_render.py | + ForEach-Object FullName +python -m pytest -q -ra $mccTests tools/test_windows_mcc_startup.py ` + tools/test_steam_workshop.py tools/test_cache_file_formats.py +python -m pytest -q tools/harness/tests/test_mcc_boat.py ` + tools/harness/tests/test_mcc_damage.py tools/harness/tests/test_mcc_mods.py ` + tools/harness/tests/test_mcc_script_threads.py +python tools/test_mcc_hud_meter_render.py +python tools/test_hud_ammo_thresholds.py +``` + +Set `MCC_TEST_MAP` to a real Workshop level to opt into the cache/geometry +fixture checks. Set `HALO_CUSTOM_EDITION_MAPS` to a private CE directory for +the CE map/resource checks. These variables do not install or copy assets. +CI remains asset-free. Windows containment tests require permission to create +their temporary junctions or symlinks; keep those tests intact when a sandbox +prevents fixture creation. + +## Evidence and limits + +Private logs and results are retained in `build/stage1`; map assets and test +outputs are not committed. The initial broad run recorded 1,646 passes, +18 skips, 13 pause-harness compilation errors and one sandbox-denied junction +fixture. The unchanged preview containment test then passed with junction +creation permitted. The pause harness subsequently passed all 13 cases, +including its missing-unbind negative control. The added CI selection passed +149 checks. Optional Ruby cache/geometry and available CE map/resource checks +passed four checks; OpenSauce and the recorded CE Blood Gulch fixture were +absent. The four MCC modules under `tools/harness/tests` passed 45 checks. + +After the combined review, the full local MCC selection (excluding the smoke +runner, checked separately), Windows startup checks, the existing frontend +CI selection, Workshop/CE format tests and those four harness modules passed +1,813 checks with 18 skips. The skips comprise JDK absence, Linux-only +filesystem/sanitizer/fuzzer cases, and optional asset fixtures; four of the +asset checks were exercised separately as described above. +The reviewed smoke-runner regression suite passed 47 checks with one skipped +file-symlink case because Windows did not grant that privilege. Real directory +junction checks and the deterministic file-reparse guard both passed. + +The hidden GPU harness passed 36 MCC meter renders; the shared stock HUD +builder passed 15,360 ammunition renders. These compare output pixels for +their specified conditions, not full-map screenshots. The Windows machine +used NVIDIA OpenGL 4.5 on an RTX 5070 Ti. The new Linux Xvfb/Mesa job was +reviewed but had not run at local Stage 1 completion; its subsequent remote +result is recorded under Stage 2 below. + +The first sandboxed Workshop attempt loaded and rendered Ruby and Cursed, +but loopback connections failed with Windows error 10013. Neither run counted +as simulation success. The interrupted next case, failed results and cleanup +record are retained separately from the final runs. + +The final run used the command above with loopback access permitted. All seven +cases passed the loaded-map, delayed simulation output, diagnostic and normal +exit checks; each ran for the configured 60-second interval: + +| Package | Virtual level | Result | +| --- | --- | --- | +| Ruby | `2915693904/a10` | Passed | +| Cursed | `2962107814/a10` | Passed | +| Mercury | `3021510694/mercury2` | Passed | +| Tiny Halo | `3675162225/halo` | Passed | +| Spasm | `3003419983/spasm_playground` | Passed | +| Mercury | `3021510694/mercury_falling` | Passed | +| Tiny Halo | `3675162225/ring_mp` | Passed | + +The Mercury logs confirm package-owned bitmaps/sounds; both Tiny Halo cases +selected the installed shared singleplayer bitmap resource. Original Workshop +map hashes were unchanged after the runs. `baseline.json` records map, binary +and resource identities; `workshop-final/results.json` and the individual case +logs retain the checks and settings. The post-review smoke regression run +again passed 47 checks with the same one privilege-related skip. + +Cleanup removed 7,675,576,320 bytes of generated map-cache files across the +successful and interrupted attempts, the disposable Xbox UI copy and temporary +test fixtures. No generated map caches or copied test executables remain in +the run folders. Fifty inactive save/cache-support files (221,548,296 bytes) +were archived losslessly to `inactive-smoke-saves.zip` (2,160,738 bytes); archive +members were hash-verified before loose copies were removed, and original +paths/hashes are recorded in `inactive-smoke-saves.json`. The baseline build +and SDL/build inputs (about 229 MB), test environment (150 MB) and diagnostic +evidence including that archive (about 3 MB) remain for the next stage. + +Stage 1 establishes test execution and a bounded baseline. It does not prove +campaign completion, full visual/audio fidelity, save/revert, multiplayer +agreement, map-family transitions, performance improvements or Android/web +runtime compatibility. No simulation, protocol, engine or platform build +generator changed, so Android/web rebuilds and transport interoperability runs +were not required for these tooling changes. Later engine changes still need +their affected platform, networking and cross-family checks under +[AGENTS.md](../AGENTS.md) and [CODINGSTANDARDS.md](../CODINGSTANDARDS.md). + +## Stage 2: boat proof and preserved crossplay + +The [boat investigation](mcc_maps.md#shared-engine-investigation-7-november-2026) +establishes a shared producer-initialization defect. The user chose to preserve +the pinned OpenCE 41 crossplay contract and defer an unconditional engine fix. +This stage therefore changes regression coverage and documentation, with no +production or protocol change. The existing MCC correction remains active. + +The initial expanded test ran against unchanged production code and reported +eight failures with eighteen passes. Non-MCC NaN controls reached the real +force consumer; finite stale values produced incorrect friction. The finished +harness also exercises the actual radius-based dispatch and `physics_update_old`, +checking its resulting linear velocity. The newer path checks computed forces +before its separately stubbed integrator. Both use an axis-aligned fixture with +controlled transforms and world queries, not a real map or a whole game. + +The boat suite passed 52 checks and recorded twelve strict expected failures. +The latter are the identified legacy force defect, not successful compatibility +checks. Only its dedicated force-failure exception is eligible for an expected +failure; compilation, active-control and scratch-boundary errors remain failures. +Mutations verify that distinction. Removing the expected-failure handling for +the two legacy water/NaN cases reproduced failures in both physics paths. + +```powershell +python -m pytest -q -rx tools/harness/tests/test_mcc_boat.py +# Deliberately reproduces the two deferred failures: +python -m pytest -q --runxfail tools/harness/tests/test_mcc_boat.py -k legacy_nan_water +``` + +Eight additional cases remove the MCC guard only from an extracted temporary +test copy. They show that unconditional initialization corrects the measured +forces with either poison pattern and both physics paths. This is evidence for +the deferred change, not shipped behavior. Production still uses its original +MCC guard. No performance improvement or new runtime compatibility is claimed. + +The first remote Stage 1 run exposed a missing `libxtst-dev` dependency while +configuring SDL for the new Linux GPU job, before any render check ran. Commit +`4acb59d66` adds that dependency; the job retains SDL's enabled X11 functionality. +Workflow syntax and its 65 coverage checks passed locally. Remote results and +the post-review checks are recorded below. Private investigation logs are +retained under `build/stage2`. + +Self-review and an independent read-only review of the combined tests, +documentation and CI dependency repair found no remaining corrections. +The final local boat, neighboring MCC harness, protocol, camera-protocol and +CI-coverage selection passed 167 checks with the twelve documented expected +failures. Documentation checks verified 55 local links, the investigation +anchor, named functions and Python syntax, and confirmed that no production +file changed. No new game run was needed for these test/documentation changes; +Stage 1's unchanged binary and runtime evidence remain applicable within +their original limits. + +The original remote [Build run at `b8d2f0dc2`](https://github.com/chestahh/GulchCE/actions/runs/42373756516) +passed Windows, Linux, Android and web debug builds. Android included its APK +and importer checks; web included the browser/native transport harness. +The [MCC run](https://github.com/chestahh/GulchCE/actions/runs/42373756545) +passed its Linux/Windows pytest jobs but failed SDL configuration in the new +GPU job as described above. + +The subsequent [Build run at `24fc89cdd`](https://github.com/chestahh/GulchCE/actions/runs/42374909776) +passed all four platform jobs with the expanded boat coverage. These are debug +builds; this workflow builds releases only on main. Android compiled the guest +and host, built its APK and passed the importer checks. Web passed its build +and browser/native transport checks with Chromium and Firefox, including the +configured packet-loss cases. These transport fixtures do not exercise a real +map or establish crossplay gameplay compatibility. + +Linux's combined regression invocation passed 2,478 checks with 27 skips, +twelve expected failures and seven passing subtests. Across its pytest +invocations the job recorded 2,794 passes, 52 skips and the same twelve expected +failures; its ordinary and full-LTO ELF light-storage checks also passed. +The expected failures are the explicitly deferred boat defect described above. +Skips are retained as skips, including checks requiring unavailable retail +assets; they are not evidence of gameplay coverage. + +The corresponding [MCC run](https://github.com/chestahh/GulchCE/actions/runs/42374909804) +passed all three jobs: Linux readers/validators, Windows adapters and Linux +GPU rendering. The corrected GPU job built the pinned SDL version with X11 +enabled and passed all 36 meter render checks under Xvfb/Mesa. The Linux +reader/validator job passed 1,615 checks with sixteen skips; its separate +ASan/UBSan invocation passed 38 checks. + +These results validate code and test revision +`24fc89cdd46761f010d81a41f16ad5ba6170487e`. The following documentation-only +commit records the completed runs; it does not change that implementation. +No production source or protocol changed in either stage. The twelve deferred +legacy boat failures remain unresolved, and the Stage 1 runtime limits still +apply. No Android-device gameplay, browser-map gameplay, full campaign, +save/revert or new map-family transition result is claimed. + +Stage 2 launched no game instances and created no map copies or saves. +Temporary harness binaries and pytest fixtures/cache were removed after +checking their resolved paths and rejecting links. About 1.9 MB of diagnostic +logs and supporting evidence remain under `build/stage2`; no generated game +caches or test executables remain there. The Stage 1 build, environment and +verified save archive remain available as described above. + +## Stage 3: resource ordering and bitmap ownership lookup + +This stage removes two demonstrated sources of unnecessary work within +MCC-owned code. It changes no format interpretation, map-family dispatch, +simulation, network version, content-identity framing or resource lifetime. + +`mcc_resource_open` no longer sorts its private directory by byte offset. +Every consumer finds entries by name and checks the whole directory for +duplicates; none depends on offset order. The comparator and sort call were +removed, while all bounds, duplicate-name and grouped-slice checks remain. +The expanded resource suite passed 117 checks before and after the change. +Compiled old/new readers also returned identical payloads, CRC32 and SHA256 +for four fixed-input comparisons covering bitmap/sound files and both directory +orders. Different on-disk directory orders still have distinct raw identities; +only the unused in-memory reordering was removed. + +`mcc_bitmap_valid_texture` now returns the owned, validated texture to both +`mcc_bitmaps_valid` and `mcc_bitmaps_pixels`. A successful pixels request no +longer searches the table twice. Validation order, first-match behavior, +failure-output clearing, descriptor identity, handles, ranges, channel flags +and storage checks remain intact. No lookup cache or new persistent state was +added. The ownership fixture checks both public entry points, copied/foreign +and mutated descriptors, missing storage, unchanged descriptor bytes, verifier +short-circuiting, duplicate entries, pressure beyond the legacy cache budget +and disposal. The media/flags/bridge selection passed 59 checks. + +In isolated extracted old/new routines, the same 39 successful bindings over +13 descriptors required 546 pointer comparisons before and 273 after; returned +allocations, sizes and sampled pixel bytes matched. This measures removed +traversals, not frame rate or map-loading speed. The separate per-conversion +stream-offset scan and content-specific HUD exceptions were not changed. + +Private evidence is retained under `build/stage3`. The original Stage 1 Windows +executable was preserved at `build/stage3/baseline/halo.exe` before rebuilding +`build/windows/halo.exe`; its recorded SHA-256 remains unchanged. Runtime +checks use installed Workshop maps directly and isolated Xbox/CE fixture +copies, saves and logs. Final review, build and runtime results follow below. + +Self-review and an independent read-only review covered all Stage 3 code, +callers, lifecycle paths, tests and documentation; no further correction was +needed. After that review, the broad local MCC, Workshop, CE-format, protocol +and neighboring MCC harness selection passed 1,909 checks with nineteen skips +and the twelve previously documented boat expected failures. Skips covered +the JDK missing from this shell's PATH, Linux-specific checks, file-symlink +privilege and optional map fixtures. Four optional checks were then run with +Ruby's Workshop `a10` and the available CE Death Island/resources; all passed. +The Windows release build succeeded with the original configure options; +the existing Expat import warnings remained. Its executable SHA-256 is +`7608089e8b1c003ba7ff15c3120392d07342af473f93a50b3471e0f60e330c3d`. +The direct GPU runners passed 36 MCC meter cases and 15,360 stock HUD ammunition +cases on the local NVIDIA renderer. + +The baseline and updated executables each completed this sequence in one +hidden 640x480 process, with fresh saves and actual rendering: + +1. Workshop `3021510694/mercury_falling`, selecting package-owned resources. +2. Xbox `levels/test/bloodgulch/bloodgulch`. +3. Custom Edition `custom_maps/deathisland`. +4. A disposable, header-valid MCC fixture with an invalid tag index; the + loader refused it and returned to the menu. +5. Workshop `2915693904/a10`, restoring MCC operation after the failed load. + Ruby's log reports no external resource selection in this run. + +Each valid map required a fresh simulation-tick epoch, an exact console marker +after 150 simulation ticks, and a subsequent rendered capture. Both processes +exited normally with no fatal diagnostic. Before/after captures were visually +inspected: the MCC intros and Xbox/CE gameplay rendered their expected scenes +and textures. They are not frame-synchronized image-equivalence tests; moving +cinematics and unique console markers differ. The malformed fixture tests early +load recovery before resource allocation, not every possible allocation failure. +These runs establish the named transitions and bounded rendering/simulation, +not campaign completion or new multiplayer, save/revert or device compatibility. + +An additional 45-second hidden Tiny Halo run (`3675162225/halo`) passed the +loaded-map, delayed simulation marker, diagnostic and normal-exit checks. Its +log explicitly selects `mcc_maps/_shared/singleplayer/bitmaps.map`, covering +the installed shared-resource path separately from Mercury's package resources +and Ruby's recovery run. + +Input verification rehashed all six original Xbox/CE fixture files and their +copies, the three exercised Workshop maps, Mercury's bitmap/sound resources +and the installed shared singleplayer bitmap resource; all hashes matched. +The three game runs removed 2,302,672,896 bytes of generated map caches. +Temporary test binaries, fixture directories and asset copies were removed. +The 107 inactive save/support/capture files (98,548,658 bytes) were archived +losslessly to `build/stage3/inactive-runtime-evidence.zip` (7,455,474 bytes). +Every member was hash-verified before removing its loose copy; the adjacent +JSON manifest records original paths, sizes and hashes. The baseline executable +and SDL DLL (about 27 MB) remain for later refactor comparisons, alongside the +current Windows build, test environment and diagnostic evidence. + +The [MCC workflow at `829ef117b`](https://github.com/chestahh/GulchCE/actions/runs/42377561461) +passed all three jobs. Its Linux reader/validator selection passed 1,652 checks +with sixteen skips, followed by 38 passing ASan/UBSan checks; the Windows job +passed 1,853 checks with seventeen skips across its invocations. The direct +Xvfb/Mesa job passed all 36 MCC meter renders. + +In the corresponding [Build workflow](https://github.com/chestahh/GulchCE/actions/runs/42377561452), +all four debug platform builds passed. Branch builds do not run the main-only +release job; the local Windows release build is recorded above. Android built +its guest/host and APK and passed touch, gyro and importer checks. Web passed +its JS/browser and native transport assertions for Chromium and Firefox, including configured packet +loss. These remain asset-free transport checks, not multiplayer gameplay +qualification. Linux's combined invocation passed 2,478 checks with 27 skips, +twelve expected failures and seven passing subtests. Across its pytest +invocations it recorded 2,794 passes, 52 skips and the same twelve expected +failures; ordinary and full-LTO ELF light-storage checks also passed. The +expected failures remain the deliberately deferred Stage 2 boat defect. + +Both workflows validated implementation revision +`829ef117b945152dcffd61d9bba9994efcec5b66`. The following documentation-only +commit records their completed results and cleanup. Final documentation review +checked the claims against logs and archive metadata; local-link, named-symbol, +Python-syntax and whitespace checks passed. Roughly 36 MB remains under +`build/stage3`, including the 27 MB baseline build and 7.5 MB verified archive. +No disposable map copies, game caches or temporary test binaries remain there. + +## Stage 4: per-tag bitmap stream preparation + +This stage simplifies MCC-owned conversion bookkeeping. It does not change +pixel decoding, format interpretation, shader selection, simulation, network +version or Xbox/Custom Edition implementations. The old private converter +scanned every texture entry to recover the next stream offset for each texture. +Preparation now passes a local cursor to `mcc_texture_prepare`, resets it when +the full runtime handle changes, and advances it only after success. + +The ordering contract is established by the actual constructors: validated +original handles have unique tag indices, `mcc_bitmaps_prepare` appends each +original bitmap block contiguously, and `mcc_bitmap_specialize` appends each +clone block under a fresh handle. Reusing a clone appends nothing. Empty blocks +add no descriptors. The items are not reordered before conversion. A resource +handle is not a runtime handle: clones can share the former while owning +separate streams. No persistent index, extra allocation or new shared-engine +hook is needed. Existing per-allocation, per-tag and aggregate bounds, failure +publication, loading progress and disposal remain unchanged. + +The expanded extracted-source fixture exercises the actual preparation, +tag/block and clone constructors, with controlled consumer selection. It covers +multiple descriptors and original tags, both clone creation orders, clone +reuse, empty groups, exact stream boundaries, aggregate storage, and failures +in allocation, internal reads, external-resource reads and packing. Failed +descriptors remain unpublished; disposal releases earlier successful textures. +The same contracts were first checked against unchanged Stage 3 production +code. Private evidence and baseline executables are under `build/stage4`. + +All 45 converter cases passed before and after. The construction cases also +produced identical full descriptor/pixel traces, read counts and storage ends. +Two deliberately broken private variants failed the expected offset assertion: +using resource handles for boundaries, and omitting cursor advancement. The +focused converter/media/channel/bridge selection passed 72 checks. Self-review +and an independent combined review found no remaining production cleanup or +structural correction justified within this stage. + +Private Windows release probes were built from Stage 3 revision `53fe6673b` +and the updated bitmap module, replacing only that translation unit. Their +999 shared response-file inputs, configure options and probe framing matched. After +successful conversion, the probe hashes every initialized pixel-allocation byte +and 21 explicitly framed semantic metadata fields for every texture, excluding +addresses and structure padding. It also records ordered handle groups, total +storage and the maximum per-tag stream end. The comparator verifies complete +records, identities, counters and digests before comparing them. Instrumented +timings are not used to claim a loading-speed improvement. + +All seven paired Workshop runs matched every recorded texture, handle group +and stable summary field: + +| Installed Workshop map | Textures | Clones | Converted bytes | Old table visits | New cursor advances | +| --- | ---: | ---: | ---: | ---: | ---: | +| Ruby's Rebalanced `2915693904/a10` | 1,275 | 10 | 107,505,536 | 1,625,625 | 1,275 | +| Ruby's Rebalanced `2915693904/b40` | 1,181 | 11 | 115,751,552 | 1,394,761 | 1,181 | +| Ruby's Rebalanced `2915693904/d40` | 1,444 | 11 | 150,436,608 | 2,085,136 | 1,444 | +| Cursed `2962107814/a10` | 1,531 | 29 | 265,864,960 | 2,343,961 | 1,531 | +| Spasm `3003419983/spasm_playground` | 908 | 12 | 200,100,480 | 824,464 | 908 | +| Mercury `3021510694/mercury2` | 1,577 | 47 | 606,337,280 | 2,486,929 | 1,577 | +| Tiny Halo `3675162225/halo` | 846 | 9 | 138,963,328 | 715,716 | 846 | + +Together these compare 8,762 textures, 129 clones and 1,584,959,744 converted +bytes. The removed scans made 11,476,592 table visits; the cursor advanced +8,762 times. All fourteen hidden processes used the real NVIDIA renderer, +required a fresh simulation-tick epoch and exact console output after 150 +ticks, captured a subsequent rendered frame, and exited normally. The complete +native smoke failure-pattern scan passed for all log/console sinks. Before/after +captures were visually inspected and showed the same expected scenes and +textures; these are not synchronized image-equivalence tests. Ruby's runs are +opening cinematics, while Spasm reaches its initial gameplay view. Installed +Workshop maps were read in place, without package copies. + +After combined review, the broad local MCC, Workshop, CE-format, protocol and +neighboring harness selection passed 1,920 checks with nineteen skips and the +same twelve deferred boat expected failures. The skips retain their earlier +meaning: unavailable JDK/symlink privileges, Linux-only checks and optional +assets. Four optional real-map checks then passed with Ruby's `a10` and the +isolated CE fixtures. Direct GPU checks passed 36 MCC meter cases and 15,360 +stock ammunition cases. The Windows release build succeeded with the unchanged +`--portable --release --pgo=off --lto=off` configuration and existing Expat import +warnings. Its executable SHA-256 is +`2f22adeba256b26843cfb8375c55c26d95535ea47491d172b5aab85874edf52b`. + +The uninstrumented baseline and updated release executables each passed the +same one-process sequence: Mercury Falling with package resources, Xbox Blood +Gulch, CE Death Island, the intentionally invalid MCC tag-index fixture, then +Ruby's `a10`. Every valid map required a fresh tick epoch, delayed console +marker and rendered capture; both processes exited normally. This confirms +early failed-load recovery and the named family transitions. The malformed +fixture does not exercise late allocation failure; the extracted-source +failure cases cover conversion publication/disposal separately. + +Both uninstrumented executables also ran Ruby's `b40` long enough to leave +the opening cinematic and render the initial gameplay area, including its +HUD, weapon and environment. Each completed the console marker after 1,800 +simulation ticks, saved a later frame and exited normally. Before/after +captures were visually reviewed. All eighteen game runs passed the complete +native smoke diagnostic scan, allowing only the deliberately requested +`refactor_invalid` refusal in the two transition runs. No protocol version or +simulation code changed; network version 41 and the deferred boat behavior +remain intact. These are bounded runtime checks, not full-campaign, new +multiplayer gameplay, save/revert, Android-device or browser-map qualification. + +All six original Xbox/CE fixture files and their copies, the eight exercised +Workshop maps, Mercury's bitmap/sound resources and the installed shared +singleplayer bitmap resource were rehashed and unchanged. Each game run cleaned +its generated map caches: 13,816,037,376 bytes across eighteen sequential runs. +The 254 inactive save/support/capture files (516,681,213 bytes) were archived +losslessly to `build/stage4/inactive-runtime-evidence.zip` (23,450,825 bytes). +Every member was hash-verified before removing loose copies; the adjacent JSON +manifest records their original paths. Private probe executables, objects and +debug symbols, disposable asset copies and pytest fixtures were removed after +checking containment and rejecting links. The Stage 3 baseline executable/SDL +pair remains for comparison, alongside the current release build and useful +logs, reproducible proof sources and archive. + +The [MCC workflow](https://github.com/chestahh/GulchCE/actions/runs/42380303410) +passed all three jobs at implementation revision +`e670a18926acc4d69e574a6172f4d3e2ddd2bd62`. Linux readers/validators passed 1,663 +checks with sixteen skips, followed by 38 passing ASan/UBSan preview checks. +Windows adapters passed 1,864 checks with seventeen skips across their +invocations. The Linux Xvfb/Mesa job passed all 36 MCC meter renders. + +The corresponding [Build workflow](https://github.com/chestahh/GulchCE/actions/runs/42380303636) +passed all four debug platform builds; the main-only release job was skipped. +The local Windows release result is recorded above. Linux's combined invocation +passed 2,478 checks with 27 skips, twelve expected failures and seven passing +subtests. Across its pytest invocations, it recorded 2,794 passes, 52 skips and +the same expected failures and subtests; ordinary and full-LTO ELF light-storage +checks passed. Windows COFF light-storage and corruption-negative checks passed. +Android built its guest/host and APK and passed touch, gyro and MCC importer +checks. Web passed its JS/browser checks and native Chromium/Firefox transport +assertions, including configured packet loss. These remain asset-free transport +tests, not multiplayer gameplay qualification. + +Final evidence review checked the combined Stage 4 claims against the retained +logs, manifests and archive. Local-link, named-symbol, Python-syntax and +whitespace checks passed. This documentation-only completion records CI for the +implementation revision above without changing its code or tests. About 60 MB +remains under `build/stage4`, primarily the 27 MB baseline build, 23.5 MB verified +archive and diagnostic logs. No disposable map copies, generated game caches +or temporary test/probe binaries remain there. + +## Stage 5: HUD ownership and identity-independent normalization + +Stage 5 starts at `a9aaa8b3ae70c7d0ac7490f0c5c181d45e663eae`. The preserved +Windows release baseline has the Stage 4 executable hash above. This stage +corrects an MCC compatibility-engine defect: supported interned HUD storage +was normalized in place for each consumer, so earlier writes could become +later consumers' input. Same-group root aliases could halve offsets, scales, +digit advances or margins twice. Shared item storage could also inherit the +wrong bitmap factor or frame marker. These are ownership errors, independent +of map names, Workshop IDs or checksums. + +`mcc_hud_ownership.inl` plans from pristine data, identifies root aliases and +isolates mutable block consumers before normalization. Pointer-free overlay +and crosshair items receive snapshots even when no second HUD reference is +visible: their storage can be interned inside a different tag allocation. +This intentionally makes supported scalar interning independent of validator +traversal order. It does not preserve the old order-dependent rejection of +otherwise supported scalar storage. The actual-validator regression cases +retain rejection of conflicting pointer-bearing/root owners and partial +overlaps. For shared pointer-bearing prefixes, the largest original extent +remains reachable so a copy cannot hide a conflicting tail. + +All snapshots finish before pointer publication. Temporary planning storage +is freed on success and failure; copies use the existing MCC runtime arena +and its normal teardown. The four-million-record budget is checked before +layout recognition; bitmap geometry walks retain their existing range checks. +No new shared-engine hook, persistent state, setting or network-version +change is involved. Xbox and Custom Edition loading and normalization remain +unchanged, as does the explicitly deferred shared boat fix. + +The first whole-converter reproduction used production structures and source +with synthetic tag storage. Unchanged Stage 4 code failed 30 of 45 cases; +fifteen independent-storage controls passed. A separate fixture combines the +actual converter and actual MCC validator. Its baseline failed five cases: +scalar-first admission, scalar-last source corruption, repeated root conversion +and both shared-prefix orders. Eight controls passed. Replacing largest-owner +retention with shortest-owner retention in a private mutation made both +conflicting-tail tests fail, showing that these negative cases detect hidden +overlaps. No original map file was modified for these reproductions. + +An inventory read ten installed Workshop maps in place: Ruby's Rebalanced +`2915693904/a10`, `b40` and `d40`; Mercury `3021510694/mercury2` and +`mercury_falling`; Cursed `2962107814/a10`; Tiny Halo `3675162225/halo`; Spasm +`3003419983/spasm_playground`; Descent `3042265379/firefight_descent_mcc`; and +Descent Quarantine `2963835242/firefight_descent_quarantine_mcc`. None contained +shared roots or placement blocks within the inspected HUD graph. The inventory +did not compare scalar addresses against every non-HUD allocation. These maps +are unchanged-behavior controls, not claimed reproductions of the +ownership bug. BioHalo was not found in the inspected `C:\Steam` library and +was not runtime-tested. + +The inventory contains 487 component HUDs, including 92 unit HUDs: 71 recognized +and 21 unrecognized unit layouts. All eleven existing unit profiles were +represented. Removing bitmap names from recognition preserved all 487 original +classifications and introduced no recognized/unrecognized class collision in +this sample. Private production-C visitor checks passed 100 cases comparing +3,896 component records, including name-only changes, placement and bitmap +registration near misses, and unterminated names. Names remain bounds-checked. +The ten weapon/grenade profiles were already independent of bitmap names. + +The 21 structural profiles remain a documented compatibility exception. +Supported anchors and scale flags do not establish the author's intended safe +frame; the unused canvas field supplies no demonstrated replacement rule. +Unknown layouts therefore retain the authored MCC frame. Replacing these +profiles requires evidence distinguishing stock and custom margins, including +near misses. This stage removes an irrelevant identity dependency without +claiming that every pre-existing exception is now eliminated or necessary. + +Layout recognition now reads each distinct pristine root once. Conversion +writes frame markers alongside the corresponding placement changes, removing +the repeated geometry/name walk previously used to stamp recognized layouts. +The later `mcc_tags.c` placement pass was also redundant: successful HUD +conversion had already consumed every high-resolution placement flag it +tested. A private comparison of the actual old and trimmed metadata functions +restored the same arena before each call and matched every byte and return +value across 56 cases. The retained pass still clears unsupported meter +overlay metadata and checks the affected roots and meter blocks. +The ten-map inventory requires 798 scalar block copies containing 935 items, +104,732 bytes in total before arena alignment. This small added storage buys +correct consumer ownership; no loading-time or peak-memory improvement is +claimed. Private sources, inventories, reproduction logs and build manifests +are retained under `build/stage5`. + +The first updated native probe exposed a fixture gap: `cseries.h` maps `free` +to `debug_free`, whose contract rejects NULL. The planner's initial nullable +free crashed before probe output. The batch stopped and its useful evidence +was retained. Nullable releases are now guarded. Both converter fixtures +enforce the engine's non-NULL free contract; the normalization fixture also +fills allocations with `0xCA` and enforces the allocator's individual size +limit. A strict private fixture fails the original planner and passes the +correction, including bitmaps-only input and every injected planning-allocation +failure. Final focused checks pass 579 cases, including 70 whole-normalization +cases and 132 validator cases. Independent re-review checked the correction, +remaining allocation bounds, ownership lifecycle, metadata trim, tests and +documentation before the final combined checks. + +The final local MCC, Workshop, CE-format, protocol and neighboring harness +selection passed 2,004 tests, with nineteen skips and the same twelve deferred +boat expected failures. Skips cover unavailable JDK/symlink privileges, +Linux-only checks and optional assets. Four optional real-map checks then +passed using Ruby's `a10` and isolated CE fixtures. Direct GPU checks passed +36 MCC meter renders and 15,360 stock ammunition renders. Documentation checks +validated 136 local links, named routes and changed Python syntax; production +changes are confined to the four MCC HUD/metadata files. + +The Windows release build passed with unchanged +`--portable --release --pgo=off --lto=off` options and the existing Expat import +warnings. Its executable SHA-256 is +`3e563cd2291cb72196350e68dac471f6f5b96799164177f4ecf9309dd647893a`. + +Private Windows release probes compare the Stage 4 HUD module with the final +Stage 5 HUD module. Their 999 other link inputs match exactly, including the +old metadata object; the separate 56-case metadata proof and final +uninstrumented build cover that trim. Probe includes are copied privately and +hashed. The observer runs only after successful HUD conversion, reads without +allocating or mutating game state, and records selected normalized HUD fields +in a stable order rather than addresses or all tag data. Its comparator checks record framing, per-tag/aggregate +digests, inventory coverage, executable identity, runtime settings, capture +dimensions and all native smoke failure patterns across four log sinks. + +All ten pairs match every recorded normalized field and stable summary: + +| Workshop map | Records | Placements | Added arena bytes | +| --- | ---: | ---: | ---: | +| Ruby `2915693904/a10` | 847 | 180 | 6,832 | +| Ruby `2915693904/b40` | 909 | 228 | 7,504 | +| Ruby `2915693904/d40` | 1,019 | 221 | 7,616 | +| Cursed `2962107814/a10` | 1,273 | 325 | 16,128 | +| Quarantine `2963835242/firefight_descent_quarantine_mcc` | 983 | 169 | 7,520 | +| Spasm `3003419983/spasm_playground` | 1,188 | 508 | 22,768 | +| Mercury `3021510694/mercury2` | 1,425 | 324 | 12,992 | +| Mercury `3021510694/mercury_falling` | 1,003 | 204 | 7,152 | +| Descent `3042265379/firefight_descent_mcc` | 1,593 | 340 | 13,664 | +| Tiny Halo `3675162225/halo` | 730 | 149 | 6,128 | + +Together these cover 10,970 records and 2,648 placements. The 108,304-byte +arena increase includes scalar-copy alignment. These are allocation sizes, +not measured peak-memory or loading-time improvements. All twenty hidden +processes advanced through a delayed 150-tick console expression, captured a +subsequent frame through the real NVIDIA renderer and exited normally. +Before/after captures were visually inspected; most short runs show opening +cinematics, Spasm shows gameplay, and Descent's short capture is still black. +They are not synchronized pixel-equivalence tests or complete HUD gameplay +qualification. + +Nine map pairs pass the full diagnostic scan. Quarantine has the same +pre-existing refusal in both builds: +`mcc: script validation refused life_lost_0 (ai_deselect); 1 scripts won't run, 0 globals start at their defaults`. +Its normalized-output comparison passes, but its runtime is explicitly +script-limited, not a clean smoke pass. The comparator requires the exact +diagnostic and occurrence list to match and rejects additional failures. +This unrelated script-compatibility gap was not changed or hidden. + +The final uninstrumented release and preserved baseline each passed the same +one-process sequence: Mercury Falling with its package resources, Xbox Blood +Gulch, CE Death Island, the deliberately invalid MCC tag-index fixture, then +Ruby's `a10`. Every valid phase required a fresh tick epoch, delayed console +output and a subsequent rendered capture. Both processes exited normally. +This verifies the named family transitions and early failed-load recovery; +synthetic allocation failures cover later conversion cleanup separately. + +Both builds also ran Ruby's `b40` at 640-by-480 with High-Res HUD enabled and +1280-by-720 with it disabled, and Descent at 1280-by-720 with it enabled. Each +completed a console expression after 1,800 simulation ticks and captured later +gameplay, including the HUD, weapon and environment. Visual review found the +expected placement, scale and custom layout preserved. Timing-dependent +animation, camera and flashing meter differences are not pixel comparisons. +The eight paired uninstrumented runs and one exploratory baseline Descent run +passed an independent full diagnostic scan, executable/settings checks and +capture/simulation checks. Only the exact requested invalid-map refusal is +allowed in transition logs. + +No original map files, network fields, simulation logic or map-family boundaries +changed. Network version 41 and the deferred boat behavior remain intact. +These results do not establish full-campaign, save/revert, multiplayer gameplay, +local split-screen, Android-device or browser-map compatibility. Existing +asset-free layout checks cover split-screen geometry; no new live split-screen +session was run. + +The [MCC workflow](https://github.com/chestahh/GulchCE/actions/runs/42385944116) +passed all three jobs at implementation revision +`809f8b8cdb9ba3dd9e5727cc261e8f3043eba931`. Linux readers/validators passed +1,747 checks with sixteen skips, followed by 38 passing ASan/UBSan preview +checks. Windows adapters passed 1,948 checks with seventeen skips across their +invocations. The Xvfb/Mesa job passed all 36 MCC meter renders. + +The corresponding [Build workflow](https://github.com/chestahh/GulchCE/actions/runs/42385944018) +passed all four debug platform builds. The main-only release job was skipped; +the local Windows release result is recorded above. Linux's main invocation +passed 2,478 checks with 27 skips, twelve expected failures and seven passing +subtests; its pytest invocations totalled 2,794 passes and 52 skips, with the +same expected failures and subtests. Ordinary and full-LTO ELF light-storage +checks passed. Windows COFF light-storage and corruption-negative checks +passed. Android built the guest/host and debug APK and passed touch, gyro and +MCC importer checks. Web passed its page/browser checks and native +Chromium/Firefox WebRTC assertions, including configured packet loss. These +transport checks do not constitute map-based multiplayer qualification. + +All six original Xbox/CE fixture files and their copies, ten Workshop maps, +Mercury bitmap/sound resources and the installed shared singleplayer bitmap +resource were rehashed and unchanged. Thirty sequential process attempts +included the one diagnosed allocator crash and 29 normal exits; generated +map caches were removed after every attempt, totalling 23,026,728,960 bytes. +The 375 inactive save/support/capture files, including the failed attempt's +useful evidence, totalled 942,965,724 bytes. They were archived losslessly to +`build/stage5/inactive-runtime-evidence.zip` (66,518,323 bytes). Every archive +member was hash-verified before loose copies were removed; the adjacent +manifest records original paths and hashes. + +Verified disposable fixture copies, pytest outputs and private probe binaries, +objects and debug symbols were removed without following links. About 108 MB +remains under `build/stage5`, primarily the 66.5 MB archive, 27 MB preserved +baseline build, inventories and diagnostic evidence. The final release build +remains usable under `build/windows`. No disposable map copies, generated game +caches or temporary test/probe binaries remain under this stage. + +Final evidence review checked the combined implementation, preserved caller +boundaries, ownership/failure paths, tests, CI and documentation. It corrected +the allocator-contract gap, removed the demonstrated redundant work, and found +no further justified structural change within this stage. Local links, named +symbols, Python syntax and whitespace checks passed. This documentation-only +completion records results for the implementation revision above; it changes +no production code or tests. + +## Stage 6: checksum consolidation + +### Boundary and exact compatibility contract + +The baseline is `18c01ec34`, with Windows release executable SHA-256 +`3e563cd2291cb72196350e68dac471f6f5b96799164177f4ecf9309dd647893a`. +The initial checkpoint, resource, saved-game, identity, precache, protocol and +script-thread selection passed all 213 tests before implementation. + +The four MCC consumers implement the same reflected CRC32 polynomial +(`0xedb88320`). Checkpoint and thread blocks begin with an all-one internal +seed and complement the result. Resource checks begin with the complemented +stored map checksum and append selected bitmap then sound resources, each +framed by its one-byte type and a `0xff` terminator. Only the published zero +is changed to one. SHA-256 separately hashes the map and selected resources +with length/type framing; it is not replaced by CRC. + +Design review rejected a direct use of `source/memory/crc.c`: its +`unsigned long *` interface does not match portable `uint32_t` storage on +LP64 standalone readers, and its lazy mutable table would introduce an +initialization dependency. The existing port-prefixed zlib CRC is already +linked by Windows, Linux, Android and web. Their build configuration uses +its static tables; Android includes the implementation in the ILP32 guest +without adding host imports. Explicit relative header includes select this +port library rather than the separate original game zlib. No vendored code, +shared engine implementation or build graph needs modification. + +The MCC callers use zlib's finalized CRC convention: seed zero for saved +blocks, the map checksum for resource chaining, and no extra complement. +Resource framing bytes remain explicit unsigned bytes. Bounds, selected +resources, file errors, loading pulses, incremental work budgets and SHA +framing retain their existing paths. There is no new mutable checksum state +to initialize or dispose. This is content-independent MCC code maintenance; +no map identities or compatibility exceptions select the change. + +### Implementation review and local evidence + +Review covered the four consumers, their callers, standalone linkage, test +oracles and reader documentation. The prefixed header must follow `cseries.h` +in the resource translation unit: the first release build caught a collision +between C-library limits macros and the engine's enum names. Correcting that +include order required no shared-source or build changes. The resulting +Windows release build passed with the existing Expat linker warnings. +Independent review found no further production or test blocker before the +final local regression selection. + +The new checkpoint/thread characterization passed 96 checks on both old and +refactored implementations. A private same-process comparison using extracted +old/current functions compared 4,194,304 persisted bytes exactly across five +cases: ordinary/max inventory, ordinary/max extended names, and the expanded +thread image. The committed tests independently check payloads, footer fields, +little-endian checksums, reserved bytes and thread coverage against Python's +zlib, retaining existing corruption/refusal and migration cases. + +Resource/catalog characterization passed 196 checks before production edits; +the final focused selection passed 238 checks. CRC oracles cover every resource +mask, zero/high-bit/all-one seeds, 16/32 KiB boundaries, final-zero remapping, +an intermediate zero before the second resource, cancellation and failed reads +without publishing partial output. SHA-256 and package-isolation coverage +remain in place. The complete original Mercury bitmap (429,799,299 bytes) and +sound (257,054,056 bytes) resources produced identical baseline/current/Python +checksums for bitmap-only, sound-only and combined masks. They were read in +their installed Workshop folder and rehashed unchanged. This private comparator +tests the actual reader/checksum with explicit resource paths; it does not +claim to exercise Workshop discovery or network admission. + +The removed incremental table reduces the x86 check object from 2,680 to +1,656 bytes, measured with `sizeof`; the synchronous 1,024-byte local table and +both per-check table-construction loops are also removed. No new allocation +or table is introduced. An isolated Windows x86 `-O2` comparison passed 24 +old/new/oracle vectors. Seven alternating-order trials over 128 MiB per sample +measured median CRC time of 0.3883 to 0.03890 seconds for 256-byte calls and +0.3867 to 0.01832 seconds for 1 MiB calls (about 10x and 21x). These are checksum +microbenchmarks, not whole-game loading, checkpoint or frame-rate measurements. + +The final broad local selection passed **2,059 tests**, with nineteen skips and +the twelve unchanged strict boat expected failures. Production changes remain +entirely in MCC-owned files. Serialized formats, SHA content proof, network +version 41, OpenCE crossplay and Xbox/CE implementations are unchanged. +Private proof sources, commands, logs and hashes are under `build/stage6`. +The final focused checkpoint/thread selection includes two additional exact +thread-length boundary cases and passed 98 checks. Four optional real MCC/CE +asset checks also passed. The post-review release rebuild required no further +work; its executable SHA-256 is +`5f3f449c13fddf4198157bd94fed9cdc1fad02290ec34d966c3d420d0aa998c7`. + +### Native runtime, retained findings and cleanup + +The preserved baseline and final release each passed the same hidden, +singleplayer save/revert/core sequence on Ruby's Rebalanced `b40` and Mercury +Falling, loaded from their installed Workshop packages. Each run advanced +150 ticks, saved a changed MCC campaign flag, proved a subsequent mutation, +restored the checkpoint and confirmed the saved flag after another 150 ticks. +It repeated mutation/restoration through `core_save`/`core_load` and exited +normally. The paired executable hashes, settings, runner and map checksums +were checked independently. All eight retained 20 MiB images passed an +independent check of their protected MCC payload/footer/thread/name blocks. +These independently validated runtime images are not claimed byte-identical +across runs; the controlled five-case comparison above establishes exact +before/after serialized-byte equivalence. + +The final release also passed Mercury Falling, Xbox Blood Gulch, CE Death +Island, a deliberately invalid MCC tag-index fixture, then Ruby `a10` in one +process. Each valid phase required a new simulation epoch, an exact delayed +output marker and a complete rendered capture. The invalid map was refused +and the later MCC load recovered. Independent review checked the complete +logs, expected refusal, marker ordering, settings, captures and normal exit. +The runtime verifier additionally passed 83 negative controls for missing or +echoed outputs, extra acceptance events and changed protected bytes. + +Four earlier attempts are retained as failed/incomplete evidence. Two Ruby +attempts exposed runner command-length and repeated-log-observation problems; +an earlier transition collector could not encode one received character. +The other Ruby baseline attempt asserted on a stale script-node index after +revert. Its MCC checksums are valid. The runner had requested a save from a +temporary console expression that remained asleep during capture; another +baseline run reprinted that saved expression's marker after restoration. +Source inspection shows finished console threads are deleted and unreferenced +syntax is collected. This is a baseline console-expression lifetime finding, +not evidence of a CRC regression, and is retained for Stage 7 investigation. +The final paired recipe issues standalone save commands and waits outside +the game before checking completion. No production workaround was added. + +Nine sequential game attempts were stopped; all five final accepted runs +exited normally. Their generated caches, including those from failed attempts, +were removed (6,908,018,688 bytes). All six original Xbox/CE fixtures, three +tested Workshop maps and Mercury's two resource files were rehashed unchanged. +The 142 inactive save/support/capture files (338,155,372 bytes) were archived +losslessly to `build/stage6/inactive-runtime-evidence.zip` (9,989,586 bytes). +Every archive member was hash-verified before removal of the loose copy; +the adjacent manifest records original paths. Original maps and saves were +not modified. Disposable synthetic pytest fixtures, duplicate map copies and +test/probe binaries were removed; useful logs, proof sources and the baseline +build remain. There are no generated game caches or active owned game processes. +About 39 MB remains under `build/stage6`, primarily the 27 MB baseline build, +10 MB verified archive and 1.4 MB of CI evidence. The final release remains +usable under `build/windows`. + +These checks establish bounded native loading, save/revert/core behavior and +map-family transitions. They do not establish full campaign, multiplayer, +live split-screen, Android-device or browser-map compatibility. At this Stage 6 +completion point, Milestone 7 implementation had not begun. + +### Platform CI and completion + +Both push workflows passed on implementation revision +`71dcfe6dd74c59fd8ab2f54d8b9fa112e04d1a36`, attempt 1, without CI repairs or +reruns. The [MCC workflow](https://github.com/chestahh/GulchCE/actions/runs/42390735879) +passed Linux readers/validators (1,782 checks, sixteen skips), 38 separate +ASan/UBSan preview checks, Windows adapters (1,983 passes and seventeen skips +across invocations), and 36 software-GL meter renders. + +The [Build workflow](https://github.com/chestahh/GulchCE/actions/runs/42390735872) +passed all four debug platforms. Linux's main invocation passed 2,498 checks +with 27 skips, the twelve existing boat expected failures and seven passing +subtests; all its pytest invocations totalled 2,814 passes and 52 skips, with +the same expected failures/subtests. Ordinary and full-LTO ELF/COFF +light-storage checks and the Windows corruption negative control passed. +Android built its guest, host and debug APK and passed touch, gyro and MCC +importer checks. Web passed page/server tests, browser startup without retail +assets, and native Chromium/Firefox WebRTC checks with and without configured +packet loss. These are transport checks, not real-map multiplayer qualification. +Main-only release/profile jobs were skipped; the Windows release was built +and exercised locally. Counts from overlapping jobs are not unique test totals. + +CI logs, metadata and local log hashes are retained in `build/stage6/ci`. +Artifact metadata names the exact revision; CI binaries were not downloaded +or independently rehashed. Final documentation review checked 145 local links, +the new section anchor, named functions and test syntax. Production remains +confined to four MCC-owned files, with no shared-source, vendor, build-graph, +protocol or map changes. The combined review found no further justified change +within this milestone. Final evidence records both successful checks and the +retained baseline finding; Milestone 6 is complete. + +## Stage 7: scripts and state lifecycle + +Stage 7 starts from `42176d5423cf6430b29ac39549a034a8feebb7bd` in the same +dedicated worktree. The preserved Windows release has SHA-256 +`5f3f449c13fddf4198157bd94fed9cdc1fad02290ec34d966c3d420d0aa998c7`. +The initial checkpoint, campaign, names, progress, scripts, syntax and thread +selection passed 229 tests before production edits. Private commands, extracted +sources, logs and hashes are retained under `build/stage7`. + +### Justified changes and boundaries + +Two production files change, both MCC-owned. No map name, package ID, checksum +or asset fingerprint selects either behavior. No shared hook, native Xbox/CE +implementation, serialized format, network message or protocol version changes. +OpenCE version 41 and MCC protocol 64 remain unchanged: valid resolution and +checkpoint behavior are preserved; the correction rejects malformed saved data. + +[`mcc_scripts.c`](../port/linux/game/mcc_scripts.c) had two copies of seven +MCC function mappings, the vibration alias and campaign fallback. The private +`mcc_script_resolve` now owns that mapping. Preparation still runs before MCC +activation and may use native fallback; public runtime lookup retains its +loaded-MCC/null guard and does not gain fallback. A recognized vibration alias +whose rumble target is absent still returns `NONE`, even if the native table +contains the original alias. Thirty-six source-based before/after traces match +exactly, including function IDs, rewritten call/predicate IDs, refusal and lookup +counts. The scripts/parameters/syntax selection passed 188 checks before and +after. This removes duplicate maintenance and drift risk; no game-speed or +frame-time improvement is claimed. + +[`mcc_checkpoint.c`](../port/linux/game/mcc_checkpoint.c) now rejects a zero +object identifier in `mcc_checkpoint_units`. Native `datum_try_and_get` treats +an identifier of zero as an unused slot. A freed header can retain a bounded +datum pointer and unit type; matching a saved handle's zero salt therefore +does not establish a live unit. The old MCC preflight allowed that record +through. Native `game_state_image_accept` then copied the incoming image and +MCC names before the real grenade restore rejected it. This is an MCC +checkpoint-admission defect; fixing its preflight benefits every MCC checkpoint +using the format and requires no native change. + +The new regression extracts the real native array layout, array validation, +datum deletion/lookup and grenade snapshot/restore. It deletes slot 0 while +slot 1 remains live, producing a legal high-water count of two and one active +entry, then recomputes both MCC CRCs. On the old code, generic validation and +MCC preflight succeeded, acceptance failed, and live bytes/names changed; +campaign restoration was not reached. The focused baseline had 59 passes and +that one intended failure. With the one-condition fix, the malformed image is +refused before copying anything, while a valid salted unit restores normally. +Stale-salt and out-of-range-pointer controls also pass. Checkpoint, grenades and +thread checks passed all 105 cases. Names/campaign and unrelated pool validation +remain adapters in this fixture; this is not a claim to validate every native +checkpoint allocation or every runtime state. + +### Ownership reviewed and retained + +The combined review examined the following routes before final checks. Sound +code was retained where removing it would lose an established contract or where +no practical benefit was demonstrated. + +| Owner and route | Retained contract and evidence | +| --- | --- | +| `mcc_scripts_prepare`, `mcc_script_find`, `mcc_script_call_valid` | Preparation and guarded runtime resolution have different fallback rules. Unsupported names and malformed calls still refuse. Exact resolver traces and scripts/syntax tests cover the changed route. | +| `mcc_parameters_prepare`, `mcc_hs_release_arguments`, `mcc_hs_release_thread` | Prepared signatures/lexical owners are separate from live saved stack arguments. Publication counts clear on preparation failure/unload; return, cancellation, deletion and overflow release held object-list references. Existing recursion/sleep/overflow tests are retained. Full-capacity local-global reuse is not established by this audit. | +| `mcc_script_threads_prepare`, `mcc_hs_threads_activate`, `mcc_script_threads_dispose` | Reserved CPU storage owns extended frames; disposal restores the previous array and arena bytes before releasing MCC storage. Save-version bridges and address checks remain necessary. Thread lifecycle and checkpoint tests exercise these contracts. | +| `mcc_checkpoint_validate`, `mcc_checkpoint_restore` | Pre-copy validation and post-copy restoration are separate responsibilities. Preserve format/version, fixed saved-pointer addresses, CRC and bounds checks; the unused-unit correction closes one demonstrated preflight gap without a speculative transaction rewrite. | +| `mcc_campaign_validate`, `mcc_campaign_restore`, `mcc_campaign_dispose` | Validate the full supported snapshot before publishing campaign fields; restore owned engine globals and effects at lifecycle boundaries. Existing snapshot-version and malformed-state coverage remains. | +| MCC effects, game speed and progress | Keep host authority, reliable host-packet/size/stale-tick checks, map-owned restoration and progress journal's valid-prefix recovery with refusal to append after corruption. Inspection did not establish safe further trimming. | +| `mcc_object_names_*`, native name dispatch, `mcc_cache_tags_unload` | Extended names activate only for MCC scenarios beyond the native 512-name table. Deletion must scan aliases even for an object whose native name is `NONE`; checkpoint restoration intentionally restores mappings while restart/unload clears them. | + +Named-object coverage grew from seven to sixteen passing cases. It checks +complete snapshots at 513, 640 and 32,767 names, output sentinels, refused +null/length restores preserving mappings, unnamed aliases, native restart +clearing, repeated unload, and partial cleanup with the loaded flag already +false. Four private negative controls caused nine expected failures while two +unaffected controls stayed green. The actual cache-unload function is extracted, +but other owners are inert there; the loader's failure funnel was source-reviewed. +These tests do not replace the native transition checks or prove network play. + +### Shared console syntax finding: investigated, fix deferred + +Three baseline runs reproduced an accepted core load followed by an expired +script-node assertion: Xbox Blood Gulch, CE Death Island and Ruby's Rebalanced +`b40`. Each saved inside a sleeping temporary console expression, let that +expression finish, waited externally through at least two collection +opportunities, then loaded the core. The assertions and abnormal exits are +retained as defect reproductions, never counted as passing gameplay checks. + +Native `hs_runtime_initialize` stores threads in saved CPU state; MCC extended +threads use their reserved saved arena. Temporary console syntax lives outside +that saved state. `hs_thread_main` deletes a completed console thread, and +`hs_runtime_update` later runs `hs_node_gc`, which removes nonpermanent nodes. +Restoring the saved thread can therefore restore references to already-collected +syntax. A ten-case private proof uses the actual allocator, interpreter, +collector and MCC thread capture/restore. Native and MCC fail after collection, +with or without slot reuse, but resume the sleeping expression before collection. +Permanent scenario nodes and completed standalone commands are controls. Parser, +core admission and networking are outside that isolated proof; the native runs +establish the real admission/assertion sequence. + +This is a shared engine ownership defect, not an MCC-only compatibility need. +Discarding all saved console threads would also remove working replay behavior; +retaining all temporary nodes would consume the bounded syntax pool. A correct +fix needs a defined shared lifetime/admission design for syntax and strings, +saved-image compatibility, and comparison with upstream OpenCE's checkpoint +contract. No network-version requirement has yet been established by this +investigation. Preserve the user's crossplay requirement while resolving those +questions; do not introduce an MCC-only bypass or claim the defect is fixed. +The scoped investigation is complete, and that shared correction is explicitly +deferred. The user confirmed this deferral before starting Milestone 8; it does +not block the remaining MCC refactor. The evidence needed to reopen it is a reviewed ownership design with +legacy/MCC replay, collection, slot reuse, save compatibility and relevant peer +agreement tests. It is separate from Milestone 8's compatibility exceptions. + +### Final validation and completion + +The combined production/test/reader-guide review found no further justified +change within this milestone. The final local regression selection passed +**2,108 tests**, with nineteen skips and the twelve unchanged strict boat +expected failures. Four additional real MCC/CE reader/resource checks passed. +The Windows release built with the existing portable/release/PGO-off/LTO-off +configuration; a post-review rebuild required no work. Existing Expat import +warnings remain. Executable SHA-256 is +`5786761be690e78678c97ce8c3dc241934d30d33a49db524efc3d2315e7956f3`. + +The baseline and current releases each passed standalone save/revert/core-load +checks on Ruby B40 and Mercury Falling from their installed Workshop folders. +Each saved a changed campaign flag, proved the subsequent mutation, accepted +the saved image, confirmed the restored value and advanced another 150 ticks. +The current release also passed native `map_reset` on both MCC maps, Xbox +Blood Gulch and CE Death Island: a fresh low-tick epoch and 150 further ticks +distinguish a restart from merely continuing the old simulation. These restart +checks do not establish reset semantics for every campaign field. + +One current-build process traversed Mercury, Xbox Blood Gulch, CE Death Island, +an invalid MCC tag-index fixture and Ruby A10. The invalid map was refused and +the later MCC load recovered; each valid phase produced fresh simulation and +a rendered capture. Inspection of the four captures confirmed coherent scenes +and the expected HUD where visible, not exhaustive visual equivalence. +All nine successful runtime checks exited normally. The three baseline console +assertion reproductions above are separate failing gameplay cases. Runs were +sequential, hidden and used isolated saves; no multiplayer gameplay is claimed. + +Independent verification checked exact commands/results, map and executable +identity, paired settings, fresh epochs, normal exits, failure diagnostics and +all eight successful 20 MiB save/core images' protected MCC blocks. The three +reproducer cores retain their identities and hashes; the Ruby reproducer also +has valid MCC CRCs. All 188 host-only verifier controls passed. An initial +checker incorrectly required restart cues at exactly tick 1 and assumed CE's +launch path was its saved scenario name. Source inspection and the authenticated +CE tag index established the actual contracts; the corrected checks retain +strict epoch/order/identity requirements. Both checker versions and the initial +failed verification are preserved. No game rerun or production change was used +to hide those checker assumptions. + +All twelve owned game processes stopped. Their 72 generated map-cache files +(9,210,691,584 bytes) were removed after each attempt. The 113 inactive +save/support/capture files (429,544,430 bytes) were archived losslessly to +`build/stage7/inactive-runtime-evidence.zip` (6,732,992 bytes). Every member and +loose file was hash-verified before removing the loose copy; the manifest records +original paths. Useful logs and reproducible proof sources remain available. +Final cleanup removed 431,648,191 bytes of disposable synthetic fixtures, +test binaries and the six copied map/resource inputs; earlier proof-binary +cleanup is recorded separately. All eleven original map/resource inputs were +rehashed unchanged. About 44 MB remains under `build/stage7`, principally the +27 MB baseline build, 6.7 MB verified archive, proof sources, manifests and CI +logs. No generated game caches or active owned game processes remain. The +current release stays usable under `build/windows`. + +Both push workflows passed on implementation revision +`f8e621acf6505e1a414e4e52142c7efcbb7b61a9`, attempt 1, without repairs or reruns. +The [MCC workflow](https://github.com/chestahh/GulchCE/actions/runs/42394316405) +passed Linux readers/validators (1,795 checks, sixteen skips), 38 separate +ASan/UBSan preview checks, Windows adapters (2,032 passes and seventeen skips +across invocations), and 36 software-GL meter renders. + +The [Build workflow](https://github.com/chestahh/GulchCE/actions/runs/42394316106) +passed all four debug platforms. Linux's main invocation passed 2,498 checks +with 27 skips, the twelve existing boat expected failures and seven passing +subtests; its nine pytest invocations totalled 2,814 passes and 52 skips, with +the same expected failures/subtests. Ordinary and full-LTO ELF/COFF storage +checks and the Windows deliberate-corruption control passed. Android built +the guest, host and debug APK and passed signing, touch/gyro and importer +checks. Web passed Node/page tests, asset-free browser startup and native +Chromium/Firefox WebRTC checks with and without configured packet loss. +These are transport checks, not real-map multiplayer qualification. The main-only +release job was skipped; Windows release was validated locally. +Overlapping job counts are not unique test totals. + +Complete job logs, revision/attempt metadata, artifact metadata and local hashes +are retained in `build/stage7/ci`. Upload digests were matched to job logs; +CI binaries were not downloaded or independently rehashed. Final documentation +review checked 134 local links, the Stage 7 anchor, seventeen named functions, +test syntax and the two-file MCC production boundary. The final resulting +implementation, tests, integration and reader documentation were reviewed; +no further justified changes remain within this milestone. Full campaigns, +real-map co-op, live split-screen and physical Android/browser-map gameplay +remain unverified by these bounded checks. Milestone 7 is complete with the +shared console correction explicitly deferred. At that completion point, +Milestones 8–9 had not begun. + +## Stage 8: compatibility exceptions and known gaps + +### Retained HUD selectors + +The 21 structural profiles in +[`mcc_hud_layout.inl`](../port/linux/game/mcc_hud_layout.inl) remain unchanged. +No simpler replacement was justified by the inspected authored fields or parent +usage. This is a retention decision with explicit limits, not proof that the +table is the only possible implementation or that every unknown layout intends +the wider MCC safe frame. + +The fresh production-visitor audit covered **670 HUD components across seventeen +installed MCC maps**, with 495 recognized components. Inputs were seven stock +MCC maps and ten Workshop maps, including Ruby's Rebalanced A10/B40/D40, +Mercury, Descent and Quarantine. Every retained profile had an installed match: + +| Profile label | Matching components | +| --- | ---: | +| assault rifle | 17 | +| master rounds | 23 | +| empty weapon/vehicle layouts | 210 | +| cyborg | 15 | +| cyborg_mp | 15 | +| warthog driver | 15 | +| passenger_2 | 15 | +| gunner | 15 | +| scorpion | 3 | +| passenger_4 | 11 | +| passenger | 9 | +| passenger_3 | 9 | +| pistol | 19 | +| master plasma | 15 | +| grenade counter panel | 36 | +| banshee | 8 | +| ghost | 4 | +| rocket launcher/needler | 26 | +| sniper rifle | 10 | +| shotgun | 13 | +| master fuel | 7 | + +These labels describe evidence; names do not select the frame. The audit +extracts the current C visitor and checks every fingerprint against an +independent bounded numeric inventory. All 670 bitmap-name controls retained +their fingerprint. All 670 private root-anchor perturbations changed it, and +all 495 recognized components became unknown. Original map files were opened +read-only, and the private tag arena was compared byte-for-byte after all +private mutations were restored. The regeneration script, input identities, source hashes, +compiler invocation and per-component metadata are retained under +`build/stage8/hud`; run `audit_profiles.py` there using the recorded stage1 +environment. These controls establish classification coverage and sensitivity, +not how hypothetical edited maps ought to render. + +Seven combinations of tag group, root anchor, the set of scaling flags and the +set of scales occurred in both recognized and unknown components. Examples +include stock gunner geometry versus Ruby B40's shadow gunner, and stock master +plasma versus Ruby's master sword. That evidence defeats this particular +aggregate selector; it does not disprove every richer authored-field rule or +establish unknown layouts' intended margins. Parent inheritance also propagates +an already classified marker: `mcc_hud_weapon_frame_begin` cannot supply the +initial decision for a populated root without a parent. + +`mcc_hud_plan_prepare` fingerprints validated pristine bytes once at load time, +before normalization. The ownership plan isolates mutable aliases; temporary +plan arrays are freed on success or failure. Runtime-owned markers and converted +data are released by failed-load/unload cleanup. Authored padding is cleared +before the converter writes its own marker. Drawing remains guarded by loaded +MCC tags. The sole weapon-frame caller brackets rendering with begin/end, without +an intervening return or goto; both boundaries clear transient state. No new +lifetime defect or cleanup edit was justified by this review. + +A separate retained exception is `mcc_hud_message_frame` in +[`mcc_hud.c`](../port/linux/game/mcc_hud.c): top-left messages at normalized +offset `(0, 60)` use native safe margins. This recognizes stock placement +independently of replacement fonts or icon art; it is not an explicit authored +safe-frame flag. Integer coordinate conversion can map distinct raw positions +to that same normalized offset. A custom author choosing that geometry with +different intended margins remains indistinguishable. Its marker has the same +MCC runtime ownership and cleanup as other converted placements. + +Existing public coverage includes 26 actual-visitor layout cases for geometry, +name independence, excluded fields, malformed references, bounds and read-only +hashing. Normalization tests cover a positive grenade profile, a two-pixel +authored near miss and aliased mutable blocks. Eleven stock-message cases cover +both coordinate units, nearby positions, other anchors and erasure of a seeded +marker. Together with the fresh all-profile audit, no material test gap was +found that justifies duplicating all authored profile layouts in tracked tests. +Runtime/rendering results are recorded separately below; classification +checks alone do not validate visual intent. + +Remove or reduce either layout exception only after a demonstrated authored +field or usage rule expresses the intended margin and preserves recognized +layouts, nearby custom layouts, parent ownership and independently centered +components. Check renamed resources, bounds, aliases, failure cleanup and +MCC-to-Xbox/CE transitions, with actual rendered comparisons on Ruby's +Rebalanced, Descent and other affected maps. Rarity or line count alone is not +evidence for removing a profile. + +The bounded adjacent-selector review distinguished these exceptions from +semantic contracts. `mcc_hud_multiplayer_text` selects +`ui\multiplayer_game_text`, string 100, because the existing score-hint consumer +in [`game_engine.c`](../source/game/game_engine.c) reads that exact resource and +index; resolving its MCC formatting argument is not a per-map bypass. Script +function/global names identify language operations, controller-entry ownership +identifies glyph roles, and structure offsets, bitmap flags and child anchors +describe validated formats. `mcc_hud_title_bounds` applies its non-wrapping +title policy to authored flags/alignment, without selecting Warthog Rally or a +160-unit box. No adjacent map-name/checksum dispatch or justified selector trim +was found in the inspected HUD/script paths. This bounded result is not a +repository-wide audit; the broader combined review remains Milestone 9. + +### MCC-wide script admission + +The installed Quarantine map (`2963835242`, SHA-256 +`5b89b330291e7cd2a5c098b2c379aee3335e1349bc85aa1677638883b26ac8cf`) +contains 114 scripts and 19,331 syntax nodes. Its continuous `life_lost_0` +contains one valid, permanent, zero-argument `ai_deselect` call. Native map +policy deliberately excludes that operation, so the previous build disabled +the entire script. This was an MCC language-compatibility gap, not malformed +map data or evidence that Xbox/CE's policy should change. + +The existing native `ai_scripting_deselect` service performs real selection +clearing when AI is initialized, including the native debug record/idle-look +cleanup. An eighteen-line addition to `mcc_scripts.c`, plus its private ID, +exposes that service through the existing MCC registry and validator. It adds +no persistent state, save fields, shared hook, map-name selector or no-op. +Existing loaded-MCC guards and unload ownership apply. Xbox/CE's allowlist, +adjacent `ai_select` refusal and client console authority remain unchanged. + +MCC protocol advances from 64 to 65 because previously disabled authored +gameplay now executes. OpenCE stays at 41; packet layouts and the camera +envelope versions remain unchanged. The composed admission regression compiles +the complete actual server dispatcher and both envelope implementations: +MCC 64 is refused before the ordinary join handler with or without a camera +wrapper; MCC 65 reaches it with MCC capability. Camera-only requests do not +gain MCC access, and legacy control joins retain their path. Removing the +inner revision check makes the negative control fail. This routing harness +uses an observed join sink; separate existing actual-handler tests cover +decoding, tokens, bans, slots and session authorization. + +Four focused resolver/admission cases failed before the adapter and pass +afterward. The final focused selection passed 121 checks, including real-source +native clearing and inactive-AI behavior, malformed calls, unload guards, +unchanged native/client policy and three deliberate-fault controls. The combined +review found no further necessary production change or justified HUD trimming. +It reviewed the final implementation, integration, tests and reader guides; +no shared `source/` implementation changed in this milestone. + +### Runtime and local validation + +The reviewed Windows release builds with the unchanged portable/release, +PGO-off/LTO-off configuration. Its SHA-256 is +`816055002eeb8f5434ec78d5dad817e5397d443e8ccb58e66d9d852e755cafbb`; +existing Expat import warnings remain. The local regression selection passed +2,123 tests, with nineteen skips and the twelve unchanged strict boat expected +failures. Four additional real MCC/CE reader/resource checks passed. + +Matched baseline/current standalone runs on Workshop Ruby B40, Descent and +Quarantine each advanced at least 1,800 ticks and produced a fresh complete +capture. Baseline Quarantine deliberately records `passed=false` for its exact +script refusal, despite completing the observation; the current run has no such +refusal. The other five runs pass and all six exit normally. Visual inspection +found coherent scenes and no apparent HUD placement/clipping regression in +these views. Ruby used 640x480 and Descent 1280x720; this is bounded rendering +evidence, not pixel-identical animation or proof of all authored layout intent. + +The baseline/current two-peer Quarantine comparison used separate saves and +authenticated host consoles. Both runs first established real cooperative mode, +two living players, fresh simulation, completed authored introduction, untouched +start device (`game_started=false`), positive lives and false end/cinematic +flags. The only assigned scenario value was `lives=0`, with immediate readback. +The baseline still had false end/cinematic flags after 1,000 additional ticks. +The current host reached `game_ended` at logged tick 1,770, the unique authored +`one_time_cinematic` marker at 2,640 and continued to 2,730. Source inspection +places `ai_deselect` after that unique marker and `ai_erase_all`, without an +intervening sleep. +Both peers continued and exited normally. This demonstrates the authored branch +after condition injection, not player death, life decrement, a full campaign +or a full synchronization verdict. + +Two earlier baseline setup failures are retained. The first lacked stock +Carousel, which native network fast setup loads before choosing the requested +MCC map; adding one verified private input copy resolved that prerequisite. +The second stopped waiting for a living second player at 45 seconds. Quarantine's +authored co-op introduction lasts 1,430 ticks, and native cooperative spawning +holds extra players during a cinematic. A 75-second wait accommodates that +existing behavior. Neither failure required a production change or was relabeled +as a gameplay pass. + +One current process traversed Mercury Falling, Xbox Blood Gulch, CE Death Island, +a bounded invalid MCC fixture and Ruby A10. All four valid phases produced a +fresh tick epoch, 150 further ticks and a complete capture. The invalid map was +refused, returned to the menu and did not prevent the subsequent MCC load. +Visual inspection confirmed coherent scenes and the native HUD where visible; +Mercury and Ruby were cinematic views. The process exited normally and its +unique invalid fixture was removed after containment/content checks. + +The newly reached authored `garbage_man` calls the existing native +`rasterizer_decals_flush` operation, whose documented effect is to flush all +decals. The current branch emits two permanent-decal deletion diagnostics during +that operation, before `ai_deselect`. Source inspection traces them through the +native cache flush and decal deletion callbacks; removal is consistent with +the command's stated effect, while permanent bookkeeping/logging remains +inconsistent. These are the only new unique error/warning classes in the +baseline/current branch comparison, on the host; no new client class appears. +They are explicitly retained findings, not an assertion that the logs are clean. +A separate baseline control waited 1,800 ticks, called only authored +`garbage_man`, then advanced another 150 ticks. Neither diagnostic existed +before that call; both appeared once afterward, reproducing the same native +behavior without the new adapter. The control completed and exited normally, +while retaining `passed=false` for the baseline's original script refusal. +No shared decal implementation was changed. Repeated flush bookkeeping and +longer-term rendering effects remain outside this bounded attribution test. +Independent verification covers twelve sessions and sixteen stopped processes, +with no forced termination or nonzero exit. It checks executable/map identity, +settings, ordered commands and response frames, tick epochs, complete captures, +all log sinks, actual failure verdicts and diagnostic inventories. Fourteen +isolated negative controls reject altered outcomes, identities, missing responses +with echoes retained, hidden fatal messages, missing transitions, partial captures +and an incomplete flush control. `archive_ready` means evidence integrity and +inactive processes; it does not turn a known refusal or warning into a pass. + +No old-checkpoint migration is established: +a checkpoint created when a continuous script had been disabled is not proven +to acquire its missing thread on restore. The supported admission path being +tested here is a fresh map load. Shared console-syntax and boat corrections +remain explicitly deferred; Milestone 9 has not begun. + +### Platform validation + +The [MCC workflow](https://github.com/chestahh/GulchCE/actions/runs/42399542277) +passed on implementation revision `99341deebf53cafdb82c9c901dfa31091a7b85a0`, +attempt 1: 1,796 Linux reader/validator passes with sixteen skips, 38 separate +ASan/UBSan preview checks, 2,037 Windows adapter passes with seventeen skips +across invocations, and 36 software-GL meter renders. + +The initial Build workflow exposed one Linux compilation failure in the new +camera admission test: its helper had static linkage after a public external +declaration. Windows' MSVC-target compiler had accepted it. The one-word fixture +correction matches that header; no production code or runtime binary changed. +Ten targeted camera/MCC protocol checks passed after correction, and a +Linux-target front-end control reproduces the old error and accepts the fix. +The original failed job/logs remain in the evidence. + +The [corrected Build workflow](https://github.com/chestahh/GulchCE/actions/runs/42400612375) +passed all four debug platforms on `15d2ef13096751ba266d8845f18b4caae2f217e8`, +attempt 1. Linux's nine invocations totalled 2,824 passes and 52 skips, with +the twelve existing boat expected failures and seven passing subtests. +Windows storage/linkage checks, Android guest/host/debug-APK and importer/input +checks, and web Node/page/startup and Chromium/Firefox native WebRTC checks +passed, including configured packet-loss transport controls. These are not +full real-map internet/co-op or physical-device gameplay qualification. The +main-only release job was skipped; Windows release was validated locally. + +The repair changes only the camera fixture; exact revision comparison proves +production, MCC workflow YAML and its test inputs unchanged. That file is +outside the MCC workflow's path filters and invocations, so its earlier green +result is reported on its actual revision rather than attributed to the repair. +Overlapping job counts are not unique test totals. Complete logs, revision and +attempt metadata, the original failure, revision proof and artifact metadata +are retained under `build/stage8/ci`. All six Build artifact upload digests +match their logs; binaries were not downloaded or independently rehashed. + +### Final review, cleanup and completion + +The final combined Stage 8 implementation, integration, tests and documentation +were reviewed before the required checks. The CI-discovered fixture correction +was reviewed and its affected local/platform checks rerun. The final document +check validates 170 local links, eight named symbols, Python syntax and the +MCC-owned production boundary. No additional code change or speculative +profile trimming is justified by this milestone's evidence. + +All sixteen owned game processes exited normally. Their 96 generated map +caches, totalling 12,280,922,112 bytes, were removed after each attempt. The +462 inactive save/support/capture files (490,433,888 bytes) were archived +losslessly to `build/stage8/inactive-runtime-evidence.zip` (38,048,459 bytes). +Every archive member and loose file was hash-verified before loose removal; +the manifest records original paths. Cleanup removed another 439,092,050 bytes +of disposable fixtures, generated bytecode and seven private input copies. +All 26 original map/resource inputs, including the full seventeen-map HUD audit +corpus, were rehashed unchanged after cleanup. No generated map caches remain. + +The cleanup gate checks session result and supporting-evidence hashes, resolved +path containment, linked ancestors and process identity. Windows reused one old +test PID for an unrelated application process; cleanup first refused it, then +verified its different executable and later creation timestamp without stopping +that process. Both failed preflight logs and the identity proof remain available. +Thirty-two private cleanup safety controls passed. About 79 MB remains under +`build/stage8`, chiefly the 38 MB verified archive, 27 MB baseline build, CI logs +and reproducible metadata/source evidence. The current Windows release remains +usable under `build/windows`. + +Milestone 8 is complete. Its remaining limits are explicit: no full campaign, +full multiplayer synchronization, old-checkpoint migration, live split-screen, +physical Android or browser-map gameplay qualification; no correction of the +shared boat, console-syntax or native flush bookkeeping behavior. + +## Stage 9: combined review and extended validation + +This milestone reviews the resulting branch against original main +`db1697c9b0c46289596f22213a5bef8ee327be24`, including all earlier production +changes, tests, build integration and reader documentation. The shared boat +and console-syntax corrections remain explicitly deferred. No additional +game-code change is justified by this review; the demonstrated corrections +below affect validation tooling and a stale documentation statement. + +### Combined review and boundary coverage + +The resource directory sort had no ordering-dependent consumer; complete +name scans and duplicate refusal remain. Bitmap cursor correctness follows +from checked original handles and complete fresh-handle clone groups, with +reuse appending nothing. HUD planning snapshots shared owners before writes +or pointer publication, and temporary planning storage is freed on failure +and success. The remaining tag pass clears meter metadata after placement +normalization. Checksum callers preserve their distinct framing and seeds. +Script resolution retains preparation/runtime separation; checkpoint +validation rejects freed slots before copying live state. AI deselection +uses the existing native service through the MCC registry. + +The final pass also inspected relevant activation, failure, unloading, +worker-join and GPU-before-pixel cleanup routes. These ownership boundaries, +required stubs, malformed-input checks and distinct regression cases remain +necessary. There is no production `source/` change across this refactor. +There is no new map-name, map-checksum or package-specific gameplay bypass. +The 21 structural HUD exceptions and separate message-frame rule retain the +evidence and removal conditions recorded in Stage 8. Existing optional HUD +artwork CRC selectors identify two known replacement sheets, after format +and size checks; they are not map selectors. Bridge tests use mocked CRCs, +so they do not independently verify those original artwork fingerprints. + +This reconciles the navigation inventory in `CODINGSTANDARDS.md` with the +actual review. "Partial" identifies a bounded inspection, not a known defect +or a claim that the remaining implementation has been audited. + +| Boundary | Changed and reviewed across the branch | Reviewed and retained; remaining limits | +| --- | --- | --- | +| Selection, loading, packages and resources | Resource ordering/checksums and HUD metadata conversion | Cache load/unload, validation worker teardown, relevant handle/root-alias checks and bitmap access reviewed. Catalog, loading UI, package/identity/SHA implementations and remaining parser/converter behavior are partial or unaudited. | +| Scripts, parameters and object names | Resolver, thread checksum, MCC AI deselection | Syntax, parameters, runtime/thread ownership, name tables and game speed reviewed. Full-capacity local-global reuse and every legacy interpreter route remain unestablished. | +| Checkpoints and campaign state | Checksum and unused-unit preflight | Campaign snapshot/lifecycle, script effects and progress journal reviewed. Individual campaign evaluators/rendering are partial; older disabled-script checkpoint migration remains unverified. | +| Explicit packages and progression | None | Full manifest, map-catalog and Android importer audit remains outside this review. Their automated checks are separate evidence. | +| Weapon-authored cameras | None | Existing camera/MCC admission-envelope composition reviewed as a network dependency; camera implementation not deeply audited. | +| Networking and names | MCC protocol version and combined manifest | Protocol, network adapter, names synchronization and relevant shared admission/cleanup routes reviewed. Workshop metadata and every native transport implementation not deeply audited. | +| Player, inventory, movement, damage, boats, seats and recordings | None | Boat initializer/native force consumers and checkpoint grenade lookup dependency reviewed. Remaining gameplay modules not fully audited. | +| Rendering, HUD and audio | Bitmap conversion/access, HUD ownership/layout and redundant normalization | Texture registry/bridge, relevant HUD frame/glyph cleanup and native decal-flush attribution reviewed. Geometry, shader, particles, sprites, audio/Vorbis and remaining HUD draw behavior not fully audited. | +| Menus and pause | None | Implementation audit remains outside this review; existing executable tests remain in the regression selection. | + +No further production trim is supported by these findings. Removing required +family boundaries or retained exceptions merely to reduce code would lose +supported behavior. Private review notes are retained under +`build/stage9/reviews/`. + +### Validation-tool corrections + +Failure injection into the real `mcc_native_smoke.run_case` and `main` +reproduced seven adverse cases: kill failure, wait timeout, console-close +failure, stdout-only fatal diagnostics, and survivor/unknown/exception +completion from a case. Previously, caches or staged executables could be +deleted despite uncertain child exit; a close error bypassed shutdown and +init restoration; stdout-only failure could be reported as success. + +Cleanup now requires observed exit or no launched child, uncertain completion +stops subsequent cases and preserves staged binaries, close errors retain +diagnostics while shutdown/restoration continues, and all four log sinks +contribute to the verdict. Results retain PID, output path and shutdown state. +Two normal-completion controls accompany the seven adverse cases. These tests +use fake processes and literal fixture bytes; they do not leave live games. +The before-fix log records the adverse behavior; the two normal controls +initially failed only because the new shutdown-result fields were absent. + +The focused suite passed 56 tests, with one unavailable file-symlink privilege +skip. Two earlier sandbox-denied junction setup failures were retained and +the complete selection rerun with native Windows operations available. +`port/linux/NETCODE.md` also corrects one stale current MCC version from 64 to +65; historical version statements remain unchanged. OpenCE remains 41. + +### Local and platform validation + +Implementation revision `f25c4886a0ee1567b8b3808eee4bd8b4e1e3e6be` +passed the combined local selection: 2,193 tests, 24 skips and the twelve +unchanged strict boat expected failures. The selection includes all MCC test +modules, MCC harness cases, frontend tests, CE cache readers, Workshop/startup, +camera admission, network-comparison and HUD threshold checks. Four additional +installed Ruby B40/CE reader, geometry and resource checks passed. Windows +release was already up to date; the wire-format manifest matches its record. +Local skips include unavailable file-symlink privilege, opt-in assets, +Linux discovery and POSIX process-lifecycle checks; the four selected asset +checks were then run with explicit inputs. The document check covered 232 +local links, eleven named symbols, changed Python syntax and the combined +MCC-only production boundary. + +Both fresh workflows passed on that exact revision, attempt 1: + +- [MCC map validation, run 42403748356](https://github.com/chestahh/GulchCE/actions/runs/42403748356): + Linux reader/validator 1,802 passes and nineteen skips, plus 38 sanitizer + passes; Windows adapters 2,046 passes and seventeen skips; 36 real + software-GL meter-render checks. +- [Build, run 42403748394](https://github.com/chestahh/GulchCE/actions/runs/42403748394): + Linux, Windows, Android and web debug builds passed. Linux recorded 2,824 + passes, 52 skips, twelve boat expected failures and seven subtests across + its invocations. Windows storage, Android touch/gyro/importer, web startup, + Node and Chromium/Firefox native-WebRTC checks passed, including configured + packet loss. Branch release jobs were intentionally skipped; the local + Windows runtime build is release. + +These selections overlap and are not a unique-test total. Nine decoded job +logs, ten job records and six artifact metadata records are retained under +`build/stage9/ci`; all six artifact IDs, revision identities and upload digests +match their logs. No CI binaries were downloaded. Build and transport checks +do not establish physical Android play, browser-map gameplay or an official +upstream-executable crossplay result. + +### Repeated loading, timing and memory + +Four sequential, matched Windows sessions completed 64 valid loads and sixteen +deliberately invalid MCC loads with actual menu recovery. Each process repeated +Mercury Falling, Xbox Blood Gulch, CE Death Island, refusal/menu and Ruby A10 +four times: one warm-up and three measured cycles. Original main and the +current build ran in both orders. All valid phases advanced at least 150 fresh +logged ticks; every process closed normally. Workshop originals stayed in +place. Renderer, 640x480 resolution, high-resolution HUD, 30 FPS cap, audio-off +settings and SDL DLL matched; captures were disabled during measurement. + +The original-main executable remains SHA-256 +`f1ec0dca876aa3cf746a4095ac9115cc026902f4679d1c3941deb20928c85d56`; +the unchanged current game executable is +`816055002eeb8f5434ec78d5dad817e5397d443e8ccb58e66d9d852e755cafbb`. +Milestone 9 changes validation tools/documentation, not that game implementation. +Private Win32 measurements use the owned process handle for private memory, +working set and handle counts. A read of the source-defined game-state header +confirms each actual map; it performs no process write, scan or save operation. + +Six measured samples per build give the following median seconds and observed +minimum–maximum ranges. These include command queueing, log publication and +approximately 100 ms observer cadence; they are not engine-only loading timers +or statistical confidence intervals. + +| Boundary | Original main | Current | +| --- | ---: | ---: | +| Mercury first logged tick | 13.567 (12.239–15.926) | 13.916 (11.657–14.467) | +| Xbox first logged tick | 1.613 (1.574–1.626) | 1.634 (1.583–1.680) | +| CE first logged tick | 2.035 (2.019–2.061) | 2.007 (1.984–2.072) | +| Ruby A10 first logged tick | 13.449 (11.796–14.949) | 14.606 (11.990–15.127) | +| Exact refusal/menu diagnostic | 0.444 (0.434–0.459) | 0.443 (0.430–0.451) | + +Time order materially affects the result: original-main Mercury/Ruby medians +fell from approximately fifteen seconds in its first process to twelve in its +last; the second current process also became faster during its sequence. +Neither the first apparent improvement nor the pooled Ruby increase isolates +a build effect. The Xbox median difference is below observer cadence and its +ranges overlap. These observations demonstrate no clear attributable loading +regression, but do not statistically establish speed gains or performance +parity. File-cache state and scheduling were uncontrolled. + +The first pair's measured menu-memory growth was 1.49 MiB on main and 10.11 MiB +on current, which prompted the reverse-order repeat. That pair grew 12.45 MiB +on main and 2.86 MiB on current. Current's observed menu maximum was 563.75 MiB +versus main's 564.72 MiB; Mercury maxima were 1,220.06 versus 1,223.80 MiB. +Some boundaries decreased, both builds released hundreds of MiB between MCC +and menu, and handle counts declined. There is no repeatable current-only +retention excess. This is not a universal plateau, attribution of every +retained byte, GPU-memory measurement or proof against long-duration leaks. + +Logical converted-tag storage is separately bounded and identical on every +repeat: Mercury adds 7,152 occupied arena bytes and Ruby A10 adds 6,832, chiefly +the required HUD ownership copies. Bitmap counts and pixel bytes are unchanged. +Temporary planner arrays are freed; retained copies belong to the map arena's +unload/decommit path. Windows commits the same fixed 64 MiB arena in both +builds, so these occupied-byte deltas are not equivalent extra PrivateUsage +and do not explain the larger process-memory variation. + +The first collector attempt remains failed: it incorrectly required a second +Xbox precache-start message, although a cached load does not emit that message. +The corrected observer verifies actual scenario identity/checksum from the +fixed native header and fresh tick epochs. Thirty-seven helper controls and +96 receipt-invalidation controls passed. Full trajectories, source identities, +raw logs and limitations are in `build/stage9/cycle-summary.md` and +`cycle-verification.json`; the initial failure was not relabelled successful. + +### Saves, restarts and co-op findings + +Current Ruby B40 and Mercury passed standalone save/revert, core save/load and +map-reset checks. Each restore proves a saved boolean's true–false–restored +round trip and at least 300 further fresh simulation ticks. Independent +decoding validates the retained 20 MiB checkpoint/core images and their MCC +footer/thread checksums. Xbox Blood Gulch and CE Death Island reset controls +also passed. These checks use completed standalone commands; they do not +snapshot a sleeping temporary console expression or close the separately +deferred console-syntax lifetime defect. + +The first Mercury attempt correctly stopped when its checkpoint image changed +before the planned revert. Both images remain retained. The original helper +called this an auto-save, but the evidence establishes replacement, not its +writer. Removing the optional idle window between capture and revert allowed +the retry to verify the same captured image; all post-restore tick checks stayed. +The helper did not overwrite the live checkpoint with its retained copy, and +no authored script was disabled for that retry. + +Extended current/current Mercury co-op passed admission, two living-player +checks and 1,800 further ticks. The unchanged strict network comparator passed +with sixty paired seconds and 1,799 on-foot drift samples, no threshold breaches +and normal exit of both peers. Nonzero drift remains recorded; this is not a +claim of bit-identical views or full campaign compatibility. + +Ruby B40 exposed a separate **pre-existing shared co-op checkpoint-recovery +failure** in the OpenCE Crossplay profile. Both current/current and +original-main/original-main runs fail the unchanged strict comparator after +team-wipe reverts, with sufficient samples (1,031 and 1,271 respectively). +An additional current idle-input run also fails after reverts with 744 samples; +the finding is not an insufficient-sampling verdict or restricted to bot combat. +Both peers stay connected, but the client lacks a player-unit binding while +the host has a positive-vitality unit. The logger's `alive` field represents a +unit binding, not a direct client health measurement. + +In the current bot run, mismatches span 21 and nine consecutive paired samples, +approximately twenty and eight seconds. Three samples is the failure trigger, +not their total duration. The baseline also crosses that threshold; subsequent +raw logs still disagree after their clock offset exceeds the comparator's +pairing tolerance. These runs prove the failure class predates the refactor; +they do not establish identical recovery timing or severity. A final one-shot +`(players)` conditional also failed in the current cases; it tests unit objects, +not session membership or continuous absence throughout its wait. + +A final aim-only control completed 900 fresh ticks (1110–2010), using only +right-stick test input. Its strict verdict is also failed, with 840 drift +samples and no insufficient-sampling problem. The host reverted at tick 2012, +just after that window; fifteen paired samples then disagreed from 2040 to +2461, approximately fourteen seconds through shutdown. An earlier isolated +mismatch at 1920 did not reach the unchanged threshold. Thus the sustained +failure in this run occurred during the final confirmation wait, not within +the completed 900-tick window. The absent final unit-count receipt and failed +judge remain recorded; this is not an ordinary-co-op pass. + +The responsible shared `network_coop`, `network_objects` and +`network_distributed` implementations are unchanged across this refactor. +Source inspection finds the live-unit recovery/replacement operations guarded +by `third_person_session_active`; both peers' recorded profile is +`opence_crossplay`. As documented in `NETCODE.md`, that profile retains the +existing checkpoint behavior and does not execute the separately versioned +recovery extensions. This supports a shared profile/recovery classification; +the exact stale-handle mechanism remains an inference because these logs do +not expose every object handle. It is distinct from console-syntax ownership. + +No map bypass, profile change or guard broadening was made. Preserving OpenCE +crossplay and feature isolation precludes silently importing those extensions +into this cleanup. A separate shared-engine contract/version review is needed +before repairing or qualifying this recovery path. This is a retained failure, +not an MCC refactor fix or full co-op checkpoint compatibility sign-off. + +### Legacy mixed-build checks and evidence audit + +Original-main/current pairs passed on Xbox Blood Gulch and CE Death Island +in both host directions. Each completed 1,800 fresh post-admission ticks and +61 paired seconds with the unchanged strict comparator, normal process exits, +and no reported divergence or comparator problem. + +| Map family | Host build | On-foot drift samples | Maximum position difference | +| --- | --- | ---: | ---: | +| Xbox | Original main | 1,822 | 0.079467 | +| Xbox | Current | 1,828 | 0.079051 | +| Custom Edition | Original main | 1,496 | 0.159609 | +| Custom Edition | Current | 1,518 | 0.079756 | + +These establish bounded mixed-build behavior on the identified OpenCE 41 +paths. They are not tests against an official upstream executable. Original +and current MCC peers were tested separately within their own protocol +versions; the earlier MCC version bump intentionally prevents mixed admission. + +Independent verification binds every runtime session, raw logs, source +snapshots, settings, binary identities and supporting files. The final ledger +contains nineteen sessions: thirteen positive observations and six retained +failures (the first collector, the replaced Mercury checkpoint, and four Ruby +co-op runs). Its coverage-completed flag is true; its overall runtime-pass flag +is false. Archive readiness establishes integrity and process inactivity, +not compatibility. Additional support files are explicitly identified as +preservation-only where they received hashing rather than semantic decoding. +The state/pair verifier passed 37 negative/positive controls, the inventory +merger twenty, the frozen state/pair helper twenty and the cleanup gate 41. +These controls supplement the cycle controls; they are not gameplay samples. + +### Final review, cleanup and delivery limits + +The final combined implementation, integration, tests and reader documentation +were reviewed before the required regression checks. The resulting smoke-tool +correction received focused failure injection, the full local selection and +both fresh CI workflows. Subsequent changes record the completed runtime +observations and limits; they do not modify the tested implementation, workflow +or test inputs. Both workflows exclude documentation-only pushes, so their +successful results remain attributed to `f25c4886a`. The final document check +validates 232 local links, eleven named symbols, changed Python syntax and +the combined production boundary. No further game-code change or speculative +trim is justified by the review. + +All 28 owned game processes exited normally. Their 168 generated map caches, +totalling 21,491,613,696 bytes, were removed after each run; none remain. +Cleanup removed 7,102 verified disposable fixtures and private input copies, +totalling another 440,218,858 bytes. No original maps or saves were removed. +The 1,097 inactive runtime save/support files and fifteen literal test-save +fixtures (745,741,325 bytes combined) were preserved losslessly in +`build/stage9/inactive-runtime-evidence.zip` (7,455,234 bytes). Its manifest +records original paths and SHA-256 values. Every archive member and loose +source was verified before removal of the loose copy. + +The separate final delivery check reverified archive inventory, CRCs, sizes +and hashes, all 309 remaining loose runtime evidence files, exact session +inventory, process inactivity, missing disposable files and the cleanup +receipts. All fifteen original map/resource inputs and four executable/DLL +records were rehashed unchanged after cleanup. Roughly 29 MB remains under +`build/stage9`, including the archive, raw runtime/CI logs, small fixture-source +evidence and the original and final verification/cleanup receipts. Required +baseline and current builds remain at their existing locations. + +Milestone 9's review and planned validation work are complete. The all-passing +runtime acceptance criterion remains unmet for Ruby co-op recovery; that +shared path is left unchanged under the standing crossplay and feature-isolation +constraints. Its original-main reproduction establishes a pre-existing failure +class, not parity of severity or proof against an indirect timing regression. +The branch is ready for delivery review with that explicit exception, not +unconditional compatibility sign-off. Full campaigns, live split-screen, +physical Android, browser-map gameplay, official upstream-binary crossplay and +long-duration leak/performance qualification remain unverified. The explicitly +deferred shared boat and console-syntax corrections remain unfixed. No pull +request description or merge is part of this milestone. + +## Stage 10: shared checkpoint recovery investigation + +### Confirmed defect and ownership + +The game implementation remains unchanged at `175c2e945` while this +investigation adds tests and documentation. This is a shared replica-lifetime +defect: restoring an accepted checkpoint can revive a unit under its existing +full object handle. It does not depend on an MCC tag layout, filename, package +or map-specific script. The responsible implementation is the shared +`network_coop`, `network_objects`, `network_distributed` and `network_damage` +path. No MCC bypass, production refactor, changed default or protocol bump +has been introduced. + +The host's object tracker records handles, so a restored living object can +remain indistinguishable from the previously advertised object. In default +Crossplay, `distributed_client_reuses_object` accepts the same handle and +definition. `distributed_client_apply_change` can make a living copy dead, +but does not rebuild a dead copy as living. `distributed_handle_unit_state` +then refuses that dead unit before player attachment. A new living sample +alone therefore cannot restore the player's binding or inventory. + +The existing camera-profile extensions request full descriptions, reconstruct +the dead copy and refresh host snapshots after restore. Their history bundles +client replica handling with host roster/replication changes and explicitly +separates agreement versions. That history does not independently prove that +every possible client-only correction would require a new version. + +### Real-function regression and counterexamples + +[`test_coop_checkpoint_recovery.py`](../tools/test_coop_checkpoint_recovery.py) +extracts the actual create/validation/delete, player-state, player attachment, +inventory, datum and damage-handler functions. Its +[C fixture](../tools/harness/tests/coop_checkpoint_recovery.c) supplies small +object/player pools and explicit constructor, tag, graph-effect and damage-effect +boundaries. It is not a copied network implementation, a wire-layout test or a +full packet dispatcher. Behavioral constants and flags come from their owning +sources; intentionally smaller fixture capacities remain explicit. + +The default-profile case verifies the exact known handle remains dead, no +replacement construction/deletion occurs, and player/control bindings remain +absent. The existing optional profile reconstructs and rebinds in this bounded +case. Ordinary controls check healthy objects, authoritative death, initially +bound corpses, different identifiers, malformed descriptions before deletion, +allocation failure, repeated restoration, bounded retry, carried weapons and +riders, and restored inventory/ammunition/grenades. Deferred inventory coverage +establishes missing-weapon replay, not timestamp freshness. + +A second case captures a valid killing-blow payload while the first life is +bound, delivers it through the actual damage validators/handler, reconstructs +and rebinds the unit, then delivers the identical saved payload again. The +handler reaches the kill-effect boundary for the restored life. This is an +accepted-order handler reproduction; it does not claim an actual socket packet +was reordered in Ruby. Normal current-life kills must still execute, while +unknown handles and malformed numeric/tag/node data remain refused. + +Both unresolved outcomes have narrowly typed, strict expected failures with +dedicated native statuses and exact markers. Compilation errors, unrelated +assertions and unexpected exits remain failures. Correct recovery returns +success and becomes strict XPASS, requiring review of the expected failure. +Eight deliberate mutations of generated function copies confirm the tests +detect lost validation, identity checks, attachment, weapon/rider preservation, +deferred inventory application and damage replay. Production files are never +mutated. The new suite is included beside the existing checkpoint tests in +the Build workflow. + +### Ruby runtime observation + +The unchanged Windows release executable has SHA-256 +`816055002eeb8f5434ec78d5dad817e5397d443e8ccb58e66d9d852e755cafbb`. +Its matching PDB GUID/age and relevant types/global offsets were frozen in a +small receipt. Two hidden, isolated peers loaded Workshop Ruby B40 from package +`2915693904`, used aim-only inputs, completed 900 fresh admitted ticks, and +continued for at least twenty seconds. Both recorded `opence_crossplay`. + +A bounded external observer used only the owned process handles. It read +full object identifiers, death flags, player bindings, inventory and supporting +replication state without modifying or suspending the game. Unchanged ticks, +player bindings, object headers and two matching semantic reads reject observed +races; raw reads and gaps are retained. The decoder received independent source/ +PDB review and fourteen host-only controls. This is not atomic observation +across machines and does not directly trace packet handles or executed branches. + +In `ruby-crossplay-observed-v2`, full handle `0xe53a02cb` was initially alive +and bound on both peers, then died. After logged host reverts at ticks 2095 +and 2956, the host restored that same handle alive and bound. The client +retained it as a dead, known object with no player binding. A witnessed +client death-state true-to-false transition supports receipt of an alive +state; an initially false flag would not establish that. Host-only state +caches are not interpreted as received client packets. +The affected slot is the client's own local player, as recorded by its +player name and local-player index; the full player datum also matches. + +At the first matched restoration observation, the host unit carried weapons +`0xe53d02ce` and `0xe53e02cf` with grenade counts `[4, 0]`; the client's corpse +had no weapons and `[0, 0]` grenades. Twenty-seven matched observations show +the same-handle mismatch across both restores. Their aggregate 31.33-second +span includes another host death and must not be described as one continuous +living-host mismatch. +The two sampled episodes contain 23 observations spanning 17.024 seconds +and four spanning 2.629 seconds, respectively. + +The observer accepted 912 host and 904 client samples, retaining state changes +and one-second heartbeats. Nine host and seventeen client transient samples +were rejected; the maximum gap between accepted samples was below 0.226 seconds. +The unchanged strict comparator reports **FAIL**, with alive-state divergence +at ticks 2100 and 2971 and no sample-insufficiency problem. Evidence collection +completed; recovery acceptance did not. Both processes exited normally. +An earlier sandbox attempt failed at process inventory before launching any +game and remains recorded separately. + +The separate `ruby-camera-profile-control` used the same binary, map and +input seeds with the existing `gulchce_third_person` session profile, camera +policy `forced_off` and third-person preference disabled. Both peers' explicit +environment settings are retained; the generated config file retains defaults +and is not itself proof of the active overrides. No packet-version capture +is claimed. After the authored revert at host tick 2104, the client first +had the same live handle bound with an empty inventory, then both exact +weapon handles and `[4, 0]` grenades approximately 0.110 seconds later. +The strict comparison **passed** with 1,155 drift samples and no reported +divergences or problems. It observed one revert, not full campaign recovery. + +The control accepted 772 host and 767 client samples, with thirteen/eighteen +explicit race gaps and maximum accepted-sample gaps below 0.226 seconds. +Both processes exited normally. Complete frozen file inventories, hashes, +source receipts and raw decoded reads passed verification for both sessions. +Six replay/receipt controls supplement the fourteen observer controls. +The result supports the existing reconstruction mechanism but does not +resolve its old-message lifetime hazard or justify changing profile guards. + +### Review and validation of the regression additions + +The combined test implementation, CI wiring, runtime helpers and documentation +received primary and independent review. Review corrected two drifted fixture +constants by extracting owning definitions, added initially bound-corpse and +live-to-dead controls, and ensured a future correct duplicate rejection becomes +strict XPASS. Source/PDB review checked the observer's actual layout and rejected +interpretation of host caches as received client state. No production change +or speculative reduction is justified by these findings. + +Windows validation covers the new recovery suite, existing checkpoint and +inventory tests, camera policy/wire/protocol/director checks, MCC protocol/ +checkpoint/save/network checks, the comparison judge and co-op wipe controls. +The new suite contributes 35 passes and two strict expected failures. +The broader selection finished with 236 unique passes, five platform skips +and those two expected failures, after retrying 27 existing account-link tests. +Those initially failed while generating non-CP1252 source comments, then on +MSVC's standard-`sscanf` deprecation diagnostic. Python UTF-8 and a private +compiler wrapper defining `_CRT_SECURE_NO_WARNINGS` let all 27 execute and +pass; no production or unrelated test source was changed. All failed and +passing run logs are retained. This is an aggregate of the selected checks +and the targeted retry, not a claim that the first command passed. + +The tests and workflow addition are committed as `f1a0d6e1b` and pushed to +`mcc-code-refactor`. Both fresh workflows passed on that exact revision: + +- [MCC validation, run 42419694409](https://github.com/chestahh/GulchCE/actions/runs/42419694409): + Windows adapters, reader/validator checks and hidden HUD-meter rendering. +- [Build, run 42419694396](https://github.com/chestahh/GulchCE/actions/runs/42419694396): + Linux, Windows, Android and web debug builds and their required checks. + The Linux log explicitly includes the new recovery test in the combined + camera/checkpoint command: **74 passed, 2 expected failures**. Its broader + suite reports 2,507 passes, 27 skips, twelve existing boat expected failures + and seven passing subtests. The web job passed Chromium/Firefox smoke and + room checks and the native WebRTC harness with both browsers. These are + transport checks without retail-map internet gameplay. Release steps are + skipped on this branch by the existing workflow conditions. + +The final documentation check validates 68 local links, fourteen anchors, +twelve named source functions, changed Python syntax, the CI test selection +and unchanged production scope/version constants. Subsequent documentation +commits do not change the tested implementation or test inputs; the workflows +exclude documentation-only pushes. Milestone 10 still lacks an enabled repair +and its required post-fix gameplay matrix, irrespective of successful builds. + +### Evidence preservation and cleanup + +All four owned game processes exited normally. Their 24 generated map caches, +totalling 3,070,230,528 bytes, were removed after the runs. A manifest-bound +cleanup then removed nine verified input/binary copies and 86 generated test +binaries, totalling 277,757,525 bytes. The user's original maps, Workshop inputs, +required builds, existing worktrees and saves were not removed. + +All 156 inactive runtime save/support files and 132 generated test-evidence +files were archived losslessly before removing their loose copies. Their +97,565,831 bytes occupy 1,141,882 bytes in +`build/stage10/inactive-saves-and-test-evidence.zip`, SHA-256 +`e9223e41f761769ea011651e2b66a5b2eeb504594ffa9943b3fd7900d76dce57`. +The manifest records original paths and hashes. Exact ZIP inventory, CRCs, +sizes and SHA-256 values were verified before removal and again afterward. +Raw memory records, runtime logs, source/PDB receipts and failed observations +remain available; `data/gamestate.txt` was explicitly retained as a diagnostic. + +Primary and independent cleanup review and 23 guard controls precede the +applied cleanup. The final verifier checks unchanged originals, retained loose +files, missing disposable targets, exact runtime inventories resolved through +loose files plus archive members, and all four stopped PIDs. All seventeen +original map/resource/executable records remain unchanged. Approximately 21 MB +remains under `build/stage10`, including the archive and useful diagnostic +evidence. The integrity result passes while the aggregate runtime gameplay +result remains false; archival success does not erase Ruby's default-profile +failure. The earlier Stage 9 records and archives remain untouched. + +### Compatibility decision and remaining repair work + +This section records the investigation's earlier compatibility decision. +The user subsequently lifted the old-client crossplay constraint for +Milestones 10 and 11; the fix below uses explicit agreement separation. + +The authoritative upstream check on 7 November found the relevant shared +recovery modules unchanged between pinned OpenCE 41 commit `c507cb26b` and +then-current upstream `fc9deb0b1`. Official build 334 identifies the pinned +revision, but no upstream executable was run for this investigation; no new +claim of runtime crossplay qualification is made. + +Simply removing profile guards is not justified. Recreating the same handle +does not distinguish its new life from earlier damage or inventory messages. +The source dispatcher deliberately lets ordinary reliable/unbatched damage +bypass its per-kind stale gate. Object changes have no corresponding lifetime +fence. An empty reliable damage message therefore cannot advance that gate; +the existing reverted event only stops script sounds. Ordered host delete/create +alone does not repair these old-client semantics, and broad refresh would also +detach healthy units and disturb seats and inventory. + +A narrower client-only correction using fresh authoritative descriptions and +local lifetime tracking remains a possible research direction. It has not +been proved safe against stale creates, old kills, pending inventories or +same-tick events, and must retain the old host's resend limit. It cannot repair +an unchanged old client's receive implementation in the reverse host direction. +This is a specific unresolved contract, not a claim that all client corrections +are inherently incompatible. + +At the end of this investigation, Milestone 10's repair remained **open** under +the crossplay condition. Proceeding required either a demonstrated compatible +lifetime/recovery contract or an explicit scope decision permitting updated +peers with agreement separation. The user subsequently chose the latter, as +recorded below. The original failures and meaningful regressions remain; +the investigation's tests and optional-profile observation alone did not +establish default recovery, all-map compatibility or completion of the +post-fix join/rejoin, transition, platform and transport matrix. + +## Stage 10: shared checkpoint recovery fix + +The user authorized incompatible old-peer separation on 7 November 2026 for +Milestones 10 and 11, with Milestone 10 implemented first. This supersedes the +prior crossplay blocker, without relaxing map-family ownership, authority, +validation or cleanup. Console-syntax work remains deferred and the shared +boat implementation remains separate. + +### Design and evidence + +The earlier real-map observation and extracted-function failures establish +two shared defects: a host restores a living object under a full handle that +the client still owns as a corpse, and a previous-life kill can act on a +reconstructed object with that same handle. Both paths use the shared co-op +replication contract; neither depends on an MCC layout, map identity or authored +workaround. The repair therefore belongs in `network_distributed`, +`network_objects` and `network_coop`, with existing MCC-owned cache cleanup +retained through `mcc_network_new_game`. + +Each distributed gameplay header carries a 32-bit checkpoint epoch. The host +advances its nonzero epoch outside saved game memory on new maps and restores. +Clients adopt only an exact, reliable, nonbatched host boundary, before any +fresh object snapshot. Message time alone cannot distinguish a restore at the +same tick; independent per-kind clocks also cannot protect a new object life +against a later-arriving reliable kill. Epoch checks precede message clock and +gameplay handling. A late joiner's reliable ready request is the narrow +exception: it may solicit the rate-limited current boundary/snapshot, but +contributes no clock or prediction evidence. + +The ordered snapshot must finish before the client receives or sends gameplay. +This prevents a current-epoch kill overtaking an earlier live description. +Only the first validated description of a slot may reconstruct its old corpse; +a later same-epoch resend must preserve a newly killed unit. Full snapshots +also carry reliable ordinary inventories, including empty ones: the existing +periodic sender deliberately stops sending empties after three seconds and +cannot clear retained future-world equipment after a slow snapshot. The +existing serializer and inventory lifecycle are reused; that periodic +optimisation remains. MCC extra grenades/campaign state remain independently +owned periodic updates. The ordered end marker does not prove every object +was constructed; failed creation retries remain required. + +Transient input, prediction, inventory, death, animation and queued effect +history is reset. Connection identity, current roster and object ownership are +preserved. The host immediately sends fresh descriptions; a validated live +description reconstructs a dead replica through the normal delete/construct +lifecycle, while healthy replicas remain. Host-known carried weapons and +riders retain their established detach/reattach handling. Current-roster +restoration and dead-replica recovery no longer depend on camera permission. + +Inspection found another old-world producer: client projectiles and delayed +effect parts can create a fresh hit report after adopting the new epoch. The +client discards its predicted projectiles through normal deletion. The small +`effects_discard_gameplay` service uses the same validated object/damage part +classes as `effect_generate_part` and normal `effect_delete`, including later +events; harmless visual-only effects remain. Its data and lifecycle are private +to `effects.c`, so this cannot be implemented safely by manipulating effect +storage from an MCC module. Host checkpoint projectiles/effects are retained. + +Base agreement 32714, MCC 66 and camera 32716/32717 separate these semantics +from earlier clients. A version field appended to the ordinary join request +is checked before admission: advertisements alone did not protect direct +joins. The default UI label is now GulchCE Standard; the stored +`opence_crossplay` token is retained for configuration continuity. This does +not claim compatibility with OpenCE 41 or an untested future upstream release. + +### Implementation and preliminary evidence + +Historical failures and archives under `build/stage10` are unchanged. New +private evidence is isolated under `build/stage10-fix`. The original executable, +PDB and SDL library were copied and authenticated before rebuilding. Workshop +Ruby B40 and Mercury originals remain read-only; eight bounded Xbox/CE setup +files occupy 403,621,461 bytes in the isolated data folder. + +The first implementation is committed and pushed as +`6666464c12c9fcc8f446cc21a324cee6f6096a61`. Its Windows portable release build +uses `--portable --release --pgo=off --lto=off`. The retained runtime candidate +has PE/PDB GUID `693AC064-21FC-7FD0-4C4C-44205044422E`, age 1; the exact +executable/PDB hashes, nine globals and ten decoded layouts are authenticated +in `build/stage10-fix/symbol-receipt-v3/layout.json`. It was built immediately +before the commit from the same gameplay sources. CI builds the committed +revision independently. Earlier candidate receipts remain historical evidence. + +The first checkpoint, recovery, retried-inventory and epoch selection passed +**82 tests**. Seven epoch tests extract the production dispatcher through its +gameplay-handler switch, preserving framing, direction, batch recursion, +simulation clocks and stale-message handling. Final gameplay handlers are +observation stubs and some entry-size constants are mocked; this is not a whole +network stack. The separate lifecycle fixture executes actual object +replacement, player binding, inventory and damage-handler paths. It passes the +two former strict expected failures as ordinary regressions. + +Controls include old/new messages at the same tick, reliable old kills and +inventories, malformed boundaries and markers, serial rollover, a current-life +death followed by a late live description, outgoing-send suppression and packer +discard, and identity/build retries. An actual snapshot serializer/replay test +delays a retained healthy replica's empty inventory beyond the old three-second +resend window; its future weapons/grenades are cleared before the ordered end +marker. A 123-unit case crosses the real inventory batch limit. Actual client +tick checks keep readiness/retry work active while preventing unsynchronized +local ammo history from rejecting that authoritative inventory. Mutation +controls demonstrate that the guards, empty inventory and later-event effect +cleanup matter. Host checkpoint effects and harmless visual effects are retained. + +The version/admission and related wire selection passes **91 tests**; workflow +and menu/protocol selection passes **67**. These are separate selections, not +an assertion that their totals are unique. The real join codec/field table +establishes a 348-byte structure and 349-byte encoded packet, rejecting the old +codec, missing suffix bytes and wrong explicit agreement before host admission. +Legacy fixtures now extract the owning distributed header instead of retaining +an obsolete eight-byte copy. Earlier failed runs are retained: one related-test +run still used hard-coded MCC message numbers, and initial Windows fixture +compilation exposed encoding/CRT declaration issues. Targeted corrected runs +pass; those first commands are not relabelled successful. + +The first full Linux job on `6666464c1` found one further stale producer: +`tools/system_link_bots.py` still emitted the old 346-byte join payload. The +engine codec expected 348 bytes. That job recorded 2,506 passes, 27 skips, +twelve existing boat expected failures, seven passing subtests and this one +failure. Follow-up `4fdaedd66017fd17385a0d471855375837776992` updates the utility +to read the canonical agreement and append its two bytes. Its existing test +now checks their value/order and preservation of the account fields as well as +all six message sizes. The failure was reproduced locally before correction; +the bot and wire-format checks then passed. This utility deliberately emits +only system-link updates, so it has no distributed-header/epoch producer to +convert. The follow-up changes no game, build or web-site inputs; runtime +artifacts remain explicitly bound to `6666464c1`, with that two-file source +equivalence recorded, rather than being relabelled as a later build. + +Primary and independent combined review covered the production modules, +source additions, all callers of the changed header filler, test fixtures, +admission/version integration, generated labels and reader documentation. +Review identified and resolved the outgoing gameplay window, empty inventory +resend limit and delayed gameplay-effect producers before the final focused +checks. Existing object ownership, failed-create retry and MCC-owned sidecars +remain. No line-count or speed improvement is claimed for this correctness fix. +The explicit costs are four extra bytes per distributed header and an 8,192-byte +per-slot recovery-eligibility array at the configured object capacity. Full +ordinary inventory snapshots add bounded reliable traffic when a snapshot is +sent. Existing resend rate limits and the periodic empty-inventory cutoff +remain; there is no new per-frame scan or perpetual empty-inventory resend. +These are required correctness costs, not a claimed bandwidth optimisation. + +The first implementation's default-profile Ruby B40 and Mercury runs both pass the unchanged strict +comparison, two controlled wipe sequences and raw-memory replay. Ruby supplies +2,194 drift samples, with maximum drift 0.006164 and no reported divergences; +Mercury supplies 1,884 samples with zero measured drift. Both peers recover +living player bindings and ordinary inventory after restores. Ruby's same +client handle `0xe53a02cb`, which remained a corpse in the pre-fix observation, +is alive and bound after each observed new checkpoint epoch. The separate +host-authoritative player restores/spawns also acquire matching handles on both +peers. Ruby observes four restores in total, including authored recovery; its +three-reverts-per-minute fallback remains in the logs. Each controlled sequence +requires a new revert and 300 fresh recovered ticks, but this does not prove +every restore was immediately caused by its preceding kill command. + +The retained observer performs bounded double reads with explicit race gaps; +cross-peer pairing is asynchronous, not atomic or a packet trace. Both runs' +complete inventories, source/PDB receipts and raw reads verify, with no +qualifying same-epoch dead-client/live-host window. This does not establish +the absence of all transient states. A client death-cache reset at an epoch +boundary is not evidence that an alive packet was received. + +### Completing the transfer boundary + +Final review found a further producer path before sign-off. Client game ticks +continue while the ordered snapshot arrives. A retained living unit can create +a projectile or delayed gameplay effect after boundary cleanup; ordinary +remove-own-object cleanup excludes projectiles. Its later impact can produce +a current-epoch report after the marker. Host ownership, weapon/rate and +geometry checks do not universally reject that report, because they do not +identify the projectile's generation. This is a source-established lifetime +gap, not a claim that it caused one of the earlier real-map failures. + +The new real-function regression first fails on the surviving partial-transfer +projectile. The correction retires client gameplay effects/projectiles again +at the first validated ordered marker, then clears damage queues and provisional +prediction/input histories. It preserves restored objects, inventories and +ownership. It also preserves snapshot receive timestamps: erasing them would +let an older same-epoch inventory datagram evade the stale-message check. +`distributed_reset_checkpoint_state` now takes an explicit receive-history +reset flag; new maps/epochs clear it, snapshot completion retains it. Duplicate +markers leave current gameplay producers and prediction work intact. + +The final focused selection passes **87 tests** after combined review. The +expanded recovery fixture runs actual recursive projectile deletion, damage +reset/report sending and inventory/binding paths; creation and transport remain +explicit fake-world boundaries. Its three new mutations omit producer cleanup, +omit damage reset or repeat cleanup on duplicate markers, and each fails the +behavioral assertions. The dispatcher test uses the actual common reset: +partial prediction/input state is cleared, a received inventory at tick 100 +still rejects tick 99 after completion, and duplicate markers preserve fresh +work. Existing real effect selector/deletion tests cover delayed gameplay +parts separately. This is not a whole-engine delayed-effect reproduction. + +The rebuilt Windows candidate has PE/PDB GUID +`FB4E538B-B88F-E0C9-4C4C-44205044422E`, authenticated in +`build/stage10-fix/symbol-receipt-v4/layout.json`. The preceding executed +candidate was frozen and hashed in `prior-candidate-6666464` before rebuilding; +its earlier runtime and CI results remain pre-final evidence. The final native +executable is a local pre-commit build from the final gameplay sources, SHA256 +`66c6565fbe908a1b489389a0e68af968d26d76985a3ecec31cee60569744dc04`; +the PDB hash is +`14a48f17ffc1437b05ed02b9c16db5fbff0ed1d9ea4b78863b79cad255f796bd`. +This is not described as a clean-checkout CI native binary. + +### Final platform and runtime evidence + +Both exact-revision workflows for +`67968518222f3ee59361670323cfcd48486fa97e` completed successfully: +[Build 42427426028](https://github.com/chestahh/GulchCE/actions/runs/42427426028) +and [MCC 42427426029](https://github.com/chestahh/GulchCE/actions/runs/42427426029). +`build/stage10-fix/ci/final-6796851.json` and retained decoded job logs record +Linux, Windows, Android and Web builds, named test selections and artifact +digests. Linux reports **2,507 passed, 27 skipped, twelve existing boat expected +failures and seven passing subtests**; its checkpoint/camera/join selection +passes 107 and its sanitizer selection 38. MCC readers report 1,811 passes and +19 skips, with 38 sanitizer passes and 36 meter GPU renders. The Windows +adapter selections report 221 passes; 42 passes/one skip; 1,754 passes/16 skips; +and 38 passes. These selections overlap and are not an additive distinct-test +total. Android touch/gyro and importer checks, Windows COFF/LTO and corruption +controls, and Web build checks also pass. Platform success is not device or +full-campaign gameplay qualification. + +Final review corrected an obsolete actor-message comment promising upstream +crossplay in `network_distributed.h`. Commit +`7ed70168ac875ce28e115d5264e8036f55a22392` changes only that comment; the wire +record and gameplay remain the implementation validated at `67968518222f`. +The follow-up also passes +[Build 42430388710](https://github.com/chestahh/GulchCE/actions/runs/42430388710) +and [MCC 42430388612](https://github.com/chestahh/GulchCE/actions/runs/42430388612), +including the same named Linux/MCC selections. Its WebRTC echoes return 320/320 +for each browser; the intentional-loss controls return 689/960 for Chromium +and 714/960 for Firefox. `build/stage10-fix/ci/final-7ed7016.json` retains exact +revision/job conclusions, eight decoded logs and six artifact digests/sizes +matched to upload logs. No follow-up artifacts were downloaded or executed; +runtime artifacts retain their original revision and build provenance. + +The final native candidate repeats default-profile checkpoint recovery on +Ruby's Rebalanced B40, Mercury and Xbox B30. Each passes the unchanged strict +judge, two controlled wipe/recovery sequences, normal owned-process shutdown +and independent replay of authenticated process-memory reads. The final +`ruby-default-v2`, `mercury-default-v2` and `xbox-b30-v2` receipts record: + +| Map | Paired state seconds / position pairs | Authoritative drift samples | Maximum drift | Observed checkpoint epochs | +| --- | --- | --- | --- | --- | +| Ruby B40 | 58 / 92 | 1,958 | 0 | 1–4 | +| Mercury | 68 / 126 | 1,952 | 0 | 1–3 | +| Xbox B30 | 70 / 126 | 2,019 | 0.000003 | 1–3 | + +Recovered player bindings and ordinary inventories are observed; none of the +replays finds a qualifying same-epoch dead-client/live-host window. B30 logs +two alive and two death sample mismatches within the unchanged judge's limits; +passing does not mean every asynchronous sample is identical. Each controlled +sequence requires a new revert and 300 recovered ticks. Ruby also performs +authored recovery, so these observations do not assign every revert to its +preceding command. Bounded double reads and asynchronous pairing cannot prove +the absence of every transient state or reveal exact packet order. + +Mercury `rejoin-mercury-v2` additionally passes checkpoint capture, the first +client leaving, a replacement joining, and restoration with the current roster. +Its independent verifier pins the expected peer/name sets for all five stages, +replays both guarded reads, checks full local player/unit reciprocity and +compares shared player slots and full unit handles across peers. Player datum +salts are local: before restore the same unit `0xe4da01ac` is bound to host +player `0xec720001` and client player `0xec710001`. Restoring epoch 1 to 2 +retains the replacement `S10Rejoin`, with unit `0xe4d50001`. The captured and +final 20 MiB checkpoint images match and independently pass the MCC CRC checks. +The audit is retained in +`build/stage10-fix/reviews/rejoin-mercury-v2-verification-v2.json`. + +The final Ruby camera-protocol control also passes one controlled wipe/recovery +sequence, with 70 paired state seconds, 116 position pairs and 1,552 +authoritative-drift samples with zero measured drift. Maximum position +difference is 0.033541 and aim difference five; one alive, death and round sample +mismatch each remains within the unchanged judge's limits. Independent raw +replay observes epochs 1–3, no qualifying stale-body window, at least 300 +recovered ticks after the controlled revert at clock 2,725, and normal exits. +Both peers use `gulchce_third_person` with `forced_off` camera policy and +`HALO_THIRD_PERSON=0`: this validates the protocol profile, not shoulder-camera +rendering. + +Final Xbox BloodGulch and CE Death Island controls each pass two Slayer rounds. +Every round supplies 31 paired state seconds, 62 position pairs and 930 +authoritative-drift samples, with zero measured drift and no judge problems or +divergences; maximum aim difference is two within the existing tolerance. +The standalone transition control also passes Mercury → Xbox BloodGulch → CE +Death Island → invalid MCC refusal/menu → Ruby B40, with 150 fresh ticks per +valid map; its exact private fixture is removed. Independent raw-evidence +audits of both round controls and the transition control pass. This transition +check does not establish network map switching or campaign completion. + +Two failed final-candidate collector attempts remain failed records. B30 v1 +used `game_is_cooperative` as a network co-op gate, although stock Xbox uses +that predicate for local split-screen. Rejoin v1 incorrectly required peer-local +player datum salts to match. Its failing post-join raw pair was not retained, +so that exact failure cannot be reconstructed from raw memory. Source review +establishes that the equality gate was invalid; the v2 reads demonstrate the +valid differing salts. The narrow collector corrections pass subsequent runs +without game-code or tolerance changes. Available earlier observations, raw +reads, helpers and failed receipts are retained. + +Four old/new discovery-refusal controls also pass: Standard and camera profiles +with each side hosting. These eight processes stopped normally. Their evidence +is explicitly **pre-final**, bound to the `6666464c1` candidate; the subsequent +marker correction does not alter admission code. The independent +`admission-pre-final-verification.json` audits this attribution. These runtime +checks demonstrate discovery refusal, not forced raw old-wire injection; the +source-extracted codec/admission tests cover malformed and truncated requests. + +### Real-map native/browser transport + +The final Web artifact is the exact `67968518222f` CI build, +`halo-web-debug` artifact **13596301952**: 14,159,156 ZIP bytes, SHA256 +`af1f3217caa982a8ea138969ec0f3fc23689ee1e244b2318e759163362f8cad6`. +Its authoritative metadata, upload digest and all 24 extracted site files are +verified. It is paired with the authenticated local native build above. The +private Windows adapter uses isolated saves and browser profiles, a local MQTT +broker, real Xbox BloodGulch and at most two game instances. Retail data remains +local. Independent replay verifies raw judge inputs, source/build receipts, +bidirectional WebRTC traffic, normal native exits and 41 exported browser +save/support files per final case. + +| Final pairing | Two-player samples per peer | Drift samples / apart | Mean / maximum drift | Paired cross-log state seconds | +| --- | --- | --- | --- | --- | +| Native host, browser joins through discovery | 49 | 1,330 / 326 | 0.098554 / 109.070160 | 0 | +| Browser host, native joins by supported direct invite | 49 | 1,396 / 257 | 0.125030 / 97.919212 | 0 | +| Browser host, native discovery with look-only input | 49 | 1,330 / 21 | 0.083745 / 91.926247 | 0 | + +All three original judge results pass. The measured authoritative drift is +nonzero; the apart counts remain below its unchanged limit. However, log sample +phases fall outside the unchanged two-tick pairing bound in every case, leaving +zero paired state seconds and zero position pairs. These runs establish bounded +real-map transport and authoritative-drift coverage, **not cross-log state-field +equivalence**. Logs were not shifted, tolerances were not relaxed and tests were +not repeated to obtain favourable phase alignment. The native/native recovery +checks above separately provide matched state observations. + +The two failed preliminary Internet attempts are preserved: native-host v1 +passed gameplay/transport but failed teardown on a disappearing window; its +narrow owned-window fix was independently reviewed before v2 passed. The first +browser-host discovery attempt exited normally before joining gameplay. Its +exact quit trigger is unproved. Final direct-invite and look-only discovery +controls pass, but they use the later candidate and do not isolate that earlier +failure's cause. Their outcomes and hashes remain separate in +`build/stage10-fix/internet/final-transport-summary.json` and the independent +`reviews/internet-*-verification-v2.json` receipts. + +The `67968518222f` CI additionally passes native WebRTC echo with Chromium and +Firefox at 320/320 messages each; intentional ten-percent datagram-loss controls +return 714/960 and 698/960 respectively. Local-broker map gameplay and these echo +controls do not qualify WAN/NAT behaviour or browser checkpoint rollback. + +### Completion, cleanup and remaining limits + +Primary and independent combined review covers the resulting recovery code, +admission, integration, tests and reader documentation across the core fix and +both follow-up commits. No implementation blocker remained after the +first-marker producer correction. The obsolete interoperability comment was corrected in +`7ed70168a`. No further simplification had a demonstrated benefit: per-slot +eligibility, reliable empty inventories and the distinction between send-state +and receive-history resets each prevent a separately covered regression. +The review and raw-evidence audits are retained under +`build/stage10-fix/reviews`; no map identity selects the recovery behavior. + +At Milestone 10 completion, Milestone 11 was next under the authorized +version-separation policy: its shared boat correction had not started and the +twelve strict expected failures remained. The separate console correction was +still deferred then. Stage 11 below records their subsequently authorized and +completed repairs. + +Verified cleanup is recorded in `build/stage10-fix/cleanup-plan-final-v6.json`, +`cleanup-applied.json` and `cleanup-post-verification.log`. Across sixteen +native sessions and six Internet attempts, per-run cleanup removed **234 +generated map-cache files, 29,934,747,648 logical bytes**. Final cleanup removed +another **2,787 verified disposable files, 973,111,030 bytes**, covering private +map/site copies, duplicate executables, dependencies and fixture binaries. +A separately reviewed cleanup removed 270 dummy control fixtures (57,789 bytes), +retaining their sources and logs. Original maps, Workshop resources, the active +build, source and other worktrees remain unchanged. + +All **3,868 archived files, 6,585,303,596 uncompressed bytes**, are preserved in +`build/stage10-fix/inactive-saves-and-support.zip`: **798,147,821 bytes**, SHA256 +`4f297443ccb8432f3ca57532bea49a959ff7f972d8bd91c5cd4ba2e35f334c7f`. +This includes inactive saves and checkpoint captures, complete isolated browser +profiles and exported saves, the two preceding executed native builds and +supporting fixture evidence. Every member was verified before loose-file +removal; the archive's exact bytes were checked again before removal and after +cleanup. Diagnostics and raw observations remain available separately. +`retained-size-census.json` records approximately **952 MB** of retained evidence, +mostly this archive. No loose map copies, executables, DLLs or PDBs remain in +`build/stage10-fix`; the required active build remains outside that folder. + +The final integrity pass verifies the original inputs, active build and all +sixteen native evidence inventories. All seven raw recovery replays pass after +archival; earlier incomplete or failed gameplay attempts remain failed records. +The transport audits ran before cleanup, and their bound evidence is preserved +by the separate integrity checks; no transport rerun is claimed after removing +the private map copies. See `post-cleanup-replay-summary.json` for the replay +results and their exact archive identity. + +Earlier cleanup refusals remain recorded. They exposed retained diagnostics +outside duplicate manifests, changing unrelated PID-reuse observations and +210 empty save/profile directories omitted by file-derived planning. The final +cleanup controls pass **60 tests and 25 subtests**. Fresh process-identity proofs, +exact file inventories, contained nonlink paths and late archive-integrity +checks remain mandatory; the refused cleanup attempts removed no loose files. + +Full campaigns, live split-screen and Android-device gameplay remain outside +these bounded checks. Existing authored HUD, navigation-point and attachment +caches are not comprehensively rebuilt from checkpoint state; complete authored +campaign rollback remains unverified. The ordered marker proves ordering, not +successful creation of every replica. MCC extra grenade/campaign sidecars +remain separate periodic updates, so ordinary inventory coverage is not a +claim about every MCC sidecar. Historical failures and archives under +`build/stage10` remain unchanged. + + +## Stage 11: shared boat and console lifetime corrections + +Implementation, validation and verified cleanup are complete. The 8 November +request includes both Milestone 11's shared boat fix and the separately investigated console +syntax lifetime defect. The earlier console deferral is historical. Work stays +in the existing `mcc-code-refactor` worktree; original maps and saves are untouched. +The later request explicitly includes diagnosing and correcting Mercury's +host-driven boat synchronization discrepancy within this milestone. + +### Shared boat producer and agreement + +`update_human_boat_physics` now initializes exactly its three temporary powered +point records before the existing assignments. The native accepted-input +contract and both force consumers establish a shared producer defect. The +former MCC helper, its declaration and sole call are removed; MCC receives the +same initialized values. Other point counts, authored tags, arithmetic and seat +rules are unchanged. No persistent state or save layout is added by this fix. + +The unchanged baseline `46f8792f5e5c7642a0f729af097467f56a323ccb` fails twelve +unmasked boat cases. The expanded harness also runs the actual new-physics +linear integration and position publication, in addition to the existing old +path. It reports twelve legacy failures and twelve corresponding MCC passes +against the frozen baseline producer. With the shared correction, all 64 boat +checks pass. Guard-removal proof cases have become ordinary regressions and +negative controls that reintroduce the former MCC guard; their finite/NaN, +active-control, scratch-boundary and point-count coverage remains. + +The combined local boat and neighboring vehicle/seat/damage/color selection +passes 116 tests. Updated admission, camera, codec and CI-selection checks pass +87 tests. These are controlled real-source harness checks, not full game or +upstream compatibility results. The initial boat correction used shared +agreement 32718, MCC 67 and camera 32720/32721 to exclude incompatible older +peers; its wire manifest changed only +these agreement values. The previous agreements are explicitly rejected by +both discovery/session tests and the direct-join handler tests. + +Private evidence is under `build/stage11-fix/boat` and +`build/stage11-fix/admission-neighbors.log`. The preserved M10 native executable +has SHA-256 `66c6565fbe908a1b489389a0e68af968d26d76985a3ecec31cee60569744dc04`. +It is the earlier local portable release built from the final M10 gameplay +sources, not an exact-revision CI build. Its executable, PDB and SDL DLL were +copied and verified before rebuilding. + +### Console baseline and affected map selection + +The preserved executable reproduces the console lifetime defect on Xbox Blood +Gulch, Custom Edition Death Island and Workshop Ruby B40. Each saves inside a +sleeping temporary expression, lets it finish, waits externally through at +least two collection opportunities, compiles a replacement command and loads +the unchanged core. All three accept the saved image and then report an expired +script-node error, with abnormal exit. These are failing reproductions, not +passing validation. Raw logs, exact commands and cores are retained separately. +The corrected runtime probes require replay of the captured marker, rather +than accepting mere absence of an assertion. A separate baseline Xbox run +also demonstrates overwritten sleeping literal text without any restore. + +A bounded read-only survey of 152 installed MCC version-13 maps found the +three-point friction case in Mercury2 (`3021510694`) and B30 (`3512468479`). +Useful control boats in other packages have rear powered-point flags `0x08` +(lift only), while these affected boats use `0x0a` (lift and friction) on all +three points. Ruby's inspected maps contain no boat-controller tags. This +survey selects runtime cases; it does not establish loading or gameplay success. +The inspector, input hashes and authored tag/placement records are retained in +`build/stage11-fix/validation`. + +### Pre-clock boat observations and synchronization failure + +The original affected Workshop B30 map runs unchanged on two peers for 1,200 +fresh ticks. Read-only PDB-bound observations retain 351 host and 342 client +samples, 39 paired seconds and zero paired position difference. Both processes +exit normally. The boat remains stationary, with no throttle or driver samples; +this proves finite synchronized presence, not active boat physics or driving. + +Mercury's existing named boat `d1` belongs to its credits BSP. A private fixture +instead binds that name to an existing gameplay boat through three 16-bit +scenario name/index fields. Changes to the 99,205,136-byte map are confined to +those six bytes; powered-point flags, physics, vehicle placement and scripts +are unchanged. The original Workshop map and resource files are hash-verified +and untouched. +The probe lets the authored intro finish and enters its ordinary BSP transition +volume, allowing the map's own cleanup and transition ordering. Earlier forced +BSP jumps caused baseline object-cluster assertions; those setup failures are +retained and are not passing controls. A later failed setup also exposed an +incorrect fixed host/player-slot assumption; the runner now derives each +peer's local slot and verifies the shared player identities before seating. + +Baseline and corrected builds each exercise both client and host driving for +1,200 ticks per role, using ordinary pad input and read-only observations. +The candidate retains finite occupied boat state, forward/reverse controls, +movement and 339 fresh host-accepted client prediction samples. Client driving +passes the unchanged boat comparison: 40 paired seconds, maximum position +difference 0.673 world units (baseline: 39 seconds, 0.468). The replacement +producer is identical to the prior MCC producer after normalizing the removed +guard/helper call to its existing zero-initialization operation. + +**Both runs fail the strict host-driven position comparison.** Baseline has +three consecutive sampled seconds above the unchanged one-world-unit limit, +with a maximum of 1.550; the candidate has two, with a maximum of 1.332. Each +failure interval has a client clock approximately five or six ticks behind +the contemporaneous host and observations about 0.219 seconds apart. Nearby +wall-time observations agree much more closely, but they do not replace the +required tick comparison. One candidate failure is an exact-tick pair, so this +cannot be dismissed as nearest-sample rounding. Both original strict verdicts +remain failed. No retry for favorable timing, shifted logs or relaxed tolerance +is used to declare a pass. + +The shared control initialization is established independently by the failing +legacy harness and passing corrected cases. These pre-clock runtime runs establish +preserved finite MCC control production, occupied driving and client prediction +within their observed windows. They leave the pre-existing host-driven network +position discrepancy unresolved at that revision. The later clock correction +and its separate acceptance result follow below. The fixture, runner controls, +raw observations and independent audits are +under `boat`, `runtime` and `reviews` in the Stage 11 evidence root. + +### Shared recovery from small clock delays + +The preceding failed verdicts remain historical failures. Further diagnosis +pairs nearby read-only observations within twenty milliseconds, solely to +measure clock offset; it does not retime boat positions or change the gameplay +comparison. The original and boat-corrected builds start near the same clock, +then acquire seven-to-eight-tick offsets around Mercury's authored BSP +transition. Five-to-six-tick offsets persist during the later driving windows. +The retained observations do not identify every loading-time contribution to +the initial stall, but they establish that the offset is real and persistent. + +The responsible shared recovery contract accepts the host's reliable full +game time and never rewinds the client. Its existing handler corrects ongoing +delays only when they exceed thirty ticks. A reproduction extracting that +actual handler and the actual `game_time_update` loop preserves each five-, +six-, seven- and eight-tick delay across three hundred frames, despite reliable +host updates every second. The first-update and greater-than-one-second +corrections still work. This is a shared clock recovery defect, independent of +map format or boat data, rather than a Mercury compatibility rule. + +`game_time_synchronize_distributed` records a bounded, reliable host target +outside the saved world. On a running client, the existing frame loop may +perform up to its normal number of additional ticks, retaining the thirty-tick +total frame cap. It stops adding ticks at the last known host target and never +extrapolates it. Each added tick runs normal physics/scripts, the rendering +snapshot and the distributed network callback; fractional frame time remains +unchanged. First-update and large-stall hard synchronization remain separate. +The transient target is cleared on initialization, map disposal, game end and +explicit clock rebasing. Menus, local games, hosts, held clients, pauses and +zero game speed receive no extra ticks. + +The actual-source frame harness passes 47 checks: 37 behavior/lifecycle cases +and ten selective faulty implementations that compile and are rejected by a +behavioral assertion. The combined clock, boat, vehicle, co-op recovery, +checkpoint-epoch, MCC network and pause selection passes 233 tests, including +those 47. Eleven admission/codec checks pass with shared agreement 32722, +MCC 68 and camera 32724/32725. Previous agreements remain refused, including +direct joins and composed MCC/camera envelopes; the wire manifest changes +only the agreement values. The Windows portable release build succeeds with +the existing Expat import warnings. The completed platform and loaded-world +checks for this timing change are recorded below. + +The pre-clock native build is preserved byte-for-byte under `baseline-clock` +with its executable/PDB/SDL receipt. A fresh `mercury-clock` fixture has the +same map bytes as the earlier name-only fixture; the historical fixture and +cleanup receipt are not overwritten. + +On `6096b0b4f969ad24c4f664cf90f276593ed244ce`, Mercury passes both driving +directions with the original two-tick pairing window, one-world-unit position +limit and two-consecutive-sample failure rule. Client driving has 39 paired +seconds and a maximum position difference of 0.278; host driving has 36 and +0.343. All 1,353 raw driving observations retain finite occupied state and +the correct player/driver/passenger identities. The host accepts 325 distinct +fresh client boat predictions. Both processes exit normally. + +The authored BSP transition still produces a seven-tick clock delay. The +client recovers to within two ticks in 3.192 seconds and remains within that +bound for the remaining 668 nearby wall-time observations; both driving +windows have median clock offset zero. Raw frame observations include actual +two-tick catch-up frames. These clock observations explain the correction; +the unshifted simulation-tick comparison above is the driving acceptance gate. +A receipt proves that the runner, observer, input implementation and comparator +are byte-identical between the failed pre-clock and passing clock runs. + +The broad on-foot comparison remains **INCONCLUSIVE** because the driving +scenario supplies only twelve qualifying on-foot drift ticks. It has no +persistent divergence across 84 paired seconds, but one isolated position +mismatch reaches 1.073. That broad result is not relabeled as passing; the +separate boat comparison supplies the occupied-driving evidence. +See `runtime/boat-6096b0b4f-mercury-clock`, +`reviews/boat-6096b0b4f-mercury-clock-clock-followup.json` and +`reviews/6096-mercury-unchanged-method-receipt.json`. + +The unchanged original Workshop B30 also passes its 1,200-tick static boat +control on this build: 342 host and 340 client observations in the fresh +window, 39 paired seconds and zero position difference. Independent replay +checks both guarded reads for 1,402 total observations and all 107 frozen +evidence files. Movement, velocity, throttle and driver counts remain zero; +this supplies synchronized static presence, not additional driving coverage. +The original Workshop inputs are unchanged in both tests. Both private +Mercury fixtures have been removed through their separate verified cleanup. + +### Shared console ownership + +The fix snapshots the existing syntax allocator with the saved threads and +gives live commands bounded, separately owned source text. It does not discard +restored console threads or retain temporary syntax forever. The saved block +is 918,568 bytes on the supported ILP32 targets: 32,767 syntax records, allocator +metadata, 256 root handles and 256 source slots of 1,024 bytes. Native maps keep +their existing 19,001-node allocator limit. The block fits below MCC's separately +reserved thread and checkpoint storage without enlarging the CPU or save image. +The added allocation changes the existing allocation checksum, so old-layout +saves are refused instead of being interpreted using incomplete ownership data. + +Before copying an image over live state, validation checks saved allocator +bounds, live frame references, source ownership, terminated string storage and +call structure. Permanent map syntax must match the loaded map. Inactive +damaged scripts already disabled by map admission do not become a new reason +to refuse a checkpoint. The existing map command permissions are retained. +The [reader walkthrough](reading/console_checkpoints.md) documents the concrete +flow, ownership, lifecycle and limits. + +The pre-clock Windows console matrix passes **14 cases**, comprising **17 normal +process exits and 28 independently recounted marker observations**. Xbox Blood +Gulch, CE Death Island and Ruby B40 each pass sleeping-literal isolation, two +distinct checkpoint captures/reverts, exact core replay in a fresh process, +and clean old-layout refusal. Ruby and Mercury additionally pass saved temporary +MCC `abs_integer` calls. Positive image operations continue for at least 150 +fresh simulation ticks. Distinct process IDs, exact image hashes, monotonically +advancing tick windows and output ranges are checked; command echoes do not +count as execution. These checks include the completed console fix and saved +source-owner guard. They do not establish full campaign or every-map behavior. + +The matrix used `4f645bd110cbc01ffb7a793533091ebfba84442b`. The test-only follow-up +`ea2bef9bbd9fb9c8e18a2c9b718326c99dfce7de` has identical `source/` and `port/` +trees. The local rebuild reports no work, and both receipts authenticate the +same executable, SHA-256 +`74209dea04310a669735f877e47ec95e02a02daca165711083fb7ffc23e135dc`, with PE/PDB +identity `05AB2D31-6861-97E2-4C4C-44205044422E`. Runtime provenance remains tied +to the revision actually executed; this source-equivalence proof does not +relabel it as a different CI build. See `console/final-console-audit.json`. + +The focused selection passes **321 tests**, including 111 console cases with +seven selective fault controls, real core-header/load checks, MCC scripts, +checkpoint/deselect coverage and nine co-op wipe cases. The latter fixture was +missing the newly called capture service in the first Linux CI attempt; its +eight compilation failures remain recorded. The corrected fixture additionally +checks capture failure and later success on native and MCC paths. Failed +capture cannot publish a new image or roster, or reach MCC capture; it clears +the valid-checkpoint flag and uses the existing wipe respawn fallback. A later +successful save publishes the replacement and permits team reversion. The +final boat, vehicle, recovery, admission and wire integration selection passes +another **290 tests**; these selections overlap and are not summed as unique +coverage. + +Old-layout cores are refused with map, player count and map checksum unchanged; +the allocation checksum is the only mismatch. The earlier inherited assertion +on that mismatch is removed, retaining the diagnostic and false return before +image publication. All three runtime refusal cases continue for 150 fresh +ticks, execute another command and exit normally. Existing saves are preserved, +not migrated; a save made with the new allocation layout is required. + +The allocation ledger and ILP32 fixture both establish the 918,568-byte addition. +A conservative baseline ledger sum of 18,176,716 bytes gives an upper bound of +19,095,284 bytes afterward. Within the unchanged 20,709,376-byte CPU arena, +reserving 1,054,792 bytes for MCC threads and the maximum 197,492-byte other +MCC tail, with alignment, leaves a conservative 361,804-byte gap. The ledger +includes GPU allocations and therefore overestimates CPU use. The source-bound +calculation is `console/capacity-and-source-receipt.json`. + +Text ownership remains bounded to 256 slots of 1,024 bytes. Live globals and +unaligned stack values are scanned conservatively; a coincidental pointer-like +integer can retain a slot. Exhaustion reports a diagnostic instead of replacing +live text. Reclamation occurs on command compilation, not each simulation tick. +Validation covers the new syntax/source ownership and reachable frames; it does +not comprehensively harden opaque inherited evaluator payloads or every field +of arbitrary native saves. + +Earlier probe failures remain separate evidence. Newline-free console output +could concatenate a marker with the next command echo; positive execution is +now checked before sending that command. An initially invalid silent delimiter +was replaced with a valid conditional print whose unused marker must remain +absent. Neither preliminary result is substituted for the final matrix. + +### Map lifecycle, platform builds and final integration + +The following integration results precede the additional shared clock fix; +their exact tested revision remains recorded below. + +The single-process lifecycle control passes Mercury → Xbox Blood Gulch → +CE Death Island → bounded invalid MCC input → menu → Ruby B40. It arms one +sleeping command before each active-map transition and checks new commands +afterward. Independent replay verifies that all three old markers remain +absent through destination tick windows 60–630, 60–1,050 and 60–1,470, beyond +their old absolute wake bounds of 540, 960 and 1,380 respectively. Failed-load +refusal, menu responsiveness and later Ruby execution are ordered in raw logs. +All 50 frozen evidence files are verified, the process exits normally and the +owned invalid fixture is removed. The runner has eleven offline controls; +three additional independent mutations reject missing armed output, a late +concatenated marker and insufficient deadline coverage. + +Final two-peer checkpoint/recovery runs each capture a fresh checkpoint, +observe at least 900 ticks plus another twenty seconds, and perform two +controlled team wipes with at least 300 fresh recovery ticks after each. +Independent raw-memory replay verifies actual live player handles and their +player attachments, inventory observations, checkpoint epochs, receipt +identities and normal process exits. Reversion uses the game's current +checkpoint, which authored scripts may replace; these runs do not prove that +each wipe used the initially retained image. The unchanged comparator reports +no divergences or problems: + +| Map and session profile | Paired state seconds | Authoritative drift samples | +| --- | ---: | ---: | +| Ruby B40, Standard | 59 | 2,214 | +| Xbox B30, Standard | 81 | 2,034 | +| Mercury2, Third Person agreement with camera forced off | 81 | 2,046 | + +The Mercury profile check validates the separate session agreement and shared +recovery path; the disabled camera does not establish visual third-person +behavior. Raw evidence and independent replay receipts are retained under +`runtime/recovery-ea2bef9bb-*` and `validation/*-independent.json`. + +Xbox Blood Gulch and CE Death Island each also complete Slayer → lobby → +Slayer with two hidden peers and normal exits. Separate raw log slices preserve +each round's clock. Both Xbox rounds have 31 paired seconds and 930 drift +samples. CE's first round has only 12 paired seconds and 533 drift samples; +its second has 31 and 930. The original judge passes all four rounds without +divergences/problems, but CE's first round misses the independent twenty-pair +coverage gate. Its independent audit therefore records that coverage limit, +not a full-coverage pass. The second round provides the stronger CE comparison; +no retry or shifted log substitutes for the first round. These are same-map +round transitions, not disconnected-client rejoin tests. + +The pre-clock test-bearing revision `ea2bef9bbd9fb9c8e18a2c9b718326c99dfce7de` +passes [Build run 42439268449](https://github.com/chestahh/GulchCE/actions/runs/42439268449) +on Windows, Linux, Android and Web, and +[MCC run 42439268534](https://github.com/chestahh/GulchCE/actions/runs/42439268534) +for readers, HUD rendering and Windows adapters. Linux's broad invocation +reports 2,631 passed, 27 skipped and seven passing subtests; all subsequent +commands in that job also complete, including 107 checkpoint/network cases +and 38 controller/HUD cases. Skipped asset-dependent cases are not represented +as runtime passes. The earlier failed fixture-compilation run is retained. + +Web CI passes native WebRTC echo with Chromium and Firefox at 320/320 messages +each. Intentional ten-percent datagram-loss controls return 676/960 and 723/960 +respectively. These are transport controls, distinct from actual-map gameplay. +The complete logs, metadata and source identities are retained under +`build/stage11-fix/ci`, summarized in `summary-final-ea2bef9bb.json`. + +### Combined clock revision: final native checks and platform CI + +The complete gameplay implementation at +`6096b0b4f969ad24c4f664cf90f276593ed244ce` passes the combined implementation +review and 462 final focused tests, with no skips or failures. These include +64 boat, 111 console-lifetime and 47 clock cases, plus neighboring vehicles, +co-op wipes/recovery, native/MCC checkpoints, epochs, pause, saved-game routing +and protocol admission/codec coverage. These overlap earlier selections and +are not added to them as unique coverage. The receipt records the exact +command, per-module counts and 128 source/test hashes. + +The separately invoked `tools/test_checkpoint_timing.py` CLI is not collected +by pytest and is not one of those 462 passes. Its existing fake world still +names `game_safe_to_save`, while the extracted caller now uses +`coop_scripts_safe_to_save`; the standalone invocation fails to compile. +The caller change predates this milestone. A private one-line fixture +correction passes the timing assertions at four frame rates, and four +selective faulty implementations are rejected by those assertions. The +one-line fixture correction and explicit Linux CI invocation are now applied; +the final Windows CLI run passes at 30, 60, 120 and 990 frames per second, +including its timeout, rewind and pause assertions. The completed Linux CI log +also executes the standalone command and passes all four frame rates. The +original failure is retained in +`reviews/final-checkpoint-timing-6096.log`. + +The review confirms that all twelve previously reviewed boat/console source +files are unchanged by the clock work. Local and host clock behavior remains +unchanged in the extracted-source checks; only distributed clients catch up. +The earlier 17-process console matrix and map-family lifecycle run therefore +retain their original provenance rather than being represented as reruns. +The following new paired recovery tests exercise the combined implementation +with the same fresh checkpoint, two-wipe and minimum tick-window requirements: + +| Map and session profile | Paired state seconds | Authoritative drift samples | +| --- | ---: | ---: | +| Ruby B40, Standard | 60 | 2,175 | +| Xbox B30, Standard | 66 | 1,998 | +| Mercury2, Third Person agreement with camera forced off | 71 | 2,111 | + +Each passes independent raw replay, live player-unit/attachment and inventory +checks, checkpoint epochs and normal exits, with no comparison problems or +divergences. Maximum paired position differences are respectively zero, +0.003742 and 0.029275. The earlier limitation about authored replacement of +the current checkpoint still applies. The Mercury camera remains disabled; +this is agreement/recovery validation, not a shoulder-camera rendering test. + +The new Xbox Blood Gulch and CE Death Island Slayer → lobby → Slayer controls +each supply **31 paired seconds and 930 drift samples in each round**, with +no problems or divergences. Xbox's maximum paired position difference is +0.002449 in each round; CE's is zero. Both have zero authoritative drift +differences. Both peers have one +actual clock reset, a fresh 60–960-tick window in each round and normal exits. +These complete the twenty-pair coverage requirement independently of the +earlier limited CE run; that historical twelve-pair result remains unchanged. +Evidence is in `runtime/*6096b0b4f*` and the corresponding independent audits +under `validation/`. + +The portable Windows release executable has SHA-256 +`da8fa9004787ace509dddd61480f739a66e27a4c8193c953254be49bd580c76f` +and PE/PDB identity `E5251594-AC49-CA85-4C4C-44205044422E`, age one. +The build retains `--portable --release --pgo=off --lto=off`. +[Build run 42443616551](https://github.com/chestahh/GulchCE/actions/runs/42443616551) +passes Windows, Linux, Android and Web debug builds, and +[MCC run 42443616589](https://github.com/chestahh/GulchCE/actions/runs/42443616589) +passes readers, Windows adapters and 36 actual GPU-render cases. Linux's broad +selection reports 2,678 passed, 27 skipped and seven subtests; subsequent job +commands also pass. Skipped asset cases and branch-skipped release jobs are +not runtime validation. Web's native WebRTC controls return 320/320 messages +with both Chromium and Firefox; the deliberate datagram-loss controls return +710/960 with each. These transport controls remain distinct from loaded-map +gameplay. `ci/6096b0b4f969-final-receipt.json` binds fourteen retained evidence +files to these exact jobs and revision. + +The test-only follow-up `cafddf5d3cd77827c93feca1c9f967ad23daed35` passes +[Build run 42448770208](https://github.com/chestahh/GulchCE/actions/runs/42448770208) +and [MCC run 42448771192](https://github.com/chestahh/GulchCE/actions/runs/42448771192). +All four platform debug builds and the three MCC jobs pass, including the +standalone checkpoint timing command in the completed Linux log. Its broad +Linux selection again reports 2,678 passed, 27 skipped and seven subtests; +MCC retains 36 actual GPU-render passes. WebRTC controls return 320/320 with +both browsers; deliberate-loss controls return 714/960 in Chromium and 706/960 +in Firefox. These counts overlap the prior revision and are not additional +unique tests. The `source` and `port` Git trees are byte-identical to 6096; +runtime receipts retain their actual 6096 build provenance. +`ci/cafddf5d3-final-receipt.json` binds eleven retained metadata/log files, +independently rehashed after collection. + +The current separated agreements are shared 32722, MCC 68 and camera +32724/32725. Neither old upstream crossplay nor old-layout save compatibility +is claimed. Full campaigns, every installed map, Android hardware and public +relay/NAT traversal remain outside the observed coverage. + +### Internet gameplay setup and retained failures + +Actual-map Internet checks use two isolated processes at a time: a local +Windows release build and the exact-revision CI Web artifact, connected through +a local broker and real WebRTC data channels. The Web ZIP is artifact +`13602867233` from Build run `42443616551`, SHA-256 +`a08c85a8a7f503107753afc42df1f42f279b36aea78c8c29be3dabc9b70353ae`. +All 24 expanded site files are verified against that archive. The browser +itself is headless; the browser-host case renders its normal SDL canvas so +ordinary console key events can be exercised. + +Several private test setup failures are retained rather than reclassified: + +- The earlier pre-clock native cue had a space that the inherited command + wrapper interpreted incorrectly. The corrected input is `60(sv_end_game)`. +- The earlier browser's no-window SDL mode discarded keyboard input. A real + rendered canvas is required for this input test. +- The first rendered browser attempt typed `9sv-end-game0`, as its screenshot + shows. Actual SDL key conversion requires Shift with the physical digit and + minus keys. Explicit paced key presses now produce `(sv_end_game)`, with + missing/stuck-Shift controls and a required screenshot before submission. +- A native-host attempt entered its first game before the scheduled + twelve-second test start. A separate PDB-bound + observation replays 849 accepted double-read samples, retaining 116 races + as gaps. The engine completed its postgame timer and continued frames for + over 122 seconds in the scores state, but the debug test's `started` flag + remained false. Its automatic next-round gate was therefore never armed. + This diagnostic was ended normally and remains failed. The input code's + bot A presses in menus explain the early start, but the individual press + was not sampled. Host-only `look:0` input cannot press A, and the corrected + run records its scheduled start. A positive scheduled-start event + before the first complete gameplay sample is now mandatory. Client input, + shooting and all comparison thresholds remain unchanged. +- The rendered browser-host v5 run executes the verified command, completes + both rounds and yields 47 paired seconds without gameplay divergence, + but still **fails** the overall gate on an unhandled pointer-lock rejection. + An inert two-tab control reproduces the exact `WrongDocumentError` while + the canvas remains connected and `document.hasFocus()` is true. Bringing + that canvas tab forward makes the same request succeed. The final rendered + browser-host runs explicitly activate their owned page before Play and + console input, and have no such rejection. No pointer-lock override, error + suppression or game/site/WASM change is used. + +All three final cases independently pass on the unchanged 6096 gameplay +implementation. Each peer has one actual round reset and 49 fresh second-round +samples spanning 48 seconds. Both the recorded and independently rerun judges +report 47 paired seconds, zero tick offset and no problems/divergences: + +| Host and joining route | Client input | Maximum paired position difference | Drift samples / apart | +| --- | --- | ---: | ---: | +| Native host, browser client (`native-host-…-v3`) | `bot:1` | 0.146769 | 1,262 / 341 | +| Browser host, native invite (`browser-host-invite-…-v6`) | `bot:1` | 0.073770 | 1,316 / 314 | +| Browser host, native public-game discovery (`browser-host-browse-look-…-v6`) | `look:1` | 0.001000 | 1,316 / 8 | + +All hosts use `look:0`, so these Internet controls do not demonstrate free +host movement. The first two clients retain scripted movement; the discovery +case isolates look input. Both sides retain the scripted firing behavior. +The original drift share limit remains 0.6, with at least 300 drift samples +and twenty paired seconds required. These results do not claim bit-exact +positions. Raw corrections, transient mismatches and all tolerances remain +in the receipts. + +For both browser hosts, the reviewed screenshot shows the exact console +command before Enter. Game over follows after thirty simulation ticks +(1,160 ms for invite; 372 ms for discovery), before the real lobby transition +and second game. The actual renderer, physical key sequence, normal page +activation and absence of PAGEERROR/fatal diagnostics are verified. The +discovery log proves browsing and selection from the server browser; that +client receives no invite argument. All cases establish bidirectional real +WebRTC traffic, unchanged original inputs, verified saved exports, normal +native exit and closed browser contexts. They remain local-broker tests, +not public relay or NAT-traversal tests. + +Evidence is under `internet/runs/` and +`validation/internet-*-6096b0b4f969-*-audit.json`. Every earlier failed verdict +is preserved. The test-only checkpoint-timing follow-up also passes CI. + +### Combined review and evidence preservation + +The final implementation review covers the boat producer, console ownership +and saved-image validation, client clock lifecycle, protocol admission, +neighboring MCC integration, regression fixtures and reader documentation. +The redundant MCC boat helper/hook and unreachable console disposal branch +are removed because their replacements are demonstrated. No further production +abstraction, trimming or optimization is justified by this review. Map-family +limits, permission checks, cleanup, diagnostics and meaningful regression +coverage remain. The combined source review precedes the 462 final focused +checks and final runtime/CI validation; the later test-only correction has its +own focused review and actual Windows/Linux standalone checks. + +Primary and independent documentation reviews check the resulting behavior, +named symbols, local links and numerical claims against the retained evidence. +The final CI follow-up changes no game-source tree, so the runtime results +are not relabeled as executions of a different binary. + +Per-run cleanup removed 504 native generated map caches (64,474,841,088 bytes). +Separate verified cleanup of the nine closed Internet attempts removed another +54 caches (6,908,018,688 bytes), preserving every other run file at that stage. +Both Mercury fixtures are inactive and removed; original Workshop maps and +resources remain unchanged. These are generated caches, not player saves. + +The final reviewed plan archives **5,304 files**, totaling 11,227,077,161 +uncompressed bytes, into `inactive-evidence.zip` (1,217,001,463 bytes). +Original paths, sizes and SHA-256 values are recorded. Every archive member is +verified before its loose copy is removed. The archive preserves inactive +saves/core images, browser profiles and exported saves, both executed baseline +builds and necessary binary test inputs. Another **3,221 disposable files** +(18,622,942,131 logical bytes) are removed after ownership/input verification. +That logical total includes 344 map-copy hardlinks; it is not a disk-space claim. + +Final inventory accounting, including the last 54 Internet caches, releases +about **18.18 GB of allocated space**, with about **1.99 GB retained** under +Stage 11. Earlier per-run native cache removals are outside that comparison. +The retained total includes the 1.22 GB archive, roughly 756 MB of loose raw +captures, logs, source copies, executed CI Web ZIPs and other evidence, plus +the cleanup manifests and final receipts. The active native build and installed +toolchains remain outside this cleanup. Empty evidence directories are retained. + +The two cleanup operations each paused on a transient process-ID check. Fresh +process queries found those IDs absent, and the same plans resumed without +weakening guards or stopping unrelated processes. The final verifier rehashes +all 5,304 archive members, 2,418 retained evidence files and sixteen protected +original/current-build records, confirms every disposal target is absent and +finds no remaining generated map cache or active game process. The Ruby, Xbox +and Mercury recovery audits and Xbox/CE two-round audits replay successfully +against archived evidence; all three retained Internet log pairs again yield +47 paired seconds without problems or divergence. These are preservation +checks, not additional game launches. See `cleanup-plan.json`, +`cleanup-applied.json`, `validation/internet-cache-cleanup-applied.json` and +`validation/post-cleanup-verification.json` under `build/stage11-fix`. + +Milestone 11 is complete within the stated runtime and platform limits. +The branch contains shared fixes without map-name selectors; Xbox, CE and MCC +ownership boundaries remain intact. Old network peers and old-layout saves +are deliberately incompatible. No complete-campaign, every-map, physical +Android-device or public-NAT compatibility claim follows from these checks. diff --git a/docs/mods.md b/docs/mods.md index 12528e53ac..57c2a0307c 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -331,3 +331,10 @@ mods: 4 models from their files (4 new), 0 given back, 1 left out web): their files, their sounds' samples, their bitmaps' tags and their models' geometry. - A Custom Edition map takes mods as an Xbox map does. + +## GulchCE MCC maps + +Loose-tag mods are bypassed for MCC maps, which retain their authored sounds, +bitmaps, text and models. Console reload/enable commands cannot override this. +Your selected mods and load order remain saved and apply again when an Xbox +or Custom Edition map loads. MCC package and shared resources are unaffected. diff --git a/docs/muzzle_lighting.md b/docs/muzzle_lighting.md new file mode 100644 index 0000000000..7dbeb92f4b --- /dev/null +++ b/docs/muzzle_lighting.md @@ -0,0 +1,192 @@ +# Optional muzzle-flash lighting + +`display.muzzle_lighting = true` (`HALO_MUZZLE_LIGHTING=1`) adds short coloured +light pulses to successful shots. It defaults to **false** and is independent +of `display.plasma_lighting` and `display.plasma_occlusion`. Stock weapon flash +effects, particles, sounds, projectiles and explosions are preserved. +Keep render interpolation enabled for smooth fades between simulation ticks. + +## Supported weapons + +Profiles match exact stock weapon tag names, including both Xbox and Custom +Edition Needler names, the Warthog chaingun and both Scorpion guns. Unknown custom weapons keep their +authored behaviour. Radii below are engine world units, durations are seconds. + +| Weapon | Colour | Radius | Duration | +| --- | --- | ---: | ---: | +| Assault rifle | Warm amber | 1.8 | 0.10 | +| Pistol | Warm amber | 1.8 | 0.12 | +| Shotgun | Orange | 2.2 | 0.14 | +| Sniper rifle | Warm white | 2.0 | 0.12 | +| Plasma rifle | Cyan | 1.6 | 0.10 | +| Plasma pistol | Green | 1.6 | 0.12 | +| Charged plasma pistol | Green | 2.2 | 0.16 | +| Needler | Pink | 1.3 | 0.09 | +| Rocket launcher | Orange | 2.0 | 0.14 | +| Flamethrower | Orange | 1.4 | 0.08 | +| Warthog chaingun | Warm amber | 5.0 | 0.16 | +| Scorpion main cannon | Warm amber | 7.0 | 0.22 | +| Scorpion machinegun | Warm amber | 5.0 | 0.12 | + +The Warthog profile matches `vehicles\warthog\warthog gun`. Read-only Xbox +Blood Gulch tag inspection confirms that this weapon has no model; the vehicle +model provides `primary trigger` on its animated gun. The existing invisible +weapon fallback follows that rendered vehicle marker. Its broader warm pulse +illuminates the hull and nearby ground; rapid shots refresh one bounded light. +No new shared-engine hook or stock flash changes are needed. + +The Scorpion's `vehicles\scorpion\scorpion cannon` weapon has two triggers. +Each retains an independent pulse, so machinegun fire cannot restart or replace +the cannon's flash. Both count against the existing eight-light limit. The +vehicle's animated `cannon flash` marker places the main source ahead of the +barrel; `secondary trigger` plus 0.08 units along its forward direction places +the machinegun source just beyond its barrel. Read-only Xbox Blood Gulch and +b40 inspection established these marker names and positions. Both profiles +include vehicles in their collision queries, as the Warthog already does. + +## Ownership and integration + +`port/linux/game/muzzle_lighting.c` owns the profiles, eight bounded pulse +records, rendered marker placement, smoothstep decay and cleanup. A successful +shot records identities only; rendering creates the light. Dry fire, charging, +reloads and failed shots do not create pulses. Repeated shots refresh the same +weapon's pulse (one per gun on the Scorpion). Excess simultaneous weapons retain their stock effects; an +existing pulse is not evicted. Only muzzles within 25 units of a local camera +are retained. + +The pulse follows the rendered first-person muzzle when available, otherwise +the world-model trigger marker. Missing markers are rejected. Position and +brightness update on rendered frames; the radius remains fixed throughout the +fade. These lights use the existing optional soft surface/model attenuation +and collision-occlusion modules. Muzzle occlusion is automatic while this +option is enabled; it does not enable projectile occlusion or projectile +lighting. Specular still respects the borrowed light template's flags. + +Two minimal additions to established source implementations are necessary: + +* `source/items/weapons.c` records the successful firing event after the + existing projectile creation call. A feature module cannot reliably infer + successful shots, including misfire and alternate-ammunition handling, from + input or weapon animation alone. +* `source/objects/object_lights.c` invokes render preparation and lifecycle + cleanup, includes the feature radius in visibility bounds, and exposes a + checked move operation for an unattached, feature-owned glow. Light storage, + flags and map partition membership are private to this implementation. + The bridge verifies the salted handle, owner, template and feature flag. + +Shared additions are marked `port:`. Existing Xbox, Custom Edition and MCC +loading paths and directories are unchanged. Map changes, failed-load +recovery and shutdown discard feature identities before light storage is +destroyed. Switching/dropping weapons, losing the owner, expiry and disabling +the option release pulses. At frame end lights are blackened and disconnected +from the map so they cannot affect simulation lighting between frames. + +No network message or gameplay rule changes: each client renders successful +shots from its local simulation. The network version is unchanged. This work +does not implement CStencil or Modern shadows. + +## Validation and limits + +The asset-free harness executes the actual module and checked move bridge. +It covers subtick decay, repeated shots, profile admission, the eight-light +cap, stale identities, missing resources, disable, weapon/owner changes, +map reset and frame-end disconnection. Negative controls demonstrate that +tick-only fading, broken cleanup and a non-moving light fail the tests. +The focused muzzle/projectile/falloff/model/occlusion suite has 42 passing +tests. The light-storage ordinary COFF and full-LTO checks also pass. + +Windows hidden OpenGL captures on 2026-10-14 exercised the handheld weapon +profiles at 30, 60 and 120 FPS, Blood Gulch and Carousel, CE Death Island, +disabled controls and combined projectile/muzzle lighting. Firing/decay image +sequences were inspected at each frame rate. Frame logs show intermediate +brightness values within the same simulation tick. Accepted runs: + +| Cap | Cases | Measured mean FPS range | Maximum active-frame p95 | +| ---: | ---: | ---: | ---: | +| 30 | 15 | 30.00-30.00 | 34 ms | +| 60 | 15 | 57.97-60.03 | 20 ms | +| 120 | 16 | 119.41-120.02 | 11 ms | + +Two initial 30 FPS plasma captures had long stalls and failed the timing +threshold; their repeated captures passed and the failed logs remain retained. +The initial Xbox Needler fixture requested the CE tag name and was excluded; +the corrected tag passed at all three rates. These short capture windows are +not a sustained performance guarantee. Capture sources match the implementation +except for a subsequent source-include comment identifying the feature module. + +Console-driven Xbox Blood Gulch -> CE Death Island -> MCC Mercury Falling -> +Xbox Blood Gulch transitions completed with the feature off at 30 FPS and on +at 120 FPS, with normal exits and no logged exceptions. The first sandboxed +attempts could not connect to the local console and were excluded; the runs +with local socket access executed all three transitions. This verifies bounded +load/unload coverage, not complete MCC visual compatibility. + +A two-instance native loopback game at 60 FPS used host-on/client-off settings. +All 29 common reported player-state snapshots matched through tick 870. The +host recorded 511 muzzle samples from two weapon handles; the disabled client +recorded none. Both exited normally. This used the session's default weapons: +the fixture's early equip attempt preceded spawning. No hits, deaths or respawns +were exercised, and browser/WebRTC interoperability was not rerun because +transport and protocol code are unchanged. The normal release executable also +passed a hidden OpenGL startup/map smoke test with all lighting options off. + +Windows portable release builds pass. Android and web builds were attempted, +but this workspace has neither target/toolchain configured; those platforms +remain unverified. Linux was not built: WSL reports that it is not installed. +Approximate occlusion can still leak around complex +geometry. These captures are bounded Windows tests, not proof of every map, +GPU, multiplayer situation or split-screen configuration. +Selected model-light draws were observed. Positive muzzle-specific specular +output was not established in these scenes; the existing shader regression +tests pass, and authored no-specular flags remain authoritative. + +Capture-only instrumentation and forced inputs are built by +`tools/plasma_visual_build.py`, which restores sources and rebuilds the normal +executable afterward. `tools/plasma_visual_run.py --muzzle ar` selects a weapon; +use `--both-lighting` to combine it with projectile lighting. Captures retain +source hashes, images, logs and timing reports under `build/plasma-visual`. +Only private copied maps and generated map caches are removed after a run. + +## Warthog extension validation + +The new stock Warthog profile uses radius 5.0 and a 0.16-second warm pulse. +Capture fixtures confirmed the model-less weapon resolves the vehicle's +`primary trigger` marker and enters the actual `W-gunner` seat before firing. +Final captures at 30, 60 and 120 FPS passed the 5% timing threshold, with a +60 FPS disabled control submitting no muzzle lights. Images show broad warm +ground spill; hull illumination varies with viewing angle. Stock flash and +explosion paths were not changed. + +A hidden native Blood Gulch loopback run connected two players for 82 reported +snapshots, with host lighting on and client lighting off. The host logged actual +Warthog shots; the client submitted no muzzle lights. All 82 non-position player +states matched. Vehicle position components differed by up to 0.015 world units, +so this is not a claim of bit-identical simulation. Both exited normally. The +earlier 45-second run timed out before gameplay and is excluded. Logs are in +`build/emitter-network-retry-warthog`; final turret images are in +`build/plasma-visual/*-emitter-release-warthog`. + + +## Vehicle occlusion refinement + +Warthog muzzle pulses now include vehicle collision geometry in the existing +optional visibility field. The emitting Warthog is not excluded: its chassis +can block light reaching ground beneath it, while exposed surroundings can +receive the same broad warm pulse. Radius, colour, duration and stock flash +remain unchanged. Other muzzle profiles retain their existing collision mask. +This is automatic when muzzle lighting is enabled, independently of the +projectile/emitter occlusion toggle. Both settings remain off by default. +It is approximate collision-based visibility, not exact +render-mesh shadows, and the existing shared budget and edge leakage apply. +The regression fixture checks vehicle-only obstruction and verifies that an +unrelated muzzle profile does not acquire vehicle blocking. + +The chassis refinement was captured on Windows at 30/60/120 FPS, with an off +control at 60 FPS and final larger yaw/elevation sweeps at all three caps. +Images show exposed warm ground spill and a dark region under the chassis; +turning exposes lit hull surfaces. Final sweeps record model and specular draws. +The shared visibility regression tests pass, including vehicle obstruction and +preserving the collision mask for other muzzle profiles. These bounded scenes +do not establish perfect self-shadowing at every hull edge or seat/view angle. +See `build/plasma-visual/*-direct-warthog` and +`build/plasma-visual/*-direct-final-turn-warthog` for the retained captures. diff --git a/docs/plasma_lighting.md b/docs/plasma_lighting.md new file mode 100644 index 0000000000..712e9c2b55 --- /dev/null +++ b/docs/plasma_lighting.md @@ -0,0 +1,1037 @@ +# Dynamic lighting implementation history + +See the +[release guide](dynamic_lighting_release.md) for the current feature +set, menu controls, known limitations and acceptance status. The +[emitter additions](reading/emitter_expansion.md) describe the subsequent sword, +charge/heat, grenade, flame, vehicle and world-light extension. Muzzle lighting, +Covenant projectiles, held-weapon emitters and shield lighting are implemented; +CStencil and Modern remain separate work. `chesters-cool-stuff` remains a local +reference. + +The sections below preserve the chronological implementation and test record, +starting with `plasma-lighting-prototype`. Earlier radii, exclusions, deferred +features and test limits describe those stages; later entries supersede them. +They are not the current release checklist. + +Set `plasma_lighting = true` in config.toml's `[display]` section, or +`HALO_PLASMA_LIGHTING=1`. The default is false. Keep `display.interpolation` +enabled for motion between simulation ticks. + +## Rendering + +The feature selects existing light attachments on four exact projectile tags: +`weapons\plasma rifle\bolt`, `weapons\plasma pistol\bolt` and +`weapons\plasma rifle\charged bolt` (the pistol overcharge) and +`weapons\rocket launcher\rocket`, up to 128 authored attachments per frame. +Stock rockets have no authored light and use the separate bounded flight-light +module described below. It refreshes their marker +poses before visibility and receiver selection. New objects without a previous +snapshot use the engine's existing fallback pose. + +Live captures revealed that Xbox Blood Gulch's bolt light has flags zero: +its attachment supplies a lens flare but is not marked dynamic. The first +temporal prototype therefore did not illuminate world surfaces on that map. +Selected attachments now become dynamic during rendering, with their original +flags restored afterward. Tags are never edited and the authored-attachment +path allocates no extra light. +Already-dynamic attachments retain their authored flag after rendering. + +World diffuse illumination uses a feature-owned 64³ attenuation texture: +`max(1 - distance_squared / radius_squared, 0)²`. Both value and slope approach +zero at the outer boundary. Texels are sampled at their centres and filtered +linearly. The authored colour and radius remain unchanged. The existing +additive pass still applies material colour and surface facing. + +Model point lights now use the same squared falloff. The model shader's +existing contribution is multiplied by the extra distance factor only for +selected plasma slots. Ambient, distant and other point lights keep their +existing arithmetic. Models remain vertex lit unless the separate existing +per-pixel setting is enabled; that path applies the same curve per pixel. +No setting is silently enabled. Coarse model meshes can still reveal vertex +interpolation in the lighting. + +Omnidirectional world specular passes use the same texture on their own +attenuation stage, preserving the authored specular radius multiplier, +material mask, exponent and highlight colour. Spotlight gel passes and model +cubemap reflections remain stock; this does not add a new model specular BRDF. +Optional collision occlusion is described below. Custom projectile tag names and projectiles without +light attachments are outside this prototype. + +## Optional occlusion prototype + +Enable `plasma_occlusion = true` alongside `plasma_lighting = true` in +`[display]`, or set both `HALO_PLASMA_OCCLUSION=1` and +`HALO_PLASMA_LIGHTING=1`. Both default to false. Occlusion alone does nothing. + +`plasma_occlusion.c` builds a 16³ local visibility field using the existing +structure, scenery and machine collision queries. Bipeds, vehicles and +projectiles do not cast occlusion. The origin is the rendered light position; +queries do not modify simulation state or collision geometry. The extent +includes the authored world specular radius. Trilinear sampling avoids +switching an entire receiver on or off at a doorway. Visibility uses elapsed +time, with an 8 ms blocking half-life and a 25 ms clearing half-life. + +World diffuse and omnidirectional specular passes combine visibility with +soft attenuation in separate 16³ volume textures. Models sample the same +visibility field in their existing vertex or optional per-pixel lighting path. +The private specular-radius getter in `object_lights.c` is the only new game +source bridge: the feature module cannot safely access that private layout. +The existing falloff, model selection and lifecycle hooks supply the remaining +integration. `plasma_occlusion_gl.c` binds model volumes on extra texture units +6/7 and restores the active unit; it does not replace the game's four stages. + +Eight stable light identities can hold fields. At most eight field updates +occur per view. Each collision refresh uses 1536 directional depth rays; the +16³ grid interpolates visibility comparisons along them, not blocker distances. +Depths are reused for less than 12 ms, with immediate invalidation for radius +changes or motion exceeding one eighth of the field extent. Projection and +fading still run at every rendered pose. Active fields are not evicted +for an overflow light; excess lights retain unoccluded soft lighting. An unused +field becomes reusable after 100 ms. Upload failure also falls back. Fields +and their textures reset at the existing disable, map and shutdown boundaries; +model slots reset per receiver/view. A constant white GL fallback texture is +renderer-lifetime state and contains no map or feature history. + +This is deliberately approximate, not CStencil or Modern. Thin geometry and +cell boundaries can leak light; the cell width is twice the largest light +radius divided by 16. History is reprojected at world-space receiver +positions. Cached collision depths and temporal filtering can still introduce +short edge lag. Collision meshes may differ from visible meshes, and coarse +vertex-lit models interpolate visibility between vertices. Previously +overflowing lights fade into occlusion over 80 ms after admission. Projectile +creation/destruction is not cross-faded. The feature does not alter the stock +bolt lens flare, which can remain visible when its projected illumination is +blocked. Split-screen and every map/material remain unverified; the hardening +captures below cover scripted sustained fire and a controlled moving-door +fixture. + +## Isolation and lifetime + +Selection, render tracking and texture generation live in the dedicated +`plasma_lighting.c`, `plasma_falloff.c` and `plasma_model_shader.c` modules. The +small bridges in `object_lights.c` are necessary because light storage and cluster ownership +are private there. They validate handles and ownership before refreshing +attachments or changing the runtime dynamic flag. No map-family loading, +conversion, gameplay or network protocol changes are intended. + +World diffuse and omnidirectional specular begin/end hooks are necessary +because the attenuation sampler belongs to that existing pass. Only selected plasma draws bind the replacement +texture (stage 2 for diffuse, stage 1 for specular). End restores the stock +texture and filter, including if the option has just been disabled. Allocation failure falls back to stock attenuation. +The texture is released on disable, map initialization/unload, light recovery +and shutdown. Per-view rasterizer indices reset for each split-screen view. + +The model slot hooks in `rasterizer_xbox.c` are necessary because only that +submission path maps receiver light slots to rasterizer light indices. A +feature-owned two-bit mask is cleared before each model, each view and at +frame/map cleanup, and gated again by the option at draw time. The renderer +uploads it as a separate uniform, without borrowing stock constants or flags. +Minimal translator hooks call the feature emitter for recognized two-point-light +model shaders and the existing per-pixel model shader. The vertex path changes +only the point light colour multiply-add's RGB operand; the parallel scalar +instruction and alpha are untouched. These shared paths serve Xbox, CE and MCC +receivers, with no changes to map admission, loading or conversion. + +After interpolation ends, the feature restores original dynamic flags and +simulation-time positions and cluster membership. Map boundaries discard old +handles. Excess lights beyond the bounded tracking array retain stock behaviour. +The disabled path performs no light refresh or texture substitution. + +## Model and specular validation + +Windows portable release, 2026-10-14: 20 harness tests passed. Coverage adds +model-slot selection, disable/view/frame cleanup, specular stage/filter +restoration, and translation of the actual stock shader payloads (both model +point-light slots reached; non-point programs untouched). Light-storage ordinary +and full-LTO checks and their negative control passed. The normal release +executable was rebuilt after removing all capture instrumentation. + +Twelve hidden runs captured three real projectiles apiece, with plasma lighting +off/on at each cap. Blood Gulch used a spawned Spartan receiver; Carousel used +world diffuse lights disabled via its existing debug setting, isolating the +world specular contribution. Counts below are actual selected model draws or +specular receiver draws, not just light submissions. + +| Cap | Model off/on FPS | Model draws on | Specular off/on FPS | Specular draws on | Most poses per tick | +| --- | --- | --- | --- | --- | --- | +| 30 | 30.00 / 29.57 | 88 | 30.00 / 29.72 | 56 | 1 | +| 60 | 59.99 / 58.89 | 165 | 60.00 / 59.56 | 114 | 2 | +| 120 | 119.99 / 119.99 | 348 | 119.61 / 119.99 | 270 | 4 | + +All runs exited normally; disabled runs had zero selected draws. Median frame +intervals were 33/17/8 ms. A further enabled 60 FPS model run with per-pixel +lighting passed (59.17 FPS, 150 selected draws). Measurements include capture +and initial shader work and are not a comparative performance benchmark. + +Reviewed off/on images and consecutive frames show cyan illumination traversing +the armour and highlights crossing the indoor floor. The 60/120 FPS sequences +and telemetry contain intermediate poses within each simulation tick. Off/on +frames are matched to the nearest projectile position, not pixel-identical +simulation timestamps. Short-lived bolts still disappear at normal impacts; +no artificial lifetime or impact fade was added. Coarse vertex-lit meshes and +stock material highlight sharpness remain visible limitations. + +Evidence: `build/plasma-visual/model-comparison.png`, `model-sequence.png`, +`specular-comparison.png`, `specular-sequence.png`, `model-specular-results.json`, +and each `*-model-final` / `*-specular-final` directory. The test-only binary +and build manifest are retained; copied test maps and caches were removed. +The initial short-trajectory probe runs are diagnostic evidence only. + +Production Xbox Blood Gulch -> CE Death Island -> MCC Mercury Falling -> Xbox +transition smoke checks passed off/on: three console commands each, confirmed +CE conversion/MCC loading, exit zero and no logged exceptions. Logs are in +`build/plasma-model-transitions`. This is not visual certification of CE/MCC +plasma shaders or split-screen. + +A two-instance Windows loopback Slayer smoke test also passed with the host's +option on and the client's off: both logged two players through tick 870 and +exited normally. This checks session compatibility, not networked plasma combat. +Logs remain in `build/plasma-model-network-complete`. The first attempt lacked +the private profile's lobby map and never entered play; it is not counted. + +Android and web builds were attempted but those targets are unavailable in the +local toolchain. Linux/mobile/web runtime and browser-network interoperability +remain untested. The new code uses existing GL entry points and both new modules +are included by the native, Android guest and web source globs; no new Android +host imports or network-version change is needed. + +## Earlier world diffuse validation + +Windows portable release, 2026-10-14: 17 harness checks passed, including +negative controls, disabled selection, view boundaries, stale ownership, +restoration of both dynamic and lens-flare-only flags, allocation failure, +texture/filter restoration, and monotonic falloff with a zero boundary slope. +Existing light-storage checks passed ordinary and full-LTO links and their +negative control. + +Hidden Xbox Blood Gulch captures launched three real plasma-rifle projectiles +along a repeatable trajectory across visible ground. The fixture creates real +projectile objects using normal physics and impacts; it does not simulate +controller firing. Screenshots and per-render-frame telemetry were collected +with the option both off and on: + +| Cap | Off average | On average | On median frame interval | Most distinct rendered poses within one tick | +| --- | --- | --- | --- | --- | +| 30 FPS | 30.01 | 29.67 | 33 ms | 1 | +| 60 FPS | 60.00 | 59.56 | 17 ms | 2 | +| 120 FPS | 119.99 | 120.04 | 8 ms | 4 | + +The measurements include capture overhead and initial shader/texture work. +Images show a feathered pool following the bolt across the ground. Successive +60/120 FPS frames and telemetry show intermediate poses rather than a light +held at each 30 Hz tick. Selected lights return to zero after projectile removal. +No crashes occurred in these six runs. Captures are under `build/plasma-visual`; +`sequence-contact.png` shows consecutive enabled frames at each cap. + +Separate hidden runs with the production executable exercised Xbox Blood Gulch, +Custom Edition Death Island and MCC Mercury Falling with the option off and on. +Both runs sent all three transition commands and exited normally without logged +exceptions; the logs confirm CE conversion and MCC loading. These were loading +and transition smoke checks, not projectile-lighting visual tests on CE/MCC. +Their logs remain in `build/plasma-falloff-transitions`; copied test maps were +removed. An earlier sandboxed attempt could not connect to the local console +and is not counted as a successful transition test. + +Those earlier tests did not establish softer model/specular shading, wall occlusion, +split-screen visual quality, every plasma tag variant or full map compatibility. +Android/web targets are unavailable in the local build configuration. Linux, +Android, web, browser networking and multiplayer runtime were not tested. +The change introduces no wire-format or simulation contract changes, so the +network version is unchanged. + +## Reproducing the captures + +With the repository's Windows compiler environment configured: + +``` +python tools/plasma_visual_build.py +python tools/plasma_visual_run.py --data-root C:/Games/GulchCE --fps 30 --enabled 1 +``` + +For a visible model receiver, add `--model --distance 1.3 +--receiver-distance 1.8 --height -0.3`. For an indoor specular isolation run, +add `--map carousel --distance 1.5 --height -0.25 --specular-only`; this uses +an existing debug setting to disable world diffuse lights in the private test +session. Add `--per-pixel` to exercise the existing model lighting option. +The scene flags affect only the capture executable and private configuration. + +Repeat for caps 30, 60 and 120 and enabled values 0/1. Use `--label` for a new +output directory when repeating a combination. The builder temporarily installs +`tools/fixtures/plasma_lighting_capture.c`, restores the production source and +configuration even on failure, and rebuilds the normal executable. The fixture +is only present in `build/plasma-visual/halo-capture.exe`. The runner uses hidden +windows and private data/save folders, removes copied maps and generated map +caches, and retains screenshots and diagnostic logs. + +## Occlusion validation (2026-10-14) + +The Windows portable release build and 21 focused harness tests pass. These +include synthetic wall/doorway visibility, partial clearing, equal elapsed-time +response at 30/60/120 FPS, the four-field limit, model-slot reset, disabled +queries, allocation failure and resource cleanup. Light-storage tests pass +ordinary/full-LTO links and their negative control. + +Hidden Xbox Carousel captures compare occlusion off/on with plasma lighting +on. A diagnostic carrier sweeps across the nearby pillar/opening; this fixture +holds and moves a real projectile object and may pass through geometry. It is +not a combat trajectory. Separate normal projectiles use ordinary physics and +impact quickly in this scene. Neither probe logic nor telemetry enters the +production executable. Off/on comparisons show reduced illumination beyond +the pillar; consecutive-frame inspection shows a spatially softened transition +in the tested scene, rather than whole-receiver rejection. A synthetic doorway +is covered by the collision harness; moving-door visual behaviour is untested. + +| Cap | Corner sweep, occlusion off | Corner sweep, on | Wider sweep, on | Normal projectiles, on | +| --- | --- | --- | --- | --- | +| 30 FPS | 29.55 | 30.00 | 29.61 | 30.00 | +| 60 FPS | 58.62 | 58.61 | 58.60 | 60.00 | +| 120 FPS | 119.22 | 120.02 | 120.02 | 119.99 | + +These are average measured FPS including capture overhead and startup work, +not GPU benchmarks. One active light is exercised, not the four-light worst +case. The optional per-pixel model path passed at 58.70 FPS under a 60 cap. +With plasma lighting disabled and occlusion enabled, selection and field-update +counts remained zero (59.46 FPS). No shader/GL errors or exceptions were found +in these capture logs. An 8-unit distant scout produced no selected lights and +is explicitly excluded from successful validation. + +Production transition runs, off at 30 FPS and on at 120 FPS, loaded Xbox Blood +Gulch, CE Death Island, MCC Mercury Falling and returned to Xbox. Both completed +three console transitions, logged MCC loading and exited without exceptions. +These are loading/lifecycle smoke checks, not CE/MCC lighting visual validation. +Android/web build attempts report unknown targets in this Windows configuration; +Linux, Android, web and browser networking runtime remain unverified. The +prototype changes no simulation or network contract, so the network version +is unchanged. + +Evidence remains under `build/plasma-visual/*occ*` and +`build/plasma-occlusion-transitions`. The comparison and consecutive-frame +contact sheets are `occlusion-comparison.png`, `occlusion-corner-sequence.png` +and `occlusion-opening-sequence.png`. Copied test maps are removed; diagnostic +logs and images are retained. The capture manifests identify the source used; +subsequent source polish hardens overflow budget admission and removes +an unnecessary upper limit on the private radius getter. None changes the +successful single-light, stock-radius scenes above. + +To reproduce the controlled wide sweep after building the capture executable: + +``` +python tools/plasma_visual_run.py --data-root C:/Games/GulchCE --fps 60 --enabled 1 --occlusion 1 --map carousel --distance 3 --height -0.1 --probe --span 4 --model --receiver-distance 2 --label occlusion +``` + +Repeat at 30/120 FPS. Drop `--probe --span 4` for normal projectiles; use +`--occlusion 0` for the soft-lighting control. Output labels must be unique. + +A hidden two-instance native loopback Slayer smoke test also passed with plasma +lighting/occlusion enabled on the host and disabled on the client. Both peers +reported two players through approximately tick 870 and exited normally. Logs +are in `build/plasma-occlusion-network`; this is connection/gameplay smoke +coverage, not a multiplayer plasma-combat or browser transport test. Final +review added a regression ensuring an overflow light submitted before the four +admitted lights cannot spend their update budget. That correction is covered +by the harness and final Windows build; the captured single-light paths are +unchanged. + +## Sustained-fire hardening (2026-10-14) + +The selected budget is now eight occluded lights, increased from four. Sixteen +was evaluated but rejected as the fixed budget: the isolated 16-light fixture +fell to 85.92 FPS under a 120 cap, versus 120.02 without occlusion. With the +final eight-slot budget, the same 16 visible bolts averaged 115.52 FPS; eight +retain soft unoccluded lighting. Active identities are never evicted, and a +previously overflowing light blends into occlusion over 80 ms when admitted. +This is bounded coverage, not a claim that every bolt in arbitrary combat is +occluded. Allocation failure still uses the unoccluded fallback. + +The collision work changed from 4096 rays per field to 1536 directional rays. +The 16³ output grid filters comparisons against those depths. This avoids +inventing intermediate wall distances across openings, but widens the soft +edge slightly: the synthetic near-jamb sample is about 27% visible, while the +farther sample is fully blocked. Thin features narrower than angular/grid +sampling can still leak. Depths are cached for less than 12 ms at rendered +samples and invalidated by fast movement/radius changes. Light motion and +world-space history reprojection continue every frame. A clear cached ray uses +an explicit no-hit sentinel so moving across its previous endpoint cannot +create a false dark border; a regression failed before that correction. + +The production change stays in the plasma module and its existing setting +comment. No new shared-engine hook, map-family conversion, network protocol, +CStencil or Modern work was needed. New combat, burst, door, toggle and map-reset +controls live only in the capture fixture. The builder also temporarily +instruments input for actual trigger presses and restores all source files. +Normal builds contain none of that test logic. + +### Visual and performance evidence + +Windows portable release, hidden 640×480 captures, real Xbox/CE assets copied +into private test folders. Sustained-fire fixtures equip an actual plasma rifle +and hold/release the normal trigger; they do not manually spawn those combat +bolts. The stress fixture deliberately places simultaneous diagnostic carriers +on a controlled trajectory. Door testing spawns an existing A10 door tag with +normal runtime device groups and alternates its desired position; captures +show both animated open and closed states. These are controlled fixtures, not +full campaign playthroughs. + +| Scene | 30 cap | 60 cap | 120 cap | +| --- | --- | --- | --- | +| Xbox Blood Gulch, actual rifle fire, up to six selected bolts | 29.98 | 59.97 | 119.90 | +| CE Death Island, actual rifle fire | 29.99 | 59.99 | 119.71 | +| A10 moving-door probe | 29.99 | 59.79 | 119.99 | + +The eight-bolt stress case measured 114.67 FPS under a 120 cap; sixteen visible +bolts with the final eight-slot budget measured 115.52. Their 95th-percentile +frame interval was 11 ms. These meet the runner's 5% average tolerance, not a +claim of a locked 120 FPS. Measurements include logging/capture overhead and +startup work. Early simultaneous runs are retained for diagnosis but are not +the final isolated stress measurements. The earlier independent-ray candidate +managed only 86.74 FPS for eight bolts; directional reuse without caching +improved it to 105.93 before the final cache was added. + +Consecutive images cover the corner sweep, moving door and CE muzzle-to-impact +lighting. No whole-receiver flicker was observed in these inspected sequences; +this does not establish artifact-free behaviour for every mesh or doorway. +Thirteen rapid setting changes with eight live carriers alternated both states; +the disabled intervals contained no occlusion updates. The settings remain off +by default. Changing the setting itself is intentionally immediate. + +Evidence is in `build/plasma-visual/*hard*`, notably `hardening-door-comparison.png`, +`120-1-hard-final-eight`, `120-1-hard-budget-overflow`, `*-hard-door-final`, +`*-hard-ce-combat`, `*-hard-combat-final` and `60-1-hard-toggle`. +Each capture records its source hashes. The final no-hit boundary correction +was validated by the failing/passing harness regression and production build; +those images precede that narrow correction. The initial A10 attempt (cinematic +active, door without control groups) is excluded; the corrected fixture logs +both 0.0 and 1.0 door positions and active light fields. + +### Regression checks and limits + +Twenty-one focused harness tests pass, including multiple assertions for eight +slots, stable overflow, admission fading, cached-depth reuse/fast-motion +invalidation, moving-door clearing/blocking, a thin plane across cubemap seams, +bounded FPS-dependent response, disabled queries, model slots and texture +cleanup. The cache allows a small bounded difference in sampled visibility at +different frame rates; the test checks that explicitly rather than claiming +bit-identical results. Ordinary/full-LTO light-storage tests and their negative +control also pass. Windows portable release builds pass. Android/web attempts +report unavailable targets in this local configuration; Linux, Android, web, +browser networking and split-screen runtime remain unverified. + +A two-peer hidden native Slayer run used real plasma-rifle trigger input on the +host and moved the remote player into range using host-owned fixture setup. +The host had plasma lighting/occlusion enabled; the client had both disabled. +Both peers reached approximately tick 870 and exited normally; their logs +agree on a kill/death and the client's respawn. The host continued submitting +plasma light fields. This covers scripted local combat, not internet latency, +all weapons or a multiplayer compatibility guarantee. Logs are in +`build/plasma-hardening-combat-network-v2`. Initial helper launches lacked the +capture executable's DLL search path and are excluded from successful checks. + +Reproduce actual rifle captures with `--combat --map bloodgulch` or +`--combat --map ce-deathisland`; repeat caps 30/60/120. For stress, add +`--probe --burst 8 --map carousel --distance 3 --height -0.1`. +Use `--burst 16` to exercise overflow, `--toggle` for rapid activation changes, +and `--door --probe --map a10 --distance 3 --span 0.4 --height -0.1` for the +door fixture. Keep `--enabled 1 --occlusion 1` and a unique `--label`. + +Active transition runs (off at 30 FPS, on at 120 FPS) also completed Xbox Blood +Gulch → CE Death Island → MCC Mercury Falling → Xbox. Both sent three console +commands, logged CE conversion/MCC loading and exited without exceptions. +The capture fixture reinitializes after game-time reset and re-equipped the +rifle on Xbox/CE and after returning to Xbox; MCC is loading/lifecycle smoke +coverage, not an MCC lighting visual claim. Logs are retained in +`build/plasma-hardening-active-transitions-v2`; copied maps and generated +private cache maps were removed. Original maps and saves were preserved. + +A separate 60 FPS moving-door control with occlusion off averaged 59.14 FPS; +`hardening-door-off-on.png` contains representative off/on frames. + + +## Plasma pistol extension (2026-10-14) + +Normal pistol bolts and overcharged shots use the existing feature-owned +selection, falloff, occlusion and cleanup paths. Inspection of the local Xbox +Blood Gulch and CE Death Island data, followed by runtime captures, identified +`weapons\plasma pistol\bolt` and `weapons\plasma rifle\charged bolt`. +The overcharge lives in the rifle directory despite being fired by the pistol. +The normal bolt's light has flags 0 and the charged bolt's flags 3; both report +an authored radius of 1.0 in these captures. The no-specular definition bit +(value 2) disables specular lighting: the charged bolt deliberately retains no world specular +highlights. Promotion and restoration preserve the original dynamic state; +definition flags are never edited. No tag, colour, radius, projectile physics +or network messages change, so no network version increment is required. + +This general feature extension changes only the selector in the existing +feature module and the setting's description. It adds no shared engine hooks, +MCC adapters or loading changes. Custom projectile names still remain stock. +The eight-field occlusion budget is shared by all three selected projectile +kinds, with the existing overflow/admission policy. + +The capture runner accepts `--kind pistol` and `--kind charged`. Add `--model` +to give controlled charged shots a real biped homing target through the existing +projectile interface. These shots retain ordinary projectile simulation; +`--probe` instead holds and sweeps diagnostic projectiles and does not validate +homing. `--mixed --probe --burst 12` creates four of each supported kind to +exercise overflow. `--combat` equips the actual weapon and drives its normal +trigger (short taps for pistol, hold/release for charged). These mechanisms are +linked only into the temporary capture build, never the normal executable. + +Births use the existing interpolation fallback, and expired projectile lights +leave selection immediately. This does not add a birth/death crossfade or alter +stock impact flashes, contrails, muzzle flashes or the weapon's charging glow. +Existing low-resolution occlusion and coarse-model lighting limitations apply. + + +Validation used a portable Windows release based on `c05f2388` plus this +extension, hidden at 640x480 with capture logging enabled. The normal Windows +build passes and contains none of the capture instrumentation. The focused +harness has 23 passing cases, including a negative control which removes pistol +selection and must fail. Light-storage ordinary/full-LTO and corruption-control +checks pass. Local `ninja android` and `ninja web` both report unknown targets; +those builds, Linux runtime, browser networking and split screen remain +unverified for this extension. + +Measured capture averages (FPS, not isolated GPU benchmarks): + +| Scene | 30 cap | 60 cap | 120 cap | +| --- | ---: | ---: | ---: | +| Xbox Blood Gulch, controlled normal bolts | 29.54 | 60.00 | 120.02 | +| Xbox Blood Gulch, controlled homing overcharges | 30.00 | 60.00 | 119.99 | +| CE Death Island, controlled normal bolts | 30.00 | 60.04 | 120.02 | +| CE Death Island, controlled homing overcharges | 30.00 | 59.99 | 120.02 | +| Xbox Blood Gulch, actual tap-fired pistol | 29.99 | 59.98 | 120.11 | +| Xbox Blood Gulch, actual charge/release pistol | 29.99 | 59.99 | 119.99 | +| Twelve mixed diagnostic projectiles | 30.00 | 60.00 | 119.80 | + +All runs met the capture runner's 5% average-frame-rate tolerance. The +controlled-shot captures exercised model draws and returned to zero selected +lights after their projectiles expired. Logs at 60/120 FPS show changing render +poses within individual simulation ticks. Image sequences and the FPS overview +sheets were inspected for both map families and projectile kinds. Sampling +phase, first-use shader stalls and capture overhead prevent pixel-identical +comparisons or a general locked-frame-rate claim. + +Disabled controls at 60 FPS for both kinds on both map families recorded zero +selected lights and zero occlusion updates, even with the occlusion setting on. +Twelve mixed lights selected all three tags and updated exactly eight fields per +active frame. Eight charged diagnostic lights survived 13 rapid occlusion +setting changes with no field updates during disabled intervals. Additional +60 FPS captures exercised the existing per-pixel model path (58.99 FPS) and +Carousel's isolated world specular passes (normal: 59.51 FPS, 789 draws; +charged: zero draws, respecting its authored no-specular flag). The initial +charged specular run exited successfully but the runner wrongly failed it for +having zero draws; the corrected runner checks that no draws occur when every +reported light definition disables specular. The rerun +`60-1-pistol-specular-authored` passed at 59.30 FPS with zero specular draws +and reported flags 3. These are targeted scenes, not exhaustive map coverage. + +Evidence is retained under `build/plasma-visual/`, in directories named +`{fps}-1-pistol-{map}-{kind}`, `pistol-combat-{kind}`, `pistol-mixed`, +`pistol-toggle`, `pistol-perpixel`, `pistol-specular-{kind}` and disabled +`60-0-pistol-off-{map}-{kind}` captures. Each holds its report, logs, screenshots +and capture build manifest. Overview images are `pistol-bloodgulch-fps.png`, +`pistol-ce-deathisland-fps.png` and representative `pistol-off-on.png`; the last +uses nearby phases rather than asserting identical projectile positions. +Copied maps and derived map caches from those runs were removed. + + +Two separate hidden, two-peer native Slayer runs used normal pistol taps and +charged shots, with lighting/occlusion enabled on the host and disabled on the +client. In each run both peers exited successfully and agreed on one host kill, +one client death and the client's respawn. Only the host logged feature +occlusion updates. These are local loopback checks, not internet-latency or +browser transport coverage; no networking code changed. Evidence and private +runner scripts are `build/plasma-pistol-network-{pistol,charged}` and +`build/plasma-pistol-network.py`. + +Active pistol-fire sessions traversed Xbox Blood Gulch → CE Death Island → MCC +Mercury Falling → Xbox Blood Gulch, once disabled at 30 FPS and once enabled at +120 FPS. Both completed all three transition commands, loaded the MCC map, +returned to Xbox and exited with no logged exceptions. This validates targeted +lifecycle transitions, not MCC visual correctness or campaign completion. +Reports, logs and the private runner remain in `build/plasma-pistol-transitions` +and `build/plasma-pistol-transitions.py`. All copied maps and derived caches +from these tests were removed; original maps and saves were untouched. + + +## Rocket flight lighting (2026-10-14) + +The initial Xbox capture established that the stock rocket projectile has +contrail, particle, sound and effect attachments, but no light attachment. +Simply adding its tag to the plasma selector produced no illumination. The +feature therefore owns up to eight additional flight lights in +`port/linux/game/rocket_lighting.c`, using existing engine glow interfaces. +These use a prototype warm colour `(1.0, 0.45, 0.12)` and radius 1.0 world unit; +there is no authored rocket flight-light colour/radius to preserve. The stock +exhaust, rocket motion, damage, impact and explosion effects remain untouched. + +The existing `display.plasma_lighting` setting enables both plasma and rocket +flight lighting. Its name is retained and its default remains false. Optional +`display.plasma_occlusion`, also false by default, shares its eight-field budget +between selected plasma and rocket lights. Muzzle flashes, CStencil and Modern +remain deferred, and `chesters-cool-stuff` remains a local reference. + +Only exact `weapons\rocket launcher\rocket` projectile objects with a model +node and within 25 world units of a local camera receive new lights. A map's +existing light attachment takes precedence and uses the authored-attachment +path; no duplicate flight light is added. Missing glow templates, exhausted +light storage and rockets beyond the eight-owned-light limit keep stock +behaviour. No tag is changed and no light is attached to an explosion object. +The template comes from the engine's existing glow-definition service; this +also preserves that template's specular policy. + +Owned light identities persist across frames for occlusion filtering. They are +made black and disconnected from the spatial partition after rendering, then +reconnected before the next scene pass. They are removed when their projectile +is gone, becomes ineligible or the feature is disabled. Salted handles, object +ownership and the glow definition are checked before touching or deleting a +light. Map unload, new-map initialization, light-array recovery and shutdown +forget feature handles as the engine discards its light storage/partition. +No projectile simulation or network contract changes are introduced. + +The only new shared-engine wiring is in `source/objects/object_lights.c`: +a pre-visibility update and lifecycle reset calls, each marked `port:`. +A module-only attachment callback cannot create flight lights because stock +rockets have no light to invoke it. The new hook runs after light-array recovery +and before scene collection. All creation, selection and cleanup policy stays +in the feature module; existing Xbox, CE and MCC loading paths are unchanged. +The plasma module supplies existing falloff/model/occlusion integration. + +Capture tools accept `--kind rocket`; `--kind rocket --mixed --probe --burst 12` +creates three of each supported projectile kind. `--combat` equips the actual +launcher and uses ordinary trigger input. These diagnostic mechanisms never +enter the normal build. The first exploratory capture (`30-1-rocket-first`) +failed lighting-selection checks because no authored attachment existed; +`rocket-owned-first` verified the added light before the connection-state fix. +Neither is final acceptance evidence. + + +### Rocket validation + +The Windows release build and all 27 focused projectile-lighting, falloff, +model-shader, occlusion and owned-rocket-light harness tests passed. Negative +controls detect a removed rocket selector and a missing reconnect. The light +storage checks passed ordinary COFF, full LTO and their corruption negative +control. The capture builder restored production files and rebuilt the normal +executable; capture markers are absent from that executable. + +Hidden 640x480 captures were inspected at 30, 60 and 120 FPS. Measured averages: + +| Scenario, lighting and occlusion enabled | 30 cap | 60 cap | 120 cap | +| --- | ---: | ---: | ---: | +| Xbox Blood Gulch, flight and model impact | 29.99 | 60.03 | 119.99 | +| CE Death Island, clear flight path | 30.00 | 60.00 | 120.02 | +| Actual launcher trigger fire, Blood Gulch | 30.00 | 59.69 | 119.37 | + +Blood Gulch disabled controls averaged 29.66/59.98/119.99 FPS and selected no +feature lights or occlusion fields. CE disabled controls likewise selected +none. Blood Gulch had 12/36 changed render poses within unchanged simulation +ticks at 60/120 FPS; CE had 63/189. Controlled flights ended with zero selected +lights. The inspected Blood Gulch sequences show the stock fireball, smoke, +debris and target blast response with the feature on and off; they are not a +pixel-identical effects comparison. CE lighting is subtle against daylight. +Reports, logs, source manifests and images are retained under +`build/plasma-visual/*-rocket-*`; overviews are `rocket-bloodgulch-fps.png` and +`rocket-ce-flight-fps.png`. Runners are `build/rocket-matrix.py` and +`build/rocket-followup.py`. + +The first CE model-impact placement detonated within one tick and selected no +flight light. The revised clear-path capture resolves that fixture limitation. +Three runs failed before recording any gameplay frames with Windows exception +`c0000008` during graphics startup. Replacement CE captures and the repeated +120 FPS combat case passed; these startup failures remain recorded, not treated +as evidence of a gameplay lighting failure or a proven driver diagnosis. + +Stress limits remain: twelve overlapping mixed lights averaged 83.03 FPS at a +120 cap, and eight rockets with occlusion toggling averaged 49.52 at a 60 cap. +Both cases passed at 30 FPS (30.00/29.99), including all four projectile kinds, +the eight-rocket limit and no occlusion updates during disabled intervals. +These screenshot-heavy captures do not establish a general 120 FPS performance +guarantee. The Carousel specular-only probe selected a rocket light but recorded +zero specular draws and failed that acceptance check; rocket specular output is +not validated. The inherited template policy has not been overridden to force +highlights. + +Android and web builds were attempted, but this Windows configuration exposes +neither Ninja target (`unknown target`). Linux, Android, web and browser/native +internet interoperability remain unverified. No network data or simulation +rules changed, so no network version bump is required. + + +Two hidden native loopback peers completed ordinary launcher fire with lighting +and occlusion on for the host and off for the client. Both exited successfully +and agreed on one host kill, one client death and the client's respawn. The +host recorded 132 rocket submissions; the client recorded none and no feature +occlusion. Evidence is in `build/rocket-network-rocket`, with private runner +`build/rocket-network.py`. This checks local multiplayer with differing visual +settings, not internet latency or browser transport. + +Both active-fire transition runs (disabled at 30 FPS and enabled at 120 FPS) +completed Xbox Blood Gulch → CE Death Island → MCC Mercury Falling → Xbox +Blood Gulch. Both exited with status zero, completed all three transition +commands, loaded MCC once and logged no exceptions. This is lifecycle coverage, +not MCC visual acceptance. Reports and console logs are under +`build/rocket-transitions`; the private runner is `build/rocket-transitions.py`. +All copied test maps and derived map caches were removed; original maps and +saves remain untouched. + + +## Projectile lighting hardening (2026-10-14) + +This pass keeps both settings off by default and changes only the feature-owned +occlusion module and diagnostic tests/tools. It adds no shared-engine hooks, +map-family routing, network state, projectile simulation or explosion changes. +Muzzle flashes, CStencil and Modern remain deferred. + +Visibility fields retain the existing collision-ray count, refresh rules, +receiver reprojection, time-based clearing/blocking and overflow-admission fade. +The module now generates each model/diffuse/specular texture only when that +pass consumes it, at most once per view. It avoids trilinear sampling where +coordinates land exactly on texel centres and outside the attenuation sphere. +A failed texture upload falls back for that pass until the next view; it cannot +retry on every model draw. Texture masks are invalidated with each new field +update, and all allocated passes still release on reset. + +The regression harness checks all texels against the previous expression for +specular scales 0.5, 1 and 2 with partial admission, allowing one 8-bit rounding +level. It checks per-pass upload reuse, next-view invalidation, allocation +failure/retry, map reset, synthetic doorway/corner filtering and overflow fade. +A negative control removing mask invalidation must fail. + +The Carousel rocket specular investigation found the selected glow template to be +`weapons\plasma grenade\explosion`, flags `3`: dynamic plus no-specular. +Consequently zero rocket world-specular draws are intentional in that probe. +Blood Gulch selects `weapons\plasma rifle\muzzle flash`, flags `0x21`, which +permits specular; its outdoor receiver did not produce specular draws. Template +policy is map-dependent, and positive rocket-highlight coverage is not claimed. +The fixture now records the template flags, and the runner verifies this +policy instead of requiring highlights the template forbids. No explosion tag +is edited: the existing glow service supplies a definition for a separate +flight-light instance. Authored projectile light flags still take precedence. + +Performance diagnostics can use `tools/plasma_visual_run.py --no-images` to +remove screenshot readback/writes while retaining frame and selection logs. +Reports include active-light average FPS and 95th-percentile frame intervals, +as well as the whole capture average. These are instrumented 640x480 tests, +not a guarantee for every resolution, machine or map. + +Before optimization, twelve mixed lights at a 120 cap averaged 116.16 FPS with +screenshots and 119.99 without them; disabling occlusion also yielded 119.99. +The earlier 83 FPS result was not reproduced. Baseline evidence is in +`build/plasma-visual/*-harden-before-*` and `build/hardening-before.log`. +The baseline specular runner failed its old positive-draw expectation, prompting +the template-flag correction described above. + +An O2 harness benchmark exercises 800 field updates with synthetic collision +and model/diffuse consumers. Uploads fall from 2,400 to 1,600. Warm samples were +about 0.160–0.162 seconds before and 0.095–0.096 after; first-launch timings are +excluded. This measures CPU field generation with mocked collision/upload, +not GPU cost or a whole-game speedup. Script/results: +`build/hardening-cpu-benchmark.py` and `build/hardening-cpu-benchmark.json`. + + +### Hardening acceptance results + +The portable Windows release build and 28 focused harness tests passed, as did +ordinary/full-LTO light-storage checks and their negative control. The capture +manifest identifies base commit `5cc72528` plus the tested source hashes. Those +hashes match the final production modules, and the normal executable contains +no capture markers or fixture code. Self-review covered the complete diff; +no independent reviewer was used. + +| Final scene | 30 cap | 60 cap | 120 cap | +| --- | ---: | ---: | ---: | +| Twelve mixed lights, no screenshots | 29.75 | 60.00 | 119.99 | +| Rocket flight/model impact, screenshots | 30.00 | 59.99 | 119.99 | +| A10 moving door, plasma probe, screenshots | 30.00 | 60.00 | 119.99 | + +The 120-cap twelve-light screenshot run also averaged 119.99 FPS; its active +95th-percentile frame interval was 12 ms. Eight-rocket occlusion toggling +averaged 119.75 (11 ms active p95); the eight-rocket Carousel corner sweep +averaged 119.70 (12 ms p95). These demonstrate the tested average targets, +not a locked frame deadline. CE Death Island rocket flight averaged 120.02. +The 60 FPS disabled control selected no feature lights and did no occlusion +updates. Captures were inspected for rocket impacts, corner sweeps, moving +open/closed doors, model illumination and specular output. The stock fireball, +smoke and blast response remain visible. Coarse field-edge leakage remains an +approximation; this is not proof of artifact-free output on every map. + +The Carousel plasma specular-only case recorded 2,049 selected specular draws. +The rocket case recorded none, correctly matching its template's no-specular +flag. The three initial A10 rocket-door cases failed because A10 lacks the +rocket projectile tag; each logged three missing-tag messages. They are excluded +from acceptance, and the replacement plasma-door cases pass at all three caps. +Budget admission/turnover smoothing is covered by the synthetic harness; +real door motion and twelve-light pressure are separate visual scenarios. + +Final reports/images are under `build/plasma-visual/*-harden-final-*`, including +`sequence.png` contact sheets and `*-door-plasma/door-states.png`. Matrix and +follow-up scripts/results are `build/hardening-matrix.*` and +`build/hardening-followup.*`; `build/hardening-remainder.log` records follow-up, +network and transition execution. All 16 valid final visual/measurement cases +passed; the three unavailable-tag fixtures remain in the record. + +Two hidden native loopback peers, with lighting/occlusion enabled only on the +host, agreed on the host kill, client death and respawn and exited successfully. +The disabled peer logged no feature occlusion. Both transition runs (disabled +at 30, enabled at 120) completed Xbox → CE → MCC → Xbox with zero exit status, +all three commands, one MCC load and no logged exceptions. Evidence is in +`build/hardening-network-rocket` and `build/hardening-transitions`. This covers +local networking and map lifecycle, not internet/browser transport or MCC +visual acceptance. Copied test maps and derived caches were removed. + +The normal release executable also passed a hidden startup/load smoke test +with both settings false, no capture markers and a successful OpenGL context; +logs and its SHA-256 are in `build/hardening-playtest-smoke`. A Windows playtest +package uses these same executable/DLL bytes and keeps both options false. + +Android/web build attempts still report unknown targets: configuration records +no Android NDK and no Emscripten. WSL reports that it is not installed, so Linux +runtime validation is unavailable here. These platforms remain unverified. +No simulation or network payload changed; the network version is unchanged. + + +## Projectile visibility tuning + +The optional soft falloff now uses larger render radii: rifle bolts and authored +rocket attachments multiply their authored radius by 1.75, normal plasma-pistol +bolts by 2.25, and charged plasma-pistol bolts by 2.75. The charged bolt still +uses the rifle-directory tag. Feature-owned rocket flight lights use radius +1.75 instead of 1.0. The exact four-tag allowlist is unchanged. Plasma grenades, +needles, muzzle flashes and explosion lights are not added by this change. + +The wider radius raises illumination at a given surface distance through the +existing smooth attenuation curve. It does not multiply or clip RGB colours, +change lens-flare brightness, or remove authored no-specular flags. This keeps +plasma colour and soft edges while making the smaller pistol lights easier to +see. Bright outdoor materials will still show less contrast than dark interiors. +Both feature settings remain false by default. + +Policy remains in plasma_lighting.c and rocket_lighting.c. Minimal additive +hooks in object_lights.c are needed because its private light datum supplies +world/model receiver selection, and its private maximum-bound calculation +supplies visibility and cluster membership. Changing only rasterizer parameters +would leave the expanded light culled at its original bounds. The hooks apply +only to registered attachments or owned rocket lights with matching handles +and owners. Attachment registration precedes render-pose reconnection so the +partition sees the expanded bound immediately. Each attachment saves its prior +radius, restores it before simulation resumes, and reconnects with stock bounds; +map unload/recovery discards identities. Split views recompute from authored +radius rather than scaling previous output. Other lights retain their old bounds. + +No tag data, projectile simulation, stock explosion effects, network payloads, +map-family adapters or CStencil/Modern code changes. No network-version bump is +needed for this render-only policy. Xbox, CE and MCC continue through their +existing loading paths. + +Validation on Windows x86 portable release (full LTO): + +- Thirty focused harness cases pass, including negative controls, exact profile + scales, owner validation, maximum/actual/specular bounds, registration before + partition reconnection, split-view non-compounding and disabled cleanup. + Light-storage checks pass ordinary COFF, full LTO and the corruption control. +- All 32 main capture cases pass: each of four projectile types indoors on + Carousel and outdoors on Blood Gulch at 30/60/120 FPS; twelve simultaneous + mixed lights with model receivers at all three caps; disabled control; + CE pistol flight; a moving A10 door; isolated specular output; rocket impact. + Before/after images show wider coloured ground/wall illumination and stronger + nearby model lighting, with the soft edge and stock explosion effects retained. + Charged shots and Carousel's rocket template still forbid specular highlights. +- Actual weapon firing was captured at all three caps for all four types. + Eleven of twelve initial cases passed timing; the first 120 FPS pistol capture + averaged 111.85 FPS with 132/103 ms frame gaps. A targeted repeat averaged + 119.99 FPS with screenshots and 120.01 without; the old build also averaged + 119.68 without screenshots. The slowdown was not reproduced, but these runs + do not establish its cause. The original failed report remains in the record. + One old-build baseline rocket capture also missed timing outside its active + lighting interval; it is used for visual comparison, not performance acceptance. +- The twelve-light image captures average approximately 30/60/120 FPS, with + active-frame p95 of 34/18/12 ms respectively. These are short 640x480 tests on + this machine, not a locked-120 guarantee or a high-resolution GPU benchmark. +- Two hidden native loopback peers, feature enabled only on the host, exited + successfully and agreed on player state at tick 870. The disabled peer had no + occlusion updates. This run establishes local state agreement, not internet + transport, kill/respawn coverage or full networking compatibility. +- Disabled-at-30 and enabled-at-120 runs completed Xbox -> CE -> MCC -> Xbox, + with three transition commands, one MCC load and no logged exceptions each. + This is lifecycle coverage, not full MCC visual acceptance. Private copied + maps and derived caches were removed; original game data was untouched. +- The normal Windows executable passes hidden startup/load with stock settings, + contains no capture markers, and matches the capture manifest's source hashes. + Android/web build attempts report unknown targets (toolchains unavailable); + WSL/Linux is not installed. Those platforms remain unverified. + +Evidence: build/tuning-matrix.json, build/tuning-combat.json, +build/tuning-timing.json, build/tuning-network-rocket, +build/tuning-transitions and build/tuning-playtest-smoke. Per-run logs, timing, +images and build hashes are in build/plasma-visual/*-tuned-*; old-build comparison +runs use *-tuning-before-*. Comparison sheets are tuning-all-*.png, +tuning-caps-*.png and tuning-combat-caps.png in that directory. The refreshed +Windows package retains both options off and includes PLAYTEST.txt beside halo.exe. + + +## Dynamic lighting baseline review + +The polish review covers the existing optional feature, with every setting +still off by default. Production changes stay in feature-owned modules; no +`source/` hooks, loaders, simulation state, explosion effects, network messages, +CStencil or Modern code are changed. No network-version bump is needed for +these render-only changes. + +| Area reviewed | Outcome | +| --- | --- | +| `plasma_lighting.c` and attachment hooks in `object_lights.c` | Exact projectile selection, bounded attachment storage, rendered-pose refresh and restoration of radius/dynamic/partition state remain intact. Owned glows are excluded by the engine's parent-light contract. | +| `rocket_lighting.c`, `covenant_lighting.c` | Authored attachments retain precedence, missing-light fallbacks remain bounded, salted handles/owners are checked, and stock impacts/explosions are unchanged. No manager rewrite or broader custom-tag matching. | +| `muzzle_lighting.c` and successful-shot hook | Render-time envelope, duplicate-shot guard, marker selection, expiry and owner validation retained. Only Warthog pulses add vehicle collision blockers. | +| `covenant_emitter_lighting.c`, AR/Needler material and pose modules | Damage colours, held/dropped policy, first/world poses and map-owned shader caches reviewed. Fixed AR view-gain leakage; revised Needler falloff as documented in `covenant_emitter_lighting.md`. | +| `ammo_counter_falloff.c` | Reuse unchanged masks across views; invalidate on shape changes. Keep independent AR mask when occlusion is disabled or unavailable. | +| `plasma_occlusion.c` | Stationary fields reuse the previous cell directly; moving/resized fields retain trilinear reprojection. Removed a redundant same-view check. Collision refresh, admission, edge filtering, fade rates and eight-field limit remain unchanged. | +| `plasma_falloff.c` and world/specular hooks | Stock texture/filter restoration, allocation fallback and cleanup retained. Shared radial volume remains lazy and bounded. | +| `plasma_model_shader.c`, `plasma_occlusion_gl.c`, shader translation and binding hooks | Selected two-light slots preserve stock alpha/material/cone paths. Reserved samplers, fallback texture and active texture restoration reviewed. Uniform-location/sampler caching is a possible later measured optimization; no shared renderer rewrite is justified by this pass. | +| Settings/build/lifecycle integration | Existing registrations, false defaults, feature-off paths, map cleanup and failed-load/recovery boundaries retained. Xbox/CE/MCC loaders and ownership boundaries are unchanged. | + +The stationary shortcut is compared against full reprojection cell by cell over +synthetic moving lights, changed extents, door transitions and 30/60/120 Hz +sequences (absolute tolerance 0.00001). Cache tests cover unchanged views, +translation, radius, rotation, profile changes and cleanup. These establish +saved work and equivalent visibility, not a claim of a measured whole-game +FPS percentage. Geometry queries and GL binding remain potential costs; +reducing their quality or cadence was not part of this optimization. + +### Polish validation and limits + +- All 57 focused lighting regressions pass on the final production sources. + Light-storage COFF/LTO checks and the negative legacy-corruption control pass. + The broader harness/cache/viewmodel run has 506 passes, four skips and 28 + compile failures outside changed files: missing pthread support (10), missing + clock_gettime/CLOCK_MONOTONIC (6), and Windows __int64 typedef conflicts (12). + That broader run is not a green suite. +- The primary 53-case Windows capture matrix covers AR/Needler first/world views, + both Jackal colours, stationary shields, held fuel rods, Warthog muzzle pulses, + mixed plasma/rocket shots, twelve-Needle stress, moving doors, runtime toggles + and per-pixel receivers at 30/60/120 FPS, plus eleven disabled cases at 60 FPS. + All functional checks pass; 49 runs meet the timing threshold. Original + screenshot timing failures remain recorded: AR first-person 30 (26.65), AR + world 60 (49.37), Warthog 30 (26.91) and Warthog 60 (52.17 FPS). + Separate final-source runs without screenshot readback pass at 30.01, 60.00, + 30.00 and 60.00 FPS respectively. Capture overhead is a plausible contributor; + the repeats do not prove the cause of every original stall. +- Final-source follow-ups exercise front-facing radial Needler spill with wall + occlusion off at all three caps and first-person fallback at 60. The front + standing-player images show weapon/upper-body spill without a foot-level pool. + The c40 Grunt fixture creates an emitter but does not frame the holder usefully; + it does not establish low-NPC visual acceptance. A front-facing Marine on b40 + passes at 60.01 FPS and shows upper-body/weapon glow without a foot-level pool. + Unusual/crouched poses remain + a player acceptance item, rather than a claim of precise mesh shielding. +- A synthetic five-pair benchmark of 1,000 stationary updates reduces median + CPU time from 88 to 53 ms, with the same 1,536,000 stub collision queries. + Two unchanged mask variants over 1,000 views require two uploads instead of + 2,000. This measures avoided work with fake collisions/uploads, not game FPS. +- Hidden Xbox c40 -> MCC Mercury Falling -> Xbox Blood Gulch transitions pass + disabled at 30 FPS and enabled at 120 FPS, with two commands, one MCC load, + clean exit and no logged exceptions each. The first sandboxed attempt could + not connect its localhost console and is retained as a failed fixture run. + This checks lifecycle/load boundaries, not full MCC visual compatibility. +- Two hidden native loopback peers exit cleanly after 100 seconds and both + submit Needler emitter samples (4,919/4,925). Of 84 common player snapshots, + 19 match exactly; all 84 match excluding loaded-ammo counts, which differ + during firing. Final tick 2520 matches exactly. This is a bounded native + regression check, not bit-identical live prediction or browser/internet + transport acceptance. See `build/polish-network-needle/comparison.json`. +- The normal Windows portable release builds successfully, matches the final + capture manifest's production hashes and contains no capture markers. + Local Linux is unavailable (no WSL), and Android/web targets are unavailable + in this Windows configuration. Those builds require CI; runtime acceptance + on other platforms/GPUs remains separate. Local CE assets are absent, so no + current CE runtime compatibility claim is made. Shared loaders are unchanged. + +Evidence remains under `build/polish-acceptance.json`, `build/polish-followup.json`, +`build/polish-regressions-final.log`, `build/polish-full-tests.log`, +`build/polish-benchmark.json`, `build/polish-production-check.json` and the +per-run reports/contact sheets in `build/plasma-visual`. Captures are short, +640x480 fixtures on one Windows/NVIDIA machine, not a locked-120 guarantee. +The primary matrix predates only the final unoccluded specular-height correction; +final-source regressions/follow-ups cover that correction. Original game maps +and saves are preserved; private map copies are removed after each run. + +## October 25 integration and menu acceptance + +`main` at `2e69a88e` was merged without conflicts as `e5c43aeb`. The fixes +in `e91ba84f` retain source hue in enhanced world-specular reflections and +restore generated setting-row input after pointer/controller focus changes. +See the [rendering walkthrough](reading/rendering.md#dynamic-lighting-branch-notes) +and [menu walkthrough](reading/settings_input_and_menus.md#evidence-and-useful-checks) +for the call paths and isolation rationale. No settings defaults, network +protocol, projectile simulation, effect tags or stock explosions changed. + +The final combined review covered both fixes, the merged interfaces, +feature selection/reset lifetime, stock constant identity, setting metadata, +generated-menu consistency, regression tests and these reading routes. +The inactive tint path returns the original packed colour directly. No +broader renderer or Xbox-widget refactoring was needed. + +Local Windows portable release validation: + +- The build passed. The merge's focused MCC HUD/loading/pause/UI checks + passed (445 tests); final lighting, menu, XML and settings checks passed + (96 tests). The colour and focus regressions include negative controls. + Light-storage ordinary/full-LTO checks passed and detected the deliberate + legacy-pointer corruption control. +- Fourteen controlled Carousel captures passed: pistol, rifle, rocket and + Needler at 30/60/120 FPS, plus disabled and specular-only pistol captures. + Measured average ranges were 29.26–30.00, 59.99–60.02 and 119.99–120.01 FPS. + These are short 640x480 fixtures on one Windows/NVIDIA machine. Rockets + and Needler fallback templates on this map prohibit world specular; + that authored flag remains respected. The hue correction is exercised + by the pistol and rifle, not inferred from those no-specular cases. +- Custom Edition Death Island's pistol fixture passed at 60 FPS, including + selected model lighting. This scene did not submit world-specular draws; + it is a CE runtime/feature compatibility check, not CE specular acceptance. +- The normal executable switched all eight menu toggles on and saved them, + loaded them in a fresh process, discarded edits through both Cancel and + controller Back, discarded pending Defaults through Cancel, saved Defaults, + saved all eight off, reloaded off, and saved an unchanged screen. Logs and + configuration files were checked against expected values. Captures show + pending values as well as loaded values. Video Setup entry and return worked; + 640x480 and 1280x720 layouts were inspected. No menu XML edit was necessary. +- The first menu attempt used the executable directory's configuration rather + than the runner's data directory. It was excluded from acceptance and the + runner was corrected to use isolated executable/config locations. A separate + a10 projectile placement attempt never reached a selected draw and is also + excluded; Carousel supplied the reflective test surface. + +Evidence is retained in ignored `build/oct25-final-tests.log`, +`build/oct25-merge-tests.log`, `build/oct25-light-storage.log`, +`build/oct25-menu-results.json`, `build/oct25-menu/`, +`build/oct25-visual-results.json`, `build/oct25-final-contact.png`, +`build/oct25-ce.log` and the `oct25`-labelled `build/plasma-visual/` runs. +Local Android/web targets were unavailable and WSL is not installed; +platform builds are checked by CI rather than claimed as local runtime tests. + +The [four-platform Build run](https://github.com/chestahh/GulchCE/actions/runs/40222493166) +passed for `e91ba84f`. Xbox c40 → MCC Mercury Falling → Xbox Blood Gulch +transitions completed with all lights off at 30 FPS and on at 120 FPS, +each with one confirmed MCC load, both transition commands and no exception. +These verify load/cleanup boundaries, not MCC campaign or visual acceptance. +The sandboxed attempt could not reach its loopback console and is excluded; +the successful runs are under `build/oct25-transitions-localhost/`. + +A normal-build Windows two-peer Blood Gulch smoke test used all eight +lighting settings on for the host and off for the client. Both exited +normally, with 37/33 two-player snapshots, eight scripted shoot events each +and no logged assertion, exception or shader failure. This verifies basic +mixed-setting session operation, not full state equivalence or internet/ +browser crossplay. `tools/net_compare.py` could not run on Windows because +its process driver requires Unix signal APIs; the local Windows runner and +results are retained in `build/oct25-network-smoke.py` and +`build/oct25-network-smoke/`. + +The [MCC validation workflow](https://github.com/chestahh/GulchCE/actions/runs/40222493204) +also passed. Temporary capture executables, copied maps and generated map +caches were removed. Selected screenshots remain as lossless PNGs; inactive +test saves were losslessly archived in `build/oct25-inactive-saves.zip`, with +original relative paths and SHA-256 hashes verified before removing loose +copies. Approximately 128 MiB of diagnostics remain, plus the 13.4 MiB +Windows playtest ZIP outside this worktree. Original game data, active +saves and existing toolchains/build outputs were preserved. diff --git a/docs/reading/README.md b/docs/reading/README.md index 17d89b7dc4..7eb7f707c5 100644 --- a/docs/reading/README.md +++ b/docs/reading/README.md @@ -1,39 +1,175 @@ -# MCC support reading guide +# Reading the GulchCE code -MCC compatibility uses independent modules and the `mcc_maps` namespace. -Xbox and Custom Edition retain their existing loaders and resource roots. +This guide is for someone who can follow individual lines of code but wants +to understand how they fit together. Start with one visible behaviour and +follow the values it uses through a few functions. You do not need to read +the engine from beginning to end. -## Scope and provenance +Start with [startup and the game loop](startup_and_loop.md) for the overall +structure, keeping the [glossary](glossary.md) nearby. For a smaller first +example, the [FOV walkthrough](field_of_view.md) follows one setting from +the menu to the camera, reticle and first-person weapon. -The implementation is in this repository (`port/linux/game/mcc_*.c`, -`port/linux/src/mcc_*.c`, and the platforms' import code). These documents -came with it from the source branch it was developed on, -[GET-YOUR-MCC-HERE at 1db929c5](https://github.com/chestahh/GulchCE/tree/1db929c5e34101a45f644436e031016b5584c7bf). -That branch has more tests than were brought here; links to tests that are -not in this repository point to its commits. Its logs keep their original -branch names, protocol numbers and test commands. MCC maps play with OpenCE's -network version (`HALO_PORT_NETWORK_VERSION`). +## The complete reading route -## Reading order +| Order | Chapter | Concrete example and main question | +| --- | --- | --- | +| 1 | [Startup and the game loop](startup_and_loop.md) | Launch, enter a local map and draw between ticks: what runs when? | +| 2 | [Settings, input and menus](settings_input_and_menus.md) | Save a setting and push a stick forward: how does an action reach the game? | +| 3 | [Objects and gameplay](objects_and_gameplay.md) | Spawn, control and retire a player's body: who owns its state? | +| 4 | [Rendering](rendering.md) | Draw a room and moving player: how do poses become pixels? Includes dynamic lighting 1.0, [emitter additions](emitter_expansion.md), and separate Vulkan branch notes. | +| 5 | [Networking](networking.md) | Move a client player: what is predicted, validated, relayed and corrected? | +| 6 | [Maps and resources](maps_and_resources.md) | Load a package level: how do Xbox, CE and MCC readers keep their data and lifetimes separate? | +| 7 | [Platforms and testing](platforms_and_testing.md) | Follow platform entry points and investigate an elevator regression: what evidence reaches the behaviour? | +| Worked detail | [Field of view](field_of_view.md) | Trace a setting through the actual calculations and temporary rendering state. | +| Optional hardware | [DualSense feedback](dualsense.md) | Map physical trigger actions to feedback and clear it across gameplay and device lifecycles. | +| Worked detail | [Doppler audio](audio_doppler.md) | Follow source and camera motion into pitch, and distinguish Xbox behavior from optional stereo-source Doppler. | +| Feature prototype | [Modern frontend](menu_redesign.md) | Isolated Settings/hosting/lobby views, native browsers and main-menu-only legacy switching. | +| Branch feature | [Shoulder camera](third_person.md) | Director selection, cover-aware aiming, controls and host-owned hit validation. | +| Worked detail | [Loading presentation](loading_presentation.md) | Fill the screen with the original loading artwork while preserving map-family ownership and the Xbox chant. | +| Worked detail | [MCC level previews](mcc_level_previews.md) | Resolve installed package images, fit them inside existing menu thumbnails, and wrap package text. | +| Worked detail | [Xbox audio processing](xbox_audio.md) | Follow measured HRTF, reverb and voice processing through the shared mixer. | +| Worked detail | [Browser map imports](browser_imports.md) | Keep Xbox, CE and MCC files separate while importing, sharing, recovering interrupted writes and coordinating tabs. | +| Worked detail | [Console commands across checkpoints](console_checkpoints.md) | Preserve a sleeping command's syntax and text while restoring saved threads across all map families. | +| Reference | [Glossary](glossary.md) | Engine concepts and recurring C conventions, with source examples. | -- [Loading, resources and host sharing](maps_and_resources.md) -- [Console syntax and checkpoint lifetime](console_checkpoints.md) -- [Map formats, installation and compatibility evidence](../mcc_maps.md) -- [Stock-menu package previews and completion](mcc_level_previews.md) -- [Browser imports, storage ownership and recovery](browser_imports.md) -- [Host-only package sharing and protocol agreement](../../port/linux/NETCODE.md#mcc-package-sharing) +The chapters form a guide to the major systems, not an inventory of every +function or a claim that every feature is fully supported. Each includes +a reading route, state/lifecycle constraints, examples and evidence limits. +Detailed design notes remain linked references. Follow those when a question +needs packet layouts, map-format fields or the exact limits of a feature. -The format reference separates inspected structures from inferred behavior. -The validation record distinguishes compilation, automated checks and bounded -runtime observations; it does not claim complete campaign playthroughs. +## Where the pieces live -## Optional input prompts +GulchCE is a fork of OpenCE. Both compile the decompiled Xbox game with a +platform layer in place of the Xbox services. GulchCE also has its own +features and MCC compatibility modules. A directory's name does not always +tell you which platforms compile it: much of `port/linux/` is shared. -[Keyboard prompts and PC-menu glyphs](keyboard_prompts.md) describes the opt-in -renderer and its MCC-owned pause footer adapters. It also records the unchanged -controller, Xbox-menu and disabled-feature paths. +| Place | Read it to understand | +| --- | --- | +| [source/](../../source/) | The original engine's gameplay, cameras, rendering and data structures, with marked port changes. | +| [port/linux/game/](../../port/linux/game/) | Added game features and integration with engine types: menus, FOV, networking, map support and mods. | +| [port/linux/src/](../../port/linux/src/) | Settings and platform services, including the OpenGL implementation of the graphics calls the game makes. | +| [port/linux/include/](../../port/linux/include/) | Shared limits, compatibility headers and declarations that connect game code to the port. | +| [port/windows/](../../port/windows/), [port/android/](../../port/android/), [port/web/](../../port/web/) | Platform-specific entry points, runtime support and build details. | +| [tools/](../../tools/) | Build scripts, asset generators and tests. Some menu content is generated here rather than written directly. | +| [docs/](../) | Detailed explanations of features, formats and compatibility decisions. | -## Shared audio processing +For example, changing an FOV setting travels from menu code in +`port/linux/game/` to configuration code in `port/linux/src/`. The engine +in `source/` later calls the FOV module while preparing a view. These are +connections between responsibilities, not separate copies of the game. -[Xbox audio processing](xbox_audio.md) covers measured HRTF, reverb, resampling, -levels and their limitations across all map families. +MCC compatibility has its own modules and boundaries. Use the boundary +inventory in [CODINGSTANDARDS.md](../../CODINGSTANDARDS.md) to find them. +Xbox, Custom Edition and MCC support are not interchangeable loading paths; +the map-family isolation rules are in [AGENTS.md](../../AGENTS.md). + +## How to follow a feature + +The [optional bots and Android controls walkthrough](bots_and_android_features.md) +follows host-owned bot actions, objective/tactical additions, gyro modes and +the offline cheat menu, including lifecycle boundaries and source credits. + +1. Start with a concrete question, such as "what changes when I select + 120 degrees?" Find the setting name or the function that handles the + visible action. +2. Read the feature's header and opening comment. A `.h` file usually + describes the interface other files use; the `.c` file implements it. +3. Find one caller and one consumer of the result. Establish what goes in, + what comes out, and which state is modified before following helpers. +4. Read the early returns. They often explain when a feature must leave + the existing behaviour alone. +5. Identify state that survives the call. Ask who updates it, who reads it, + and when it is reset or restored. A per-player array and a single shared + variable have different implications in split screen. +6. Read the relevant tests and their limits. A calculation checked in a + fake world does not establish that the final picture looks correct. + +Use your editor's search for the exact function name. From the repository +root, these searches also locate the FOV walkthrough's entry points: + +```sh +rg -n 'render_fov_vertical' source port/linux/game +rg -n 'display.fov' port/linux/src/port_config.c tools/port_settings.py +``` + +There is no need to follow every dependency immediately. If a helper's +contract is clear, continue with the value it returns and revisit its +implementation when it matters to the question. + +## Reading inherited code and port additions + +Changes in the decompiled `source/` are marked with comments beginning +`port:`. These show where to look for an integration point; they do not +by themselves say whether OpenCE or GulchCE introduced it. Use file history +when authorship matters. The FOV module in the detailed walkthrough is an +existing port feature, not a new GulchCE implementation added by this guide. + +Some source files start with long symbol lists and addresses from the +decompilation. Start at the includes and function definitions when learning +the current code. Similarly, original Xbox paths in assertions are historical +context, not paths you need to create on your computer. + +Build definitions matter. Code behind a preprocessor condition may not run +in the build you are reading about. See the Defines table in +[AGENTS.md](../../AGENTS.md); in particular, `HALO_LINUX` and +`HALO_CUSTOM_EDITION` are not defined by these builds. Runtime settings and +compile-time conditions answer different questions. + +## What an explanation should establish + +A walkthrough should connect the visible behaviour to named functions, +trace a concrete example, explain the important constraints and identify +the checks that support it. Use a small flow diagram when the order of +calls is easier to see than to describe. Explain unfamiliar terms where +they first matter and add reusable definitions to the glossary. + +Distinguish what the implementation does from why a choice was made. +Existing comments and design notes may explain the reason; otherwise label +an interpretation as an inference. A source trace, an automated test and +an observation in a running game are different kinds of evidence. Record +known gaps instead of implying that a readable explanation proves correctness. + +Keep links relative to the document and name functions beside them. Line +numbers move as code changes. Quote only the small expressions needed for +the explanation, and update a guide when its described behaviour changes. +The maintenance expectations are in [AGENTS.md](../../AGENTS.md). + +The source review for this edition used GulchCE's `testing` baseline +`b746de54`, plus `dynamic-lighting-test` at `54e149e0`, `vulkan-renderer` +at `394e360e`, `online-third-person` at `7562fedf` and `main` at `42238c20`. +These identify inspected source states, not new gameplay test results. +Branch-only files are linked to their GulchCE branches because they do not +exist in every checkout. Branch links can move; use the recorded revision +and file history when comparing a later implementation with this explanation. + +## Where to read next + +| Question | Reference | +| --- | --- | +| How does the port compile and replace Xbox services? | [How the port operates](../../port/linux/README.md#how-the-port-operates) | +| How do settings affect the game? | [Settings](../../port/linux/README.md#settings) and the [FOV walkthrough](field_of_view.md) | +| What do the host and clients each decide? | [Distributed netcode](../../port/linux/NETCODE.md) | +| How are Custom Edition maps loaded? | [Custom Edition caches](../custom_edition_caches.md) | +| Where are GulchCE's MCC boundaries? | [Coding standards](../../CODINGSTANDARDS.md#scope-and-implementation-boundaries) | +| How do menu generators relate to the saved XML? | [Menu assets](../../port/assets/menus/README.md) | +| What can tests establish without retail assets? | [Harness](../../tools/harness/README.md) and [Stagekit](../../tools/stagekit/README.md) | + +[HUD artwork corrections](hud_corrections.md) explains the supplied reticles, +zoom labels, transparent Classic letters and separate map-family handling. + +[Controller detection and button styles](controller_buttons.md) follows device identity, +automatic family filtering and gameplay glyph ownership. + +[Controller button remapping](controller_remapping.md) covers the Gamepad Setup +submenu, P1-P4 layouts, physical input isolation and prompt updates. + +- [Keyboard and mouse prompt glyphs](keyboard_prompts.md): manual style, automatic input switching, binding-aware gameplay and smooth keycap rendering. + +The [standalone enhanced bot controller](enhanced_bots.md) explains stock/enhanced +ownership, goal arbitration, boarding, aircraft routes and validation limits. + +The [network bot population walkthrough](bot_population.md) explains human-only +listings, automatic replacement/restoration and the OpenCE crossplay boundary. diff --git a/docs/reading/audio_doppler.md b/docs/reading/audio_doppler.md index 24210465ae..6d04dead93 100644 --- a/docs/reading/audio_doppler.md +++ b/docs/reading/audio_doppler.md @@ -44,7 +44,7 @@ read by `DirectSoundDoWork`; a playing voice glides to its new pitch over 2. In [sound_manager.c](../../source/sound/sound_manager.c), read `refresh_listener`, `listener_measure_velocity` and `update_channels`. `director_get_followed_unit` in [director.c](../../source/camera/director.c) - recognizes first person, following and dead cameras. Their + recognizes first person, following, shoulder and dead cameras. Their listener velocity uses the same point-motion calculation as sounds. Scripted and free cameras use focus displacement per simulation tick, rather than frame-dependent observer velocity. @@ -89,7 +89,7 @@ stereo/5.1 output. Fault injection checks that the regressions are detected. [Listener tests](../../tools/harness/tests/test_listener_motion.py) exercise the actual measurement and camera functions, including short same-tick cuts, smooth motion, repeated zero-transition co-op camera updates, slot -reuse, reset and followed-camera selection. +reuse, reset and shoulder-camera selection. These checks establish calculation behavior. They do not establish perceptual equivalence to retail Xbox hardware. Map transitions, checkpoints and moving diff --git a/docs/reading/bot_population.md b/docs/reading/bot_population.md new file mode 100644 index 0000000000..40517937db --- /dev/null +++ b/docs/reading/bot_population.md @@ -0,0 +1,138 @@ +# Human population and automatic network bots + +GulchCE hosts advertise humans only in internet and LAN player counts, master +listings and Discord presence. Bots still occupy the normal gameplay roster, +score and consume player slots. The browser adds advertised human counts for +its population total; it does not infer bots from names or machine numbers. + +Both stock and enhanced bots have a `BOT ` display-name prefix, for example +`BOT Johnson` and `BOT Bisenti`. The existing network name holds eleven visible +characters, so longer names are shortened. Additional bots retain a unique +number, for example `BOT Johns16`. `bots_network_player` in +[bots.c](../../port/linux/game/bots.c) creates these names for lobby admissions, +live additions and restored bots. This uses the ordinary player-name field; +OpenCE clients receive the same names without a protocol change. A human using +a `BOT ` name is still a human because population policy uses host ownership. + +When `bots.network` is enabled, both stock and enhanced bots automatically +make room for humans and return when humans leave. There is no additional +toggle. Existing local-only bot behaviour and each controller's decisions are +unchanged. Xbox, Custom Edition and MCC retain their existing loaders and +session compatibility boundaries. + +## One example + +One initial human and Bot Count 15 establish a target of 16 occupants, provided +the server allows that many. A second human replaces one bot: two humans and +14 bots. When that human leaves, a bot returns. Humans can exceed this target +up to the server limit; bots return only when human population falls below the +target. Restoration never exceeds the requested bot count or the 63-bot limit. +Consequently a dedicated server's running match with no humans can retain the +requested bots without filling the space previously occupied by its initial human. + +The target survives map changes in the same host session. A changed Bot Count +establishes a new target from the current humans. Manage Current Bots and the +add/drop console commands adjust the live target without changing saved Bot +Count. An explicit addition also raises the target to accommodate the current +population if humans have already exceeded it. Disabling network bots in the +lobby or closing the host resets policy. + +## Reading order + +1. [bots_network.c](../../port/linux/game/bots_network.c): `bots_human_count` + filters actual host ownership. `bots_population_wanted` establishes the + target and computes restoration; `bots_population_after_join` accounts for + an arriving human before admission. A high-ID human is still counted. +2. [bots_population.inl](../../port/linux/game/bots_population.inl): + `bots_population_can_join` exposes replaceable capacity; + `bots_population_pregame_join` releases a lobby bot; + `bots_population_wait_for_slot` coordinates a live departure and admission; + `bots_population_update` restores bots after departures. +3. [bots_management.inl](../../port/linux/game/bots_management.inl): + `bots_manage_change` uses the existing addition/removal messages and bot + identity cooldown. `bots_manage` additionally changes the target for an + explicit host command. Automatic changes leave the target intact. +4. [network_server_manager.c](../../source/networking/network_server_manager.c): + `network_game_server_idle`, `network_game_server_add_player_to_game` and + the queued addition branch integrate these policies with the private server + roster. The live queue retains a human while a departing bot holds a slot. + `network_game_server_accepts_late_joins` and the listing expose replaceable + capacity while retaining the existing session-open and state checks. +5. [network_server_message_handler.c](../../source/networking/network_server_message_handler.c) + publishes the same human count and open status in discovery replies. + [server_director.c](../../port/linux/game/server_director.c) uses that count + for master publication, without changing gameplay population decisions. + +The shared hooks are necessary because admission, the queue and discovery +messages belong to the engine's networking implementations. Policy and state +remain bot-owned; the hooks do not replace map-family implementations. + +## Ordering and compatibility + +Only a validated connection requesting a new, valid player can displace a bot. +Existing ownership, controller bounds, duplicate suppression and join-rate +limits apply. Map downloaders wait in the existing held list; they do not +remove bots before their maps are ready. Pending player additions take priority +over restoration. Concurrent and split-screen requests use the existing queue. + +A bot leaves through an ordinary scheduled player-departure message. Its unit +can continue to hold the player datum (the engine's player record) until +cleanup. The queue waits for an ordinary usable slot, for at most ten seconds; +it never forces a datum or bot identity to be reused early. Cancellation and +timeouts allow the population to refill. Restoration checks once a simulation +second and retains the existing team policy. + +OpenCE clients receive ordinary joins, departures and controls. No packet +layout, new field, simulation rule or peer capability is introduced. Discovery +continues to carry a host-supplied population count and capacity; gameplay +settings retain the complete roster. This host admission policy needs no new +protocol version. The [crossplay baseline](../../port/linux/NETCODE.md) still +applies; MCC and third-person sessions retain their separate requirements. + +Bots reserve their existing machine-ID range until the host closes. Replacing +bots frees player slots, not those reserved connection identities. Existing +machine, split-screen, map-download, closed-game and player limits still apply. +Other hosts and forks determine their own advertised counts. + +## Checks + +[test_bots_lobby.py](../../tools/harness/tests/test_bots_lobby.py) compiles the +real policy, management and roster functions. It covers human-only counts, +high-ID humans, full lobbies, live joins, held slots, bounded waits, cancelled +requests, split-screen/concurrent admissions, restoration, manual commands, +empty-human sessions and lifecycle boundaries. Mutation controls verify that +breaking count filtering, target accounting, queue priority, manual target +changes or timeout enforcement fails its regression. The existing stock-bot +preservation and OpenCE protocol-layout checks cover their unchanged contracts. + +On 6 November 2026, Windows hosts were exercised against the unmodified official +OpenCE build 337 client (commit `899219cc0a14b03bc12f0517a1e9ee4c37158af8`). +The downloaded Windows release matched its published SHA-256 checksum. +Xbox Blood Gulch was tested with stock and enhanced bots; Custom Edition +Death Island was tested with enhanced bots. Each run admitted and disconnected +the OpenCE client twice. Each admission removed one bot and each departure +restored one. OpenCE's discovery probe reported one human, open admission and +network version 41 while the host had fifteen bots. The enhanced Blood Gulch +run was repeated after the admission review corrections. The later manual-add +target correction was verified by the source harness and rebuilt on all three +platforms; the automatic join/leave paths were unchanged by that correction. + +Host per-tick movement drift passed the existing `net_compare.py` tolerances. +This is not a full world-state equivalence result: late-join logs sometimes +have no samples close enough in time for pair comparison, and a departed +player can remain in the host's score history but not a newly joining client's. +Full-capacity admission, held player slots and concurrent/split-screen requests +were exercised in the source harness, rather than with a full live server. + +Windows release, Android guest/host libraries and web builds passed. The web +JavaScript suite passed. MCC admission tests exercised both capability states +and confirmed that replaceable bots do not bypass tokens, bans or closed games. +There was no MCC map runtime run for this change; no MCC test maps were available +in the local test data. The existing separate MCC protocol remains required. + +Runtime crossplay used local network transport. Native/browser WebRTC could +not start because its runner constructs Unix paths on Windows; the internet +game runner could not start because `mosquitto` was unavailable. Linux runtime, +browser internet gameplay and physical Android device behavior were not verified. +The implementation commit records the final regression totals. Unit tests and +successful builds alone do not establish complete crossplay or map compatibility. diff --git a/docs/reading/bots_and_android_features.md b/docs/reading/bots_and_android_features.md new file mode 100644 index 0000000000..c543a3b6ef --- /dev/null +++ b/docs/reading/bots_and_android_features.md @@ -0,0 +1,519 @@ +# Optional bots and Android controls + +These are GulchCE additions. Their defaults preserve OpenCE's local Slayer +bots and Android's saved touch layout. Xbox, Custom Edition and MCC keep +their existing map loaders, limits, rules and resource ownership. + +## What players can enable + +- `bots.enhanced = true` adds CTF and King of the Hill goals, team roles, + precision-weapon vantage choices and powerup selection. It is read at map + load. Enhanced combat, pathfinding and recovery have their own controller and + state; stock Slayer decisions remain in `bots.c`. Spawning uses the engine. +- `bots.routes` selects `direct` (default), `lanes` or `mixed`. A lane is an + alternate route through two intermediate destinations. Unreachable lanes + are abandoned for that bot's current life. +- `bots.thread = true` moves enhanced bots' graph searches to a bounded + background worker. **Path Worker** in Bot settings controls it; it is off + by default and takes effect on the next map. Collision queries and action + decisions still run on the game thread. +- `bots.vehicles = true` lets enhanced bots seek ground-vehicle seats, aircraft and + turrets, including nearby friendly player transports. They use ordinary + player controls to enter, steer and leave. Aircraft have bounded 3D routes + and require a slow grounded landing before exit. Switching this option off + asks ground riders to leave and aircraft pilots to land; disabling enhanced bots takes effect on the next map. +- `bots.network = true` permits bots on a network host. Set it before + creating the host or apply it with **OK** in the lobby's Bots settings; + `bots.count`, `bots.skill` and `bots.teams` still apply. + Up to 63 bots join, subject to the lobby's player limit (63 bots plus one + human need at least 64 player slots). The default count remains zero. + Network bots automatically yield to joining humans and return when humans + leave; the browser counts humans only. The [population walkthrough](bot_population.md) + explains the target, join ordering and OpenCE compatibility. +- In the CE menus, **Settings > Network > Bots** configures count, network + admission, difficulty, teams, enhanced tactics, vehicles and routes. + **Create Game** and the host's lobby also have a **Bots** button. During + a match, open **Settings > Network > Bots > Manage Current Bots** to add + or remove one bot on either team, or let Any Team balance a team game. + Live changes adjust the session population target without changing the + saved lobby count. Clients cannot manage + the host's bots. Xbox menu artwork and navigation remain unchanged. +- Android's **Settings > Gamepad > Android Controls > Gyro Aim** offers + **Touch Settings**, **Off**, **On** and **Zoom Only**. Touch Settings is + the default and preserves the layout's saved gyro switch and sensitivity. + Explicit modes use independent horizontal/vertical sensitivity and invert + settings. Zoom Only discards motion while unzoomed. +- Touch Options can be moved in the layout editor; Export, Import and Save + sit in its center. General settings can disable aiming with held buttons + and choose a three- or four-finger tap for enabled cheats. Older + layouts retain their saved controls and gyro behavior when loaded. + OpenCE version-4 layouts omit GulchCE's `menu-fingers` field; importing + those files uses the existing three-finger cheat gesture default. +- Android's **Cheat Menu** option adds a **CHEATS** touch button beside + **Hide/Touch**, as well as **Cheats** in touch **Options**. The button is + available during offline or hosted gameplay, including when the gameplay controls + are hidden; the layout editor and cinematics hide it. Tapping opens the + existing dialog through `openDialog`, which releases held controls. + It defaults off and is unavailable to joining clients, including while joining + a lobby. Android hosts use the same cheat APIs as desktop hosts. It exposes + invincibility, ammunition, bottomless clip, super jump, omnipotence, + no fall damage, Medusa, bump possession, Easy Rider, weapon/powerup/vehicle + spawning and camouflage through existing engine cheat APIs. Easy Rider + disables rider ejection; it does not change the saved game's defaults. + +For example, set `bots.count = 6`, `bots.enhanced = true`, +`bots.network = true` and `bots.routes = "mixed"`, then create a CTF host. +Six bots join as ordinary players if the lobby has space. The host decides +their goals and publishes their controls. A client needs the same map and a +compatible OpenCE protocol, but does not run the new bot AI. MCC sessions +still require GulchCE's existing MCC support and negotiation. + +The complete settings and environment variables are in +[the port settings table](../../port/linux/README.md) and +[the Android guide](../../port/android/README.md). + +## Read the bot flow + +1. [bots_network.c](../../port/linux/game/bots_network.c): + `bots_network_session_begin` initializes admission policy; + `bots_player_ownership` records synthetic players actually created by + this host. A high machine number alone never grants bot ownership. + `bots_network_lobby_enable` changes admission only after the bot management + module checks the pregame state and unused machine IDs. Disabling it + removes lobby bots but retains the reservation until session disposal. +2. [network_server_manager.c](../../source/networking/network_server_manager.c): + `network_game_server_port_bots` retains the existing lobby, team and + capacity rules. An opted-in host reserves the final 63 machine IDs; + ordinary hosts retain all human machine slots. + `network_game_server_update_countdown` also asks `bots_lobby_can_start` + in the bot module whether one human machine has owned bots. Those bots + have synthetic machine IDs but no connections, so the ordinary + **START NOW** request can start play without another computer joining. + Upstream now starts immediately for the host; a client request only + shortens the countdown. This hook only extends the inactive-countdown start gate; + existing player minimums, team requirements and countdown pauses still + apply. It adds no session state or network messages and applies equally + to Xbox, Custom Edition and MCC lobbies. High-ID human players never + acquire this permission merely from their IDs. + [bots_management.inl](../../port/linux/game/bots_management.inl)'s + `bots_lobby_settings_apply` is called by the Bots menu's OK event after + saving choices. It checks connections, including pending joins, and + unowned high-ID players before enabling bots in an existing network lobby. + Conflicts produce an actionable error without stealing a player's ID. + It runs the existing lobby reconciliation immediately; clients and hosts + already loading or playing only save their choices for a future host. + `bots_manage` uses that server's existing join/quit dispatch for live + changes. Admission assigns the authoritative slot before encoding; + failed encoding rolls back the unannounced record. A departing bot's + machine identity stays unavailable until after the scheduled quit tick. +3. [bots.c](../../port/linux/game/bots.c): `bots_update_actions` runs only + on the host and selects exactly one controller. Stock decisions stay in this + file; [enhanced_bots_controller.c](../../port/linux/game/enhanced_bots_controller.c) + owns enhanced decisions, paths, recovery and per-bot state. Both use upstream + `bots_combat.c` for the six skill levels: Recruit, Easy, Normal, Heroic, + Veteran and Legendary. Enhanced policy preserves Infection zombies' melee + behavior and arbitrates objectives, items and committed seat approaches. +4. [enhanced_bots.c](../../port/linux/game/enhanced_bots.c): + Its enhanced aiming, healing, powerup reach and retreat thresholds use + the same six-level enum as upstream combat. Easy, Normal, Heroic and + Legendary retain their original enhanced values. Recruit shares Easy's + enhanced table row while upstream combat supplies its weaker reactions + and aiming; Veteran interpolates Heroic and Legendary. This prevents an + inserted skill from silently selecting the next difficulty's tactics. + When enhanced bots are enabled, their head/SWAT/feet selection owns the + aim-point override; the base automatic head selection must not bypass + its probabilities. Other upstream combat rules still run, including + reaction, shot pacing, grenade decisions and skill-dependent movement. + `enhanced_bots_update` caches objective state once per tick; + `enhanced_bots_goal` selects flag, carrier, hill or vantage destinations. + A flag carrier keeps advancing while fighting. A bot on the hill holds + its position; an off-hill bot advances toward it. With OpenCE's Multi-Hill + enabled, these existing bot queries target the first active hill, whose + state `king_hills_to_globals` exposes through the original accessors. +5. [bots_roles.c](../../port/linux/game/bots_roles.c), + [bots_routes.c](../../port/linux/game/bots_routes.c) and + [bots_vantage.c](../../port/linux/game/bots_vantage.c): + `bots_tactics_update` advances bounded graph preparation; + `bots_routes_search_goal` supplies lane waypoints to the enhanced path + search. A vantage point is a position overlooking useful map locations; + `bots_tactics_goal` chooses one suited to a bot's weapon and role. +6. [bots_vehicles.c](../../port/linux/game/bots_vehicles.c): + `bots_vehicle_goal` reserves reachable seats and + `bots_vehicle_action` supplies ordinary action/steering inputs. The + engine checks reach, occupancy, hostility and attachment itself. +7. [player_queues_new.c](../../source/game/player_queues_new.c): + `update_server_note_bot_action` puts the host's chosen input in the + existing update for the tick it executed. Clients replay the same + player actions through the existing simulation. + +The enhanced controller derives from the existing OpenCE/GulchCE core, with +independent state and lifecycle. It does not include or call the stock controller's +decision functions. See the [standalone controller walkthrough](enhanced_bots.md) +for navigation, boarding, aircraft, validation and limits. Route/vantage preparation retains +bounded working memory (32,768 walkable nodes and a 262,144-entry surface +lookup at most) and releases it when finished. The optional worker only +traverses private graph snapshots; bot decisions stay on the host's game +thread. No network packet, deterministic simulation rule or protocol version +is added. This bot extension does not add to the current upstream Xbox/CE protocol. See +[NETCODE.md](../../port/linux/NETCODE.md) for authority and transport rules. + +Map initialization resets objective, precision-cache and vehicle state. +Map disposal frees graph/grid allocations, including partial preparation. +Respawn and live removal release seat reservations and vantage claims. Session disposal +clears bot ownership and the network reservation. Map-loading and MCC +cleanup paths remain unchanged. + +`tools/harness/tests/test_lobby_countdown.py` exercises the real countdown +and bot ownership functions with 1, 31 and 63 bots, split-screen humans, +existing countdowns, team/minimum/pause checks and session ownership reset. +It also checks that removing the bot start hook reproduces the failure. +These asset-free checks do not establish map-loading or gameplay compatibility. + +[bots_menu.inl](../../port/linux/game/bots_menu.inl)'s `bots_menu_event` +connects generated CE widgets to those host operations and displays their +result. Settings retain the existing save, cancel and defaults behavior. +The console offers `add_bot`, `add_bot_red`, `add_bot_blue`, `drop_bot`, +`drop_bot_red` and `drop_bot_blue` through the same permission checks. +The console hook follows the dedicated server's role check. Neither path +executes arbitrary console strings from a widget or another machine. + +## Read the Android flow + +[TouchControls.java](../../port/android/app/src/main/java/com/halo/decomp/TouchControls.java) +retains its existing sensor lifecycle and +[GyroscopeAim.java](../../port/android/app/src/main/java/com/halo/decomp/GyroscopeAim.java) +integration. Explicit gyro modes bypass swipe sensitivity, reset accumulated +motion on mode changes and leave legacy mode behavior intact. +[host_touch.c](../../port/android/host/host_touch.c) transfers scalar mode +and motion values under its existing mutex. +[touch_gyro.c](../../port/linux/src/touch_gyro.c) applies per-axis settings; +`halo_linux_gyro_filter` discards unzoomed motion in Zoom Only mode. + +[AndroidCheatMenu.java](../../port/android/app/src/main/java/com/halo/decomp/AndroidCheatMenu.java) +uses the touch overlay's existing dialog/input-reset path. It sends typed +IDs through [host_android_cheats.c](../../port/android/host/host_android_cheats.c), +an eight-entry mutex-protected queue. No console text or guest pointers cross +this boundary. [android_cheats.c](../../port/linux/game/android_cheats.c) +rechecks offline/host permission on the game thread and consumes at most four +requests per poll. It follows the desktop console's +`hs_playing_in_anothers_game` rule: both distributed clients and clients +joining a lobby without a local server are denied. Changing from host to +client clears queued requests and releases menu-owned switches. Existing +host cheat semantics and object replication are reused; this menu adds no +network messages or client-side cheat settings. + +Both the desktop console and Android menu reach `cheat_all_weapons` in +[cheats.c](../../source/game/cheats.c). Its map-supplied weapon list, or its fallback +enumeration of loaded weapon tags, can include CTF flags and Oddball balls. These +objective items need ownership assigned by the game mode. The generic cheat spawn +has no such owner, so `distributed_client_change_valid` in +[network_objects.c](../../port/linux/game/network_objects.c) rejects them. The host +could still pick them up, leaving clients unable to reproduce its inventory. + +`cheat_objects` now skips weapons with the objective flag (the same bit used by +`weapon_is_flag`) when the game is a network host. This applies to both weapon-list +paths and both cheat interfaces. For example, spawning all weapons in Blood Gulch +creates ordinary weapons without adding unowned flags or balls. Offline spawning, +powerups, vehicles and the game modes' own objective creation retain their paths. +This is a shared cheat-spawn correction, not an MCC adapter or a change to client +validation. It adds no state, messages or peer agreement requirement; the +current upstream and separate MCC protocols are described in NETCODE.md. + +Host access does not establish that every cheat synchronizes correctly; physical +Android touch and Android-to-desktop network testing remain separate checks. + +Cinematics suspend requests without losing owned toggle +values. Disabling the menu or leaving the map restores values it changed, +unless a later console/script edit changed them again. One-shot spawned +items remain ordinary game objects; they are not undone by closing the UI. + +## Why the shared hooks are needed + +- Optional background traversal needs the path module's private graph + routines without its live profiling/debug writes. `bots_path_find_snapshot` + is an additive entry point in `source/ai/path.c`; the original + `path_state_find` is unchanged. Only `bots_worker.inl` calls it, with private + walkability and a snapshot of broken surfaces. This one hook cannot live + solely in the feature module because traversal is private to `path.c`. + Xbox, CE and MCC keep their existing graph loading and ownership paths. +- CTF flag/carrier and King hill geometry are private to their engine + modules. The `game_engine_ctf_flag_state`, `game_engine_king_hill` and + `game_engine_king_point_on_hill` accessors expose read-only state to + feature code; they do not change scoring or game rules. +- The lobby owns player admission and machine IDs, and the tick queue owns + authoritative input publication. Feature code cannot safely replace + either ownership boundary. Their small hooks call the feature modules. +- Live bot management needs the server's private record and message types; + its feature-owned include runs there without exposing those internals as + a new public engine API. The script-console hook only recognizes the six + typed bot commands; menus call the same feature function directly. +- `player_control` knows the actual zoom state when it consumes input; + the gyro hook needs that state to discard unzoomed motion. +- `cheats_dispose_from_old_map` is the map boundary at which menu-owned + switches and pending Android requests must be cleared. + +The stress tests also exposed a glow marker assertion. In +[glow.c](../../source/objects/widgets/glow.c), `glow_particle_update` and +`glow_time_wrap_down` accept `t == total_time`, but the original first lookup +in `get_particle_world_position` excluded that endpoint. Its narrow fix +includes the last endpoint while retaining half-open interior intervals and +out-of-range assertions. This corrects an existing engine contract for all +map families; it adds no MCC conversion semantics or gameplay rules. The +failing run did not capture the particle value, so the endpoint defect was +established independently by an extracted-source regression and negative +control rather than inferred solely from that assertion. + +All additions in `source/` carry `port:` markers. General-feature logic +stays in feature modules. No MCC compatibility logic was moved into the +Xbox or Custom Edition implementations. + +## Credits and source provenance + +The reference fork is +[thelinkin3000/halo-ce-universal at d92cc933](https://github.com/thelinkin3000/halo-ce-universal/tree/d92cc93385edf03d0a4a21cfe4c58dd578a3e786). +Its current project licence is AGPL-3.0-or-later; inherited code retains its +original notices and licences. Selected adaptations are distinguished from +design references below; this is not a wholesale cherry-pick. + +| Feature | Authors and reference | +| --- | --- | +| Existing local bots | **BirchWoodGod**, OpenCE commit `4a275b60`; retained as the base implementation. | +| Routes, roles, vantage points and vehicle reference | **BirchWoodGod**'s [halo-ce-vita](https://github.com/BirchWoodGod/halo-ce-vita), adapted by **thelinkin3000** in [88df94fd](https://github.com/thelinkin3000/halo-ce-universal/commit/88df94fd9fb7dc76b3762ef28bfd5d624fe4bba5). The retained tactical code and derived portions keep GPL-3.0-only; its full text ships in [LICENSES/GPL-3.0-only.txt](../../LICENSES/GPL-3.0-only.txt). Vehicle controls are a focused adaptation using this engine's public seat/action interfaces. | +| CTF and hill decisions | **thelinkin3000**, [ef77e2b4](https://github.com/thelinkin3000/halo-ce-universal/commit/ef77e2b4d73fbd81622279ae7cd1f5e5d40771c2) and [91871681](https://github.com/thelinkin3000/halo-ce-universal/commit/918716812b155eb889f73c125b11bd53bb475564). Those commits credit **id Software** and **ioquake3 contributors**: Quake III CTF/team rules and key-area defense inspired the decisions. Quake III did not supply a Halo hill implementation; no additional Quake source was imported here. | +| Network bots | **thelinkin3000**, [ed6cdaed](https://github.com/thelinkin3000/halo-ce-universal/commit/ed6cdaeda8871b7bee781c76bff3a4da2836c1bf), for publishing bot actions through the existing tick queue. GulchCE adds explicit host ownership and opt-in machine reservation. | +| 63-bot capacity and live controls | **thelinkin3000**'s `bots.h`, `overlay_menu.c` and `network_server_manager.c` at the pinned reference above, built on **BirchWoodGod**'s OpenCE/Vita bots. GulchCE adapts capacity and join/quit behavior into feature-owned controls with generated CE menus, explicit ownership and delayed identity reuse. | +| Gyro settings | **thelinkin3000**, [29638d60](https://github.com/thelinkin3000/halo-ce-universal/commit/29638d603d90283e16f95b2ac78d1ab99639912a), as the settings/zoom-mode reference. Built on **MrBruh**'s existing OpenCE Android controls (`fc610044`), preserving their legacy behavior. | +| Android cheat menu | **thelinkin3000**, [406f793f](https://github.com/thelinkin3000/halo-ce-universal/commit/406f793f4c08751f854a3615ed244ea3b1f90b88), whose overlay credits **hardran3**'s **OpenCE-Ultrahand** and **HaloDrones** packages. GulchCE uses a new small typed Android dialog/queue and existing cheat APIs; the fork's general console and renderer overlay are not imported. | +| Navigation, richer vehicles, aiming, powerups and Infection | Focused adaptations from **thelinkin3000**'s `bots.c` at `18a94774`, retaining its credit to **BirchWoodGod**'s Vita navigation, vehicles and powerups (GPL-3.0-only). SWAT/Infection and aiming rules are the fork's additions on that base. The snapshot worker is a separate implementation of the optional worker capability. | +| Touch editor and edge handling | **thelinkin3000**, [d119125f](https://github.com/thelinkin3000/halo-ce-universal/commit/d119125f) (edge controls, button aim, version-4 layout and toolbar), [62824171](https://github.com/thelinkin3000/halo-ce-universal/commit/62824171) (scrolling), and the earlier three/four-finger gesture, built on **MrBruh**'s OpenCE Android controls. The gesture opens GulchCE's existing cheat dialog. | + +Code credits belong here and in player-facing commit notes, not in the +art-only `AUTHORS.md`. Release packaging includes the retained GPL text and +this provenance; web distributions include both in `licenses.txt`. + +## Reference audit + +This source audit compares the original `d92cc933` reference and the fork's +[current main, 18a94774](https://github.com/thelinkin3000/halo-ce-universal/tree/18a94774a73ca275e9c0ab4f281e492ad8bb656e) +(28 October 2026), with GulchCE's combined implementation. The 90 commits +between those references leave the bot core and cheat-entry list unchanged, +but add touch-layout/editor changes and replay features. It does not claim full +behavioral parity with the fork. The bot/touch follow-up adapts the remaining +capabilities below while retaining GulchCE's defaults and engine interfaces. + +| Reference capability | GulchCE disposition | +| --- | --- | +| 63 bots, names and host-only network actions | Capacity restored; ordinary protocol-39 player records/actions retained. Lobby limits still apply. | +| Live add/drop by team; difficulty, routes and vehicles in a menu | Implemented through CE settings and Manage Current Bots. The three/four-finger gesture opens the Android cheat dialog when enabled offline or as host; the general renderer overlay remains separate. | +| Nine cheat switches and weapon/powerup/vehicle spawns | All exposed by the Android dialog, plus the earlier camouflage action. Available offline or to the session host; joined clients cannot use them. | +| Explicit gyro modes, per-axis sensitivity and inversion | Adapted; the default Touch Settings mode additionally preserves the user's earlier saved gyro settings. | +| Roles, lanes, vantage choices, CTF/King goals and ground vehicles | Focused adaptation already present, not an import of the fork's complete bot core. Vehicles stay off by default, unlike the fork's enabled default. | +| Teleporter routing/shortcuts, ladder routing and learned navigation obstacles | `bots_navigation.inl` adds bounded link discovery, measured shortcuts, disconnected-floor links, reservations, cooldowns and ordinary climbing controls around the existing path core. | +| Detailed vehicle weighting, passenger pickup/waits, flipping, vehicle-width obstacle learning and turret arc decisions | `bots_vehicles.c` adds these choices, charged turret fire, injury escape and combat driving. Entry/exit/flipping use ordinary player actions; the engine still decides whether the action is legal. | +| Skill-dependent head/feet aim, SWAT aim, objective-target combat priority, Infection-specific goals | `enhanced_bots.c` and `bots_infection.inl` add stable aim choices, carrier/hill target weighting, zombie pursuit/melee and human regrouping/retreat goals. Infection does not select sniper vantage points. | +| Detailed powerup claims, skill thresholds, avoidance and shared scan cache | `bots_powerups.inl` shares a bounded once-per-second scan, resolves claims by distance and bot order, and uses the existing unreachable-item memory and pickup lifecycle. | +| Optional helper-thread pathfinding | `bots_worker.inl` provides three snapshot jobs, stale-answer rejection and joined cleanup. `bots.thread` is off by default and exposed in the bot menu. No performance equivalence or measured speedup is claimed. | +| New touch edge-zone handling and optional held-button aim suppression | Adapted. Existing held-button aiming remains the default. Empty edge space retains Android gestures. | +| Movable Options button and centered layout-editor Export/Import/Save | Adapted with layout version 4; versions 1–3 still load, and new coordinates are validated and rescaled. | +| Scrollable Android General settings | Adapted with the expanded settings inside a scroll view. | +| General overlay console, custom TOML commands, HUD/debug and game-speed controls | Outside the requested bot/Android-cheat UI scope; not imported. | +| Replay recording, Theater and playback controls added after d92cc933 | A separate feature, not part of this bot/Android-cheat completion. Not imported. | + +The retained legacy gyro mode and disabled vehicle/worker defaults are +deliberate. Source comparison cannot establish touch feel or device-specific +sensor behavior; runtime evidence is recorded separately below. + +## Following an enhanced route + +With Enhanced Bots enabled, `bots_choose_goal` selects the host's objective +or an item, then `bots_search` uses the existing path graph. Read +[`bots_navigation.inl`](../../port/linux/game/bots_navigation.inl)'s +`bots_navigation_answer`, `bots_navigation_query` and `bots_navigation_follow` +next. For example, a Blood Gulch bot measures a teleporter's entrance and +exit against its ordinary walk, accepts only a route at most 80% as long +and at least 15 units shorter, walks onto the entrance, then detects the +ordinary engine teleport and searches from the exit. Ladder links connect +otherwise disconnected floors and finish with facing, forward and jump +controls. There are at most 64 links and two reservations per link. +Once climbing starts, the bot keeps that destination through the landing, +even during combat. Its climb timeout replaces ordinary horizontal stuck +recovery until it lands or abandons the link. + +[`bots_worker.inl`](../../port/linux/game/bots_worker.inl) optionally runs +only graph traversal on one worker. Submission snapshots walkability and +breakage; event signals transfer job ownership. Completion rejects changed +units, goals, link phases, teleports or answers older than one second. +The copied graphs provide a closed sentinel for open edges. Malformed +collision rings keep searches synchronous so shared engine diagnostics +cannot race. Obstacle queries and path smoothing remain on the game thread. Disposal +joins the worker before releasing feature graphs; scenario geometry remains +loaded until the later scenario unload. Allocation/start failures fall back +to synchronous searches. Job arrays and graph buffers use the engine's paired +tracked allocator; growth allocates before releasing an old buffer so failure +preserves ownership. Fixed-tick benchmarks also remain synchronous. + +[`bots_vehicles.c`](../../port/linux/game/bots_vehicles.c)'s +`bots_vehicle_goal` weighs seats and `bots_vehicle_action` drives, waits, +fires or requests exit. Obstacle learning closes a separate vehicle graph; +it never closes biped routes merely because a vehicle is too wide. +[`bots_infection.inl`](../../port/linux/game/bots_infection.inl) shares a +once-per-second role snapshot; [`bots_powerups.inl`](../../port/linux/game/bots_powerups.inl) +shares item discovery but keeps claims and timeouts per bot. Map disposal, +death and respawn clear their respective ownership. Only the host chooses +actions; clients consume the existing records. Protocol versions and +Xbox/CE/MCC map namespaces are unchanged. + +## Checks and limits + +The navigation/combat/touch follow-up's final self-review covered the combined +modules, generated settings, worker ownership, disabled behavior, map and +respawn cleanup, source provenance and regression fixtures. It corrected +closed-edge snapshot sentinels, allocation cleanup, a clock read before game +initialization, duplicate powerup pursuit and climbing interrupted by horizontal +stuck recovery. A live map transition exposed a worker allocation mismatch; +the corrected allocator pair now survives repeated map disposal. Real +Boarding Action movement also showed that tall ladders +need more than the reference's fixed eight seconds: the allowance now scales +with height, bounded to 8–60 seconds, followed by at most two seconds to land. + +Follow-up validation (final game code `4ec67c3d`): + +- [Build CI](https://github.com/chestahh/GulchCE/actions/runs/40796118360) + passed Linux, Windows, Android, web and changelog jobs; + [MCC validation](https://github.com/chestahh/GulchCE/actions/runs/40796118536) + also passed. These CI runs validate the final code before testing promotion. +- Windows, Android guest/host and web release builds passed. The original + `--portable --release` configure options were restored. The unchanged Java + changes passed SDK 35 compilation and layout/gyro checks; all 36 web page + tests passed. Bot settings were rendered in a hidden window and inspected. +- The [final web CI job](https://github.com/chestahh/GulchCE/actions/runs/40796118360/job/123192982935) + passed browser smoke/room checks and native WebRTC exchanges with Chromium + and Firefox (320 of 320 messages returned in each browser). +- The focused bot/worker/navigation/cheat/gyro/glow suite passed 83 checks. The six + real-game stock/enhanced/disabled regressions passed on `3899ad7e`; + enhanced Slayer/CTF/King passed again on `94c60acc` after the climb-control + correction. These are earlier checks of those unchanged synchronous paths. + Stock Blood Gulch bots and the default-disabled network-bot path both + passed again on the final build (two real-game checks). +- A 15-bot Infection match on `3899ad7e` with the worker enabled had active + movement/combat, completed teleports and a clean exit. Boarding Action matches discovered + ladder links and approached/climbed them, but random goals alone did not + establish completed landings during those bounded runs. +- A disposable engine fixture of the `090dbd05` bot code placed one bot at + the foot of a discovered five-unit Boarding Action ladder with matching + initial facing and velocity. + Production traversal code then climbed, landed and resumed ordinary goals, + without an assertion. Only placement/initial route choice was instrumented; + this verifies traversal, not natural route selection or every ladder. +- On `090dbd05`, a dedicated host with six bots and a joined client played + Xbox Blood Gulch, CE Death Island and Xbox Blood Gulch again. The worker started on all three + maps, cleanup raised no assertions, and the server quit cleanly. The test + stopped its own client after server shutdown. This establishes those live + transitions; a live transition involving MCC remains unverified. +- The final Xbox Blood Gulch CTF run with vehicles and the worker admitted + 63 bots plus two humans with unmodified OpenCE build 317. Both peers exited + cleanly and logged all 65 names. Intact players 0..31 compared for 67 paired + seconds without sustained divergence under unchanged tolerances. The + existing 4096-byte log truncation prevents comparing every player's state. +- CE Death Island CTF with the same 63-bot/worker setup also admitted all 65 + participants with OpenCE 317 and exited cleanly. Its intact records compared + for 67 paired seconds without sustained divergence, with the same log limit. +- MCC DigsiteMP/1 with 63 bots and the worker admitted all 65 participants + using normal startup timeouts. After the glow endpoint fix, both peers + exited cleanly without assertions; intact records compared for 73 paired + seconds without sustained divergence. This uses two GulchCE peers and the + existing MCC protocol, not an upstream OpenCE client. + +The 63-bot/menu/cheat completion was reviewed as a combined implementation, +including generated screens, shared hooks, failure rollback, ownership and +cleanup. Runtime rendering exposed and fixed a description-ownership bug: +management feedback must have an owned text buffer with no string list, +otherwise rendering replaces it every frame. The host's assigned player +slot is encoded before publishing a join, and existing lobby focus is kept. + +Earlier 63-bot/menu/cheat completion validation on Windows: + +- Windows, Android guest/host and web release builds passed with the original + PGO options restored. Android Java compiled against SDK 35; Java layout and + gyro checks and all 36 web page tests passed. +- The focused suite passed 123 checks with five platform skips; 25 additional + server-teardown checks (including negative controls) passed after updating + their extracted-source fixture for bot cooldown cleanup. All six + real-game bot regressions passed, including stock Slayer, enhanced + Slayer/CTF/King, movement/combat and network bots disabled. +- Unmodified OpenCE build 317 (protocol 39, release archive SHA-256 + `9950628b540cd5245440ae5db7ddad97cc76c9aed1ec20ca1419156acc4fb931`) + admitted 63 bots plus two humans on Xbox Blood Gulch and CE Death Island. + Both peers logged all 65 names and exited cleanly. The existing 4096-byte + player-state line truncates large matches: intact players 0..31 compared + for 67 and 66 paired seconds, respectively, with no sustained divergence + under unchanged comparator tolerances. This does not compare all 65 positions. +- Three live additions and three removals agreed with OpenCE for 67 paired + seconds. Both peers retained the same dead, unreused quit-player datum; + that ninth logged record is not a ninth active participant. Bot identity + reuse after the quit deadline and failed encoding are also harness-tested. +- Two GulchCE instances on MCC DigsiteMP/1 admitted all 65 participants and + exited cleanly without a timeout override. The same intact-record comparison + covered 76 paired seconds with no sustained divergence; the large-log + limitation applies here too. +- OpenCE also joined an already-running Xbox match with 63 bots: both peers + logged all 65 names and exited cleanly. Their once-per-second samples did + not align, so this establishes admission/lifecycle, not a position comparison. +- Hidden rendered checks covered Bot settings, Manage Bots, Server Setup + and Network Setup. Scripted controller presses verified that the real + management screen displays host-only rejection feedback. + +The Windows web-build test module has six POSIX path/header failures despite +the web build succeeding; Linux CI supplies the native fixture environment. +Android physical-device interaction, an Internet game through a broker, and +live cross-family map changes were not established by these earlier checks. +The follow-up above adds Xbox/CE transition coverage. Saves +from completed isolated runs are archived losslessly with original paths +and verified hashes; copied maps and disposable binaries are removed. + +The focused [harness tests](../../tools/harness/tests/) exercise real source +for lobby defaults/opt-in/ownership, partial and repeated cleanup, gyro +mode/sensitivity behavior, and the Android cheat queue's permissions, +capacity and lifecycle. [test_touch_layout.py](../../tools/test_touch_layout.py) +covers Java layout, gyro integration and sensor-state transitions. +[test_bots.py](../../tools/test_bots.py) exercises real local games. + +Earlier implementation validation on Windows (six bots): + +- All six real-game bot regressions passed: stock Blood Gulch and Chill + Out Slayer, enhanced Blood Gulch Slayer/CTF/King, and bots absent from a + network game when the option is off. These checks establish movement, + combat and clean exits, not flag captures or complete objective strategy. +- Unmodified OpenCE build 309 (`22947203`) joined a GulchCE host with six + bots. Xbox Blood Gulch had 68 paired seconds and CE Death Island CTF had + 68, with eight players and no sustained divergences under unchanged + comparator tolerances. With vehicles enabled, bots entered and drove + vehicles and the same OpenCE client agreed for 67 paired seconds. + A CE late-join run admitted both players and all bots, but its samples + did not align: that run establishes joining/lifecycle behavior only. +- Windows, Android host/guest and web compile/link checks passed. Android + and web used temporary Windows command adapters for Unix shell steps + in the existing build graph. Android Java sources compiled against SDK + 35; the Java layout/gyro regressions and 36 web page tests passed. +- The focused regression set passed 89 checks with five platform skips. + The larger harness/net-comparison run had 1,292 passing checks and six + skips after correcting a Windows test-compiler macro. All 312 remaining + failures reproduced on an unchanged export of the branch's `origin/main` + base (`e94810f1`); they are not a green full-suite result. +- MCC DigsiteMP/1 originally needed the debug timeout override to reach + gameplay. The subsequent [MCC startup fix](maps_and_resources.md) prepares + the host identity before admission and avoids hashing its unchanged + package twice. With normal timeouts and no override, two GulchCE instances + then agreed for 76 paired seconds with six bots and two human players, + 90 logged samples each and clean exits. A repeated run with the client's + package in a differently named folder also passed 76 paired seconds. + Local play produced 61 logged samples. Comparator tolerances were unchanged; + this is not evidence for every MCC package or arbitrary storage stalls. + +Compilation and automated checks do not establish Android touch/gyro feel, +all vehicle/map combinations or full campaign compatibility. The +native/browser WebRTC harness could not run on this Windows host (POSIX +build/path assumptions); Linux CI runs it with Chromium and Firefox. An +Internet game through a broker, Android device/visual checks and live map +transitions involving MCC remain outstanding. Record subsequent checks with +the implementation commit; do not treat suggested checks as results. diff --git a/docs/reading/browser_imports.md b/docs/reading/browser_imports.md index 1ff73cff0e..aa00b81f4b 100644 --- a/docs/reading/browser_imports.md +++ b/docs/reading/browser_imports.md @@ -24,13 +24,13 @@ the default-on `game.mcc_campaigns` setting. | Read | Follow | | --- | --- | | [Launcher](../../port/web/site/app.js) | `mapImport`, `beginStorageTask`, `play`: UI ownership, existing import guards and startup recovery. | -| [CE importer](https://github.com/chestahh/GulchCE/blob/1131d624b5c4e1f6e4d12174c4929452acf65285/port/web/site/ce-import-worker.js) | `plan`: flat CE names, version 609, resource headers and OpenSauce rejection. | -| [MCC importer](https://github.com/chestahh/GulchCE/blob/1131d624b5c4e1f6e4d12174c4929452acf65285/port/web/site/mcc-import-worker.js) | `plan`, `parseJson`, `png`: package layout, campaign/MP metadata, raw JSON identity and optional previews. | -| [Import primitives](https://github.com/chestahh/GulchCE/blob/1131d624b5c4e1f6e4d12174c4929452acf65285/port/web/site/map-import-files.js) | `chosen`, `path`, `cacheHeader`, `resourceHeader`: bounded reads and portable names, without Xbox format policy. | -| [Browser storage](https://github.com/chestahh/GulchCE/blob/1131d624b5c4e1f6e4d12174c4929452acf65285/port/web/site/map-import-storage.js) | `importPlan`, `begin`, `finish`, `recover`, `startGame`: owned journals, publication and cross-tab locks. | -| [Storage worker](https://github.com/chestahh/GulchCE/blob/1131d624b5c4e1f6e4d12174c4929452acf65285/port/web/site/map-storage-worker.js) | Dispatch page/game requests to the Worker where synchronous OPFS handles are available. | -| [C bridge](https://github.com/chestahh/GulchCE/blob/1131d624b5c4e1f6e4d12174c4929452acf65285/port/web/src/web_mcc_storage.c) and [JS bridge](https://github.com/chestahh/GulchCE/blob/1131d624b5c4e1f6e4d12174c4929452acf65285/port/web/src/web_mcc_library.js) | `web_mcc_share_io`, `web_mcc_package_visible`, asynchronous mailbox results and bounded waits. | -| [MCC staging](https://github.com/chestahh/GulchCE/blob/1131d624b5c4e1f6e4d12174c4929452acf65285/port/linux/game/mcc_share_stage.c) | Browser direct staging alongside unchanged native directory publication. | +| [CE importer](../../port/web/site/ce-import-worker.js) | `plan`: flat CE names, version 609, resource headers and OpenSauce rejection. | +| [MCC importer](../../port/web/site/mcc-import-worker.js) | `plan`, `parseJson`, `png`: package layout, campaign/MP metadata, raw JSON identity and optional previews. | +| [Import primitives](../../port/web/site/map-import-files.js) | `chosen`, `path`, `cacheHeader`, `resourceHeader`: bounded reads and portable names, without Xbox format policy. | +| [Browser storage](../../port/web/site/map-import-storage.js) | `importPlan`, `begin`, `finish`, `recover`, `startGame`: owned journals, publication and cross-tab locks. | +| [Storage worker](../../port/web/site/map-storage-worker.js) | Dispatch page/game requests to the Worker where synchronous OPFS handles are available. | +| [C bridge](../../port/web/src/web_mcc_storage.c) and [JS bridge](../../port/web/src/web_mcc_library.js) | `web_mcc_share_io`, `web_mcc_package_visible`, asynchronous mailbox results and bounded waits. | +| [MCC staging](../../port/linux/game/mcc_share_stage.c) | Browser direct staging alongside unchanged native directory publication. | The page's small additive guards also cover existing Xbox import, mod changes and Xbox-data deletion. Their worker implementations, formats, directories @@ -157,14 +157,18 @@ their validated case; manual import names are normalized once. The automated import, storage and launcher tests execute the production JS with synthetic headers and fault-injected OPFS/Web Locks interfaces. -[Real browser import checks](https://github.com/chestahh/GulchCE/blob/1db929c5e34101a45f644436e031016b5584c7bf/port/web/tests/map_import.mjs) additionally +[Real browser import checks](../../port/web/tests/map_import.mjs) additionally select real files and use the actual Chromium/Firefox workers and OPFS: map/JSON SHA preservation, campaign metadata, invalid-preview placeholders, no overwrite, reload persistence, cancellation and concurrent shared games. -[WasmFS staging checks](https://github.com/chestahh/GulchCE/blob/1131d624b5c4e1f6e4d12174c4929452acf65285/port/web/tests/mcc_storage.mjs) exercise the real +[WasmFS staging checks](../../port/web/tests/mcc_storage.mjs) exercise the real C stage, bridge, flush failures and crash/uncertain-outcome recovery in both browsers. Their synthetic bytes are not playable maps. -The repository includes the focused storage tests. An imported map or successful storage transaction +At this implementation phase those component and browser storage checks +passed; final combined MCC/CE/Xbox gameplay and networking validation remains +a separate Milestone 14 gate. Consult the +[validation ledger](../mcc_refactor_validation.md) for current runtime evidence, +tested revisions and limits. An imported map or successful storage transaction does not prove rendering, simulation, campaign progression or cross-platform network compatibility. diff --git a/docs/reading/console_checkpoints.md b/docs/reading/console_checkpoints.md index 2261d3d4ad..146a5c21a3 100644 --- a/docs/reading/console_checkpoints.md +++ b/docs/reading/console_checkpoints.md @@ -11,9 +11,9 @@ remain separate. The interpreter represents an expression as linked **syntax nodes**. A thread's **stack frames** record the calls it must finish, including handles -to those nodes. A handle contains both a slot and an allocation identifier. -Reusing the slot does not preserve the old expression: the identifier must -still match the allocation being referenced. +to those nodes. A handle contains both a slot and an identifier; see +[datum indices](glossary.md). Reusing the slot does not preserve the old +expression. Historically, checkpoints saved the threads in the CPU game-state image, but their temporary console syntax lived outside that image. After the @@ -32,7 +32,7 @@ an MCC-only adapter could not repair Xbox or CE console continuations. | --- | --- | --- | | 1 | [hs_compile.c](../../source/hs/hs_compile.c): `hs_compile_expression`, `hs_parse_string` | Where does a command's source text live, and how does a string node refer to it? | | 2 | [hs_runtime.c](../../source/hs/hs_runtime.c): `hs_runtime_evaluate`, `hs_thread_main`, `hs_runtime_update`; [hs.c](../../source/hs/hs.c): `hs_node_gc` | Which thread retains the expression, and when can its temporary nodes be collected? | -| 3 | [hs_console_state.h](https://github.com/chestahh/GulchCE/blob/1131d624b5c4e1f6e4d12174c4929452acf65285/port/linux/game/hs_console_state.h), then [hs_console_state.inl](https://github.com/chestahh/GulchCE/blob/1131d624b5c4e1f6e4d12174c4929452acf65285/port/linux/game/hs_console_state.inl): `hs_console_source_acquire`, `hs_console_sources_mark`, `hs_console_source_finish` | What prevents a new command from reusing live text? | +| 3 | [hs_console_state.h](../../port/linux/game/hs_console_state.h), then [hs_console_state.inl](../../port/linux/game/hs_console_state.inl): `hs_console_source_acquire`, `hs_console_sources_mark`, `hs_console_source_finish` | What prevents a new command from reusing live text? | | 4 | [game_state.c](../../source/saved%20games/game_state.c): `game_state_save`, `game_state_save_core`; `hs_console_state_capture` in the console module | What is captured before either kind of save is written? | | 5 | `game_state_image_accept`; `hs_console_state_validate`, `hs_console_saved_threads`, `hs_console_saved_graph`, `hs_console_state_restore` | What is checked before saved bytes become live, and how are the original syntax handles restored? | | 6 | `hs_runtime_initialize`, `hs_runtime_initialize_for_new_map`, `hs_runtime_dispose_from_old_map` | Who allocates the state and clears it when the map changes? | @@ -98,7 +98,7 @@ The source pool and snapshot reset during map initialization and old-map disposal. Native threads keep their inline stacks; MCC threads keep the MCC-owned enlarged storage selected by `mcc_hs_threads_activate` and bounded by `mcc_hs_stack_end` in -[mcc_script_threads.inl](https://github.com/chestahh/GulchCE/blob/1131d624b5c4e1f6e4d12174c4929452acf65285/port/linux/game/mcc_script_threads.inl). +[mcc_script_threads.inl](../../port/linux/game/mcc_script_threads.inl). The generic fix neither transfers that ownership nor combines the map loading paths. @@ -129,7 +129,7 @@ downloaded-map restrictions. `hs_console_syntax_node_valid` applies console permissions to saved console expressions. This does not grant authored Xbox or CE scripts access to console-only commands, or bypass MCC's separate function validation. -In [mcc_scripts.c](https://github.com/chestahh/GulchCE/blob/1131d624b5c4e1f6e4d12174c4929452acf65285/port/linux/game/mcc_scripts.c), +In [mcc_scripts.c](../../port/linux/game/mcc_scripts.c), `mcc_script_call_arguments_valid` checks that grammar for temporary console nodes. The map wrapper, `mcc_script_call_valid`, still requires the permanent-node bit before delegating to it. @@ -144,10 +144,10 @@ in [NETCODE.md](../../port/linux/NETCODE.md). ## Evidence and limits -[test_hs_console_state.py](https://github.com/chestahh/GulchCE/blob/1131d624b5c4e1f6e4d12174c4929452acf65285/tools/harness/tests/test_hs_console_state.py) +[test_hs_console_state.py](../../tools/harness/tests/test_hs_console_state.py) extracts the actual compiler ownership path, allocator, interpreter, collector, checkpoint support and validation functions. Its fixture in -[hs_console_state.c](https://github.com/chestahh/GulchCE/blob/1131d624b5c4e1f6e4d12174c4929452acf65285/tools/harness/tests/hs_console_state.c) supplies a +[hs_console_state.c](../../tools/harness/tests/hs_console_state.c) supplies a small fake world. Cases cover collection and reuse, concurrent text, global references, capacity limits, malformed saved references, inactive permanent nodes and deliberate faults that the tests must detect. @@ -156,5 +156,7 @@ These controls do not establish a complete game session or cross-platform compatibility. Required runtime checks include replay on Xbox, CE and affected MCC maps, ordinary checkpoint/revert, same-build cross-process core loading, old-layout refusal and map-family transitions. Platform -builds and native/browser networking need separate testing; this walkthrough +builds and native/browser networking need separate validation. Actual runs, +binary identities and remaining limits belong to the +[refactor validation record](../mcc_refactor_validation.md); this walkthrough does not claim those checks have all passed. diff --git a/docs/reading/controller_buttons.md b/docs/reading/controller_buttons.md index 1746e05c69..dbc7e91c97 100644 --- a/docs/reading/controller_buttons.md +++ b/docs/reading/controller_buttons.md @@ -1,55 +1,125 @@ # Controller detection and button styles -Gamepads > Button Appearance contains AUTO BUTTON DETECTION, enabled by default for new configurations. -Saved choices are preserved. Detection limits Button -Style to the controller assigned to the menu's player. Turning it off exposes all -eleven controller styles plus Keyboard; unknown or disconnected devices retain the saved manual choice. -Device detection always runs, including when the option is off. - -Xbox offers Classic, Gems, Dark Gems and Modern; PlayStation offers Classic, Gems, -Dark Gems and Modern; Switch offers Classic, Gems and Modern. Each family remembers -its preferred style. Labels use the detected family independently of artwork. -For example, P2's DualSense exposes PlayStation styles while P1's Xbox controller -continues using the Xbox preference. Steam Input may expose an Xbox identity. - -BUMPER STYLE appears for Xbox Classic, Gems and Dark Gems. Original Xbox, the -default, keeps black/white buttons; Modern Xbox uses the existing LB/RB artwork. -The preference is shared by local players, retained across controller changes and -automatic detection, and changes no bindings. Other styles keep their bumpers. -Appearance settings remain available with High-Res HUD off; the artwork changes -apply when High-Res HUD is enabled in Graphics. Keyboard keycaps work independently. - -KEYBOARD GLYPHS is off by default. Enable it alongside AUTO BUTTON DETECTION -to follow keyboard/mouse and controller activity in gameplay. The detected -Keyboard row is read-only; saved controller and manual preferences are retained. -With detection off, select Keyboard manually to keep keycaps. MENU GLYPHS, also -off by default, extends the same selection to existing PC-menu A/B/X/Y legends -and inline face-button tokens, independently of High-Res HUD. See [keyboard prompts](keyboard_prompts.md). - -## Reading route - -1. [controller_buttons.c](../../port/linux/src/controller_buttons.c) classifies SDL - devices and owns per-port snapshots and style preferences. Existing assignments - in [xinput_sdl.c](../../port/linux/src/xinput_sdl.c) supply device identity. -2. [controller_button_menu.inl](../../port/linux/game/controller_button_menu.inl) - filters pending settings and the optional bumper row without overwriting the - manual preference. Dynamic labels retain their help indices. Cancel, - Defaults, disconnects and live family changes retain normal menu behavior. -3. [controller_glyphs.c](../../port/linux/game/controller_glyphs.c) maps the viewport - to its local input port. It draws supplied artwork within the existing prompt - cells, preserving advances, centered anchoring and split-screen scale. -4. [hud_hires_tags.c](../../port/linux/game/hud_hires_tags.c) identifies native and - stock CE button entries before calling that renderer. Existing Xbox styles and - low-resolution fallbacks keep their paths. The new cache is keyed by artwork, - shared across viewports and disposed at normal map teardown. -5. [controller_button_assets.py](../../tools/controller_button_assets.py) generates - the retained source artwork with deterministic platform labels. See its - [provenance](../../port/assets/controller_buttons/README.md). Classic Xbox - letters use transparent cutouts in [button_assets.py](../../tools/button_assets.py). - -The settings table is in [the port README](../../port/linux/README.md). -[Button remapping](controller_remapping.md) is a separate Gamepad Setup submenu. -The production-C and artwork checks in [test_controller_buttons.py](../../tools/test_controller_buttons.py) -and [test_hud_button_style.py](../../tools/test_hud_button_style.py) cover family -selection, pending settings, unknown devices, glyph geometry, animated controls, -opacity, bumper choices and cache cleanup. Driver behavior and real hardware require playtesting. +Gamepads > Button Appearance contains AUTO BUTTON DETECTION, on by default for +new configurations. Existing saved choices are preserved. The manual Button Style +row offers eleven controller styles and KEYBOARD. Turning detection on shows +Keyboard for active keyboard/mouse input or restricts artwork choices to the +controller family. Controller style captions identify P1 through P4. Devices are identified even while the +option is off. Detection and style selection do not change input; +[controller remapping](controller_remapping.md) is a separate Gamepad Setup submenu. + +For example, a DualSense assigned to P2 exposes PS Classic, PS Gems, PS Dark Gems +and PS Modern. Choosing PS Modern saves the PlayStation preference. Turning +automatic detection off restores the independently saved manual choice. A +simultaneous Xbox player uses the Xbox preference in their own gameplay viewport. +Players with the same family share that family's style preference. + +BUMPER STYLE appears only for Xbox Classic, Xbox Gems and Xbox Dark Gems. Original +Xbox, the default, keeps the existing black/white artwork. Modern Xbox uses the +supplied LB/RB artwork already used by Xbox Modern. This choice is shared by local +players and stays saved when automatic detection is on, when another family is +connected, or when another style hides the row. For example, an Xbox player using +Gems and Modern Xbox bumpers gets gem face buttons with LB/RB prompts; a simultaneous +PlayStation player keeps PlayStation artwork. The option changes no bindings. + +Controller artwork choices can be saved while High-Res HUD is off, but affect +gameplay only when it is enabled in Graphics. The selectable KEYBOARD style +also requires High-Res HUD; see [keyboard/mouse prompts](keyboard_prompts.md). +Automatic detection includes keyboard/mouse activity without a second toggle. +The detected Keyboard row is read-only and never overwrites the saved manual +choice. With detection off, manual KEYBOARD stays selected. + +The [modern frontend](menu_redesign.md) also uses these saved styles. +Its Interface page starts with Menu Style, High-Res Text and High-Res HUD. +Stock Menu Glyphs enables optional artwork in classic PC and pause-menu legends. +Auto Detection and glyph appearance controls, including Stock Menu Glyphs, are +shown only while High-Res HUD is pending on. Detection follows the active menu input: a +read-only Keyboard row or the active physical controller's family preference, +falling back to Manual Style for an unknown controller; turning +detection off restores Manual Style. Hiding controls preserves their pending and +saved choices. These visibility rules do not change the legacy submenu above. +Its navigation prompts follow the most recently used physical controller port, +with keyboard/mouse and touch alternatives. Keyboard and controller artwork in menus and +gameplay requires High-Res HUD; menus use text or native prompts when it is off. + +## Reading route and boundaries + +1. [controller_buttons.c](../../port/linux/src/controller_buttons.c), + `controller_device_read`, `controller_device_update` and + `controller_button_style_for_port`: SDL identity snapshots and style policy. +2. [xinput_sdl.c](../../port/linux/src/xinput_sdl.c), `connected_gamepads` and + `XInputGetState`: minimal hooks publish identity using the existing port + assignment. A feature module alone cannot know when that assignment changes. +3. [port_config.c](../../port/linux/src/port_config.c) and + [port_settings.py](../../tools/port_settings.py): saved defaults, environment + overrides and generated menu rows. Existing saved Xbox style names are kept. +4. [controller_button_menu.inl](../../port/linux/game/controller_button_menu.inl), + `controller_button_rows_show`: pending selections, family filtering, focus and + the optional bumper row. The existing menu callback wires this in; Save, + Cancel and Defaults continue through the normal settings machinery. Hidden + family selections do not replace the manual choice. Labels keep their help + indices without a string list, so the hints work with dynamic player captions. +5. [controller_glyphs.c](../../port/linux/game/controller_glyphs.c), + `controller_glyph_style`, `controller_glyph_draw`, `controller_glyphs_dispose`: + viewport-to-controller resolution, optional artwork and resource lifetime. +6. [hud_hires_tags.c](../../port/linux/game/hud_hires_tags.c), `hud_hires_button_draw`, + and [mcc_hud_draw.c](../../port/linux/game/mcc_hud_draw.c), `mcc_hud_icon_draw`: + each established renderer identifies its own controller entries before calling + the feature. These hooks are necessary because only those renderers have the + map's icon identity, cursor and text context. Xbox/CE loading paths and MCC + ownership guards remain independent; weapon/pickup art is not replaced. + +## Identity and lifecycle + +SDL identifies Xbox 360/One-family devices, PS3/PS4/PS5 and Switch Pro/Joy-Con +variants. Xbox Series and third-party Xbox-compatible pads depend on the type +reported by SDL and their driver. USB/Bluetooth names, instance IDs and vendor / +product IDs are retained on native desktop and web builds when SDL exposes them. +The Android guest currently exposes the SDL type only: its displayed device name +is a family description and the other identity fields are zero. + +Detection describes the device visible to SDL. Steam Input or another controller +wrapper can present a PlayStation pad as an Xbox pad; the game cannot recover the +hidden physical identity. An unknown controller falls back to the manual +selection instead of guessing. Disconnecting the keyboard owner restores its +last keyboard/touch presentation. Input polling refreshes snapshots and clears +disconnected ports, including existing keyboard/gamepad split-screen assignments. + +Automatic detection and each family preference are global configuration settings. +The active menu uses its player port; gameplay uses the viewport's player-to-port +assignment. Changing families does not overwrite other saved preferences. Disabling +High-Res HUD preserves the established low-resolution paths. Appearance selections +remain available in their submenu for the next time High-Res HUD is enabled. + +New artwork is cached by asset, not by current player, so alternating viewports do +not evict each other's glyphs. Each allocation retains its originating renderer's +optional unbind callback. The existing high-res map teardown releases all feature +textures before map tags disappear, including MCC resources. Repeated cleanup is +safe; a failed allocation falls back to the established glyph for that map. +The existing Xbox styles keep their geometry. `controller_glyph_asset_index` only +substitutes the two modern shoulder assets for the three older Xbox styles when +`display.hud_bumper_style` is `modern`. Both map renderers already call this feature +after resolving the viewport's style, so this addition needs no shared-engine or +MCC-specific hook. Switching back uses the original renderer, and cached modern +artwork is released by the existing map teardown. Xbox Classic's letter transparency +is corrected as described in [HUD artwork corrections](hud_corrections.md). + +## Artwork, geometry and checks + +See [asset provenance and generation](../../port/assets/controller_buttons/README.md). +The new renderer fits visible artwork within the existing face/control cells, +preserves aspect ratio, centers on the text's capital midpoint, retains cursor +advances and applies the existing 0.75 split-screen scale. Switch uses printed +B/A/Y/X at physical south/east/west/north; this is a label choice, not remapping. + +[Controller tests](../../tools/test_controller_buttons.py) exercise production +identity and policy code with SDL fakes, pending menu behavior, all generated art, +and production draw geometry, allocation and cleanup. Existing Xbox/CE/MCC HUD +regressions remain relevant. These tests establish software behavior; they do not +prove that every physical controller/driver reports the expected SDL type. +Hardware checks should cover USB/Bluetooth, hotplug, mixed-family split screen, +Save/Cancel/Defaults and Xbox/CE/MCC map transitions. Those suggested checks are +not a claim that every device and transition has been tested. + +This changes local presentation only: no network packet, input mapping or shared +simulation contract changes, so the network version remains unchanged. diff --git a/docs/reading/controller_remapping.md b/docs/reading/controller_remapping.md index e71be9ddb1..7d75279bca 100644 --- a/docs/reading/controller_remapping.md +++ b/docs/reading/controller_remapping.md @@ -1,11 +1,18 @@ # Controller button remapping -Gamepad Setup > **Button Remapping** edits separate P1–P4 layouts. These belong +Gamepad Setup > **Button Remapping** edits separate P1–P4 layouts. These belong to input slots on this installation, not device serial numbers or player profiles. Empty settings keep the profile preset and stock shortcuts. - -Choose Movement, Combat, General, Communication or Debug. Select an action, release -the opening press, then press the desired button on that player's controller. +The separate **Dead Zones** screen sets left/right stick thresholds shared by +the input path. Its stock defaults preserve the original game thresholds. +`halo_stick_dead_range` in [xinput_sdl.c](../../port/linux/src/xinput_sdl.c) +supplies them to [input_xbox.c](../../source/input/input_xbox.c); button +remapping remains independent of these axis settings. +Optional [DualSense feedback](dualsense.md) follows these physical L2/R2 assignments; +actions on buttons without actuators do not produce adaptive-trigger effects. + +Choose Movement, Combat, General, Communication, Debug or Camera Perspective. +Select an action, release the opening press, then press the desired button on that player's controller. All four D-pad directions and Back/Select are available. Start/Options and Escape cancel capture. Button names follow the detected controller family independently of Button Style. Stick axes, sensitivity and menu navigation keep their settings. @@ -32,6 +39,13 @@ Voice uses the existing shared microphone and first player's voice routing; any slot can hold its assigned Push to Talk button. Enable push-to-talk in voice settings. Keyboard and touch retain their own bindings. +Camera Perspective contains Third Person On / Off and Swap Shoulder, both unbound +by default. These are gameplay actions and use the normal replacement confirmation +when assigned an occupied gameplay button. They use the same installation-wide +camera preferences as N and B, respect host policy, and are inactive while menus, +chat, binding capture or the debug camera own that controller's input. Simultaneous +keyboard and controller presses toggle once. Debug actions remain a separate group. + Debug includes Camera Speed Up/Down, Camera / Player Switch, Camera Raise/Lower and Cycle Camera. These reuse buttons independently of gameplay. Hold Cycle Camera for one second to advance through the director's views: first person, flying, @@ -55,7 +69,7 @@ adjusting speed. Camera movement uses the player's movement and look settings. Menus and chat continue to block custom camera input in either mode. Gameplay prompts use the physical binding, or **UNBOUND** for a cleared action. -Xbox and CE retain their existing glyph renderers, sizes and anchoring. +Xbox, CE and MCC retain their existing glyph renderers, sizes and anchoring. ## Reading route and integration @@ -91,27 +105,28 @@ Xbox and CE retain their existing glyph renderers, sizes and anchoring. [input_abstraction.c](../../source/input/input_abstraction.c) applies digital movement; [hud_messaging.c](../../source/interface/hud_messaging.c) maps prompt identity and renders UNBOUND. Those private engine states cannot be - accessed solely from a feature module. No map loading path is changed. + accessed solely from a feature module. No map loading or MCC adapter is changed. ## Persistence and lifecycle `input.controller_p1` through `input.controller_p4` default to empty strings. -New custom layouts use `v3:` followed by 26 comma-separated entries in this order: +New custom layouts use `v4:` followed by 28 comma-separated entries in this order: ``` jump, grenade type, use/reload, weapon, melee, flashlight, grenade, fire, crouch, zoom, scoreboard, screenshot, forward, backward, left, right, all chat, team chat, vehicle chat, push to talk, camera faster, camera slower, camera/player switch, -camera raise, camera lower, cycle camera +camera raise, camera lower, cycle camera, toggle perspective, swap shoulder ``` Entries are physical tokens: `south,east,west,north,rb,lb,lt,rt,ls,rs,dpad_up, dpad_down,dpad_left,dpad_right,back`, or `unbound`. South means A on Xbox, Cross on -PlayStation and B on Switch. Tokens must be unique within gameplay/communication -and separately within Debug; `unbound` may repeat. Unbound saves remain distinct +PlayStation and B on Switch. Tokens must be unique within gameplay, communication and +camera perspective, and separately within Debug; `unbound` may repeat. Unbound saves remain distinct from an empty setting (profile defaults). -Old ten-action and 25-action `v2:` strings remain readable. The appended Cycle +Old ten-action, 25-action `v2:` and 26-action `v3:` strings remain readable. +The two Camera Perspective actions start unbound in every older layout. Cycle Camera defaults to RB unless an old debug action already owns RB, in which case Cycle Camera starts unbound and can be assigned in the Debug group. Existing assignments are preserved. Ten-action strings' original actions take priority over @@ -138,5 +153,5 @@ including mouse priority and menu/chat blocking. combine the real widget-ownership check, remapper and director input for main-menu navigation, pause, camera cycling, alternate bindings, timing and lifecycle guards. Tests distinguish those contracts from physical driver behaviour. Runtime -screenshots and Xbox/CE gameplay checks complement the tests; +screenshots and Xbox/CE/MCC gameplay checks complement the tests; real-controller playtesting is still needed for device-specific behaviour. diff --git a/docs/reading/dualsense.md b/docs/reading/dualsense.md new file mode 100644 index 0000000000..f0f4577488 --- /dev/null +++ b/docs/reading/dualsense.md @@ -0,0 +1,86 @@ +# DualSense feedback + +This optional OpenCE feature drives a DualSense or DualSense Edge's adaptive +triggers (the resistance motors in L2/R2), lightbar and player-number lights. +GulchCE adds remapping-aware routing and explicit gameplay/lifecycle cleanup. +It does not change weapon simulation, controller input or network messages. +Xbox, Custom Edition and MCC retain their own map-loading paths. + +Set `input.adaptive_triggers = true` and optionally +`input.lightbar = "player_color"` in `config.toml`. Both default off. +`input.trigger_strength` accepts `"light"`, `"normal"` and `"strong"`. +These settings currently have no menu rows. See the +[settings table](../../port/linux/README.md) for environment-variable names. +The desktop SDL PS5 driver handles USB/Bluetooth; Linux can alternatively +write the controller's hidraw device while the kernel reads input. +Android and web compile no-op output interfaces. + +## Reading route + +1. [dualsense_game.c](../../port/linux/game/dualsense_game.c): + `dualsense_game_update`, `dualsense_player` and `mapped_effect` read local + players, existing profile/custom mappings and weapon state. Fire effects + follow the physical trigger mapped to fire; grenade/zoom effects follow + their trigger. Actions on face buttons have no trigger actuator. +2. [dualsense_rules.c](../../port/linux/src/dualsense_rules.c): + `dualsense_right_held`, `dualsense_event` and `dualsense_left_effect` + produce eleven-byte effects from weapon state. The historical right/left + names describe the default layout, not a restriction on routing. +3. [dualsense.c](../../port/linux/src/dualsense.c): `dualsense_wish_set` + copies the game thread's request under a lock. `dualsense_frame` consumes + it on the SDL event thread; `pad_frame` owns delivery and elapsed-time + scheduling. `pad_send` uses SDL or Linux hidraw. +4. [sdl_platform.c](../../port/linux/src/sdl_platform.c) calls the output + service and removal hook. [xinput_sdl.c](../../port/linux/src/xinput_sdl.c) + identifies which physical pad belongs to each controller port. + +For example, a pistol shot 10 ms after a Bluetooth report cannot be sent +until the 50 ms reporting window opens. The 35 ms kick remains pending +until delivery succeeds, then its duration begins. Pending events coalesce +to the latest shot and expire after 300 ms; context changes cancel them. +The held effect returns after the kick, subject to the same report window. +SDL may combine or queue driver writes; a successful API call establishes +acceptance, not measured mechanical response time. + +## Ownership and lifecycle + +Game-thread history is per controller port and separate from checkpoint +data. Player, unit, weapon, device instance, layout and strength changes +establish a new baseline; an old last-fired timestamp is never replayed. +Paused, menu-blocked, director-inhibited and dead-player contexts request +neutral triggers. Requests older than 300 ms also release them. + +Two small engine integrations are necessary because feature modules do not +receive these lifecycle events on their own: + +- [player_control.c](../../source/game/player_control.c) calls the update + after all local input, including players without units, and resets at map + initialization/unload. This preserves existing input processing and allows + prompt neutral requests while menus suppress gameplay. +- [game_state.c](../../source/saved%20games/game_state.c) registers + `dualsense_game_reset` in the existing before-load callbacks. This clears + history before checkpoint object identities can be reused, including a + load that subsequently fails. Both integrations carry `port:` comments. + +Disabling, unbinding, removing a pad and normal shutdown restore owned +outputs. Busy writes retain a reset request; final removal/shutdown retries +are bounded to 200 ms. SDL restores the original player index and that +index's default palette color; it cannot read another application's custom +RGB. Hidraw restores blue and clears player lights. An abrupt crash cannot +guarantee cleanup; reconnect the pad if effects remain. + +## Checks and limits + +[test_dualsense.py](../../tools/test_dualsense.py) exercises the production +scheduler with a simulated SDL endpoint and game-context routines with +engine fixtures: Bluetooth timing, busy writes, both trigger routes, +pause/death/menu suppression, context changes, bindings and light restoration. +The [rules harness](../../tools/harness/tests/test_dualsense_rules.py) checks packing, +weapon profiles, report framing and link coalescing. These are automated +checks, not evidence of physical trigger feel or every controller firmware. + +USB hardware validation can check SDL acceptance and neutral cleanup; +Bluetooth, Linux hidraw and DualSense Edge still require their own hardware +runs. Map smoke tests establish only the exercised loading/gameplay path, +not full campaign compatibility. See [provenance and notices](../../port/third_party/dualsense/README.md) +for the public MIT/zlib format references and upstream PR history. diff --git a/docs/reading/emitter_expansion.md b/docs/reading/emitter_expansion.md new file mode 100644 index 0000000000..33dc86cb4f --- /dev/null +++ b/docs/reading/emitter_expansion.md @@ -0,0 +1,285 @@ +# Energy, vehicle and world emitters + +This optional extension uses the dynamic-lighting baseline's world/model +falloff, specular colour and local occlusion fields. All new preferences +default off. Android excludes the feature modules and retains stock hooks. +No projectile, equipment, vehicle, damage or network simulation is changed. + +## Player controls + +Video Setup > Dynamic Lighting groups related sources: + +| Control | Sources | +| --- | --- | +| Projectile Lights | Existing projectiles, armed plasma grenades and flamethrower streams | +| Muzzle Flash Lights | Existing handheld, Warthog and Scorpion flashes | +| Weapon Glow | Energy sword, plasma charge, fuel rods, AR counter and Needler crystals | +| Plasma Prong Lighting | Independent short, soft outward spill from Plasma Rifle/Pistol prongs; off by default | +| Shield Emitters | Jackal shields and Covenant stationary shields | +| Vehicle Lights | Supported Covenant running/engine lights and Warthog/Scorpion headlights | +| World Emitters | Overshield/active-camouflage pickups and the green teleporter surface | +| Light Occlusion | Optional blocking for projectiles, weapons and world emitters; muzzle and vehicle sources always request blocking | + +Shield Glow and its host-policy controls remain separate. Consolidation does +not grant a client control over host-authoritative shield effects. + +Weapon Glow and Shield Emitters offer only **OFF** and **ON**. The first load +of an older configuration resets all optional dynamic-lighting switches to +OFF and Shield Glow intensity to Default. The configuration loader records +`display.dynamic_lighting_reset = true`; subsequent player choices survive +restarts. Other graphics settings, shield appearance and overshield effects +are unchanged. Explicit environment overrides still apply after migration. +The individual configuration keys remain available; a group displays ON if +any member is enabled. Choosing OFF disables every member, and choosing ON +from OFF enables them all. Defaults stages OFF until saved. +The `lighting.*` names are menu controls, not new persistent config keys. +See the [settings table](../../port/linux/README.md) for persistent keys. + +The bounded migration in +[lighting_settings_migration.inl](../../port/linux/src/lighting_settings_migration.inl) +uses the TOML parser's source positions to replace just lighting values. +`config_load` calls it before loading settings and applying environment overrides. +If migration cannot be prepared, old lights remain OFF in memory and the file +is left unmarked for a later retry. Invalid files and read-only command modes +retain the configuration loader's existing no-write behaviour. + +## Reading order + +1. [authored_emitter_lighting.c](../../port/linux/game/authored_emitter_lighting.c): + `authored_emitter_lighting_profile` matches exact object and light tag + identities, cached only for the current map. It returns the category and + radius multiplier; authored colour, timing and spotlight cones survive. +2. [plasma_lighting.c](../../port/linux/game/plasma_lighting.c): + `plasma_lighting_prepare` saves attachment state and refreshes the rendered + pose; `plasma_lighting_frame_end` restores radius, flags and attachment + position before simulation resumes. Attachments disconnected by the engine + remain disconnected: `light_port_refresh_attachment` refuses the refresh, + and preparation restores the dynamic flag and discards the render entry. + This preserves map membership for hidden or inactive objects. The private-light + hook in [object_lights.c](../../source/objects/object_lights.c) now supplies the + definition identity. The feature module cannot obtain that private field + through the existing public object interface; this is the only additional + game-source argument needed for exact selection. +3. [ambient_emitter_lighting.c](../../port/linux/game/ambient_emitter_lighting.c): + `ambient_emitter_lighting_begin` resolves exact profiles and combines live + flame projectiles by firing owner. `ambient_emitter_lighting_sample` reads + render poses, model markers and evaluated object functions without writing + game state. Unknown tags, missing markers and collected pickups produce no + sample. Model-less flame projectiles are a deliberate exception to the + object's invisible flag: their stock particles are visible independently. +4. [covenant_emitter_lighting.c](../../port/linux/game/covenant_emitter_lighting.c): + the existing eight-slot pool owns allocation, render-time easing, view + submission and cleanup for both old and new samples. Two components let + separated vehicle sources share that pool without adding another budget. + A flame stream uses one centroid per owner, with smooth render-time motion + where the model-less projectile has no interpolated node matrix. +5. [plasma_occlusion.c](../../port/linux/game/plasma_occlusion.c): vehicle + sources request vehicle collision tests, including the emitting chassis. + Existing local visibility-field limits and approximation errors still + apply. This is not stencil shadowing or a new shadow-map implementation. +6. [lighting_menu.c](../../port/linux/game/lighting_menu.c) and + [port_settings.py](../../tools/port_settings.py): group reads/writes and + generated menu rows. The minimal `setting_text`/`setting_write` hooks in + [menu_functions.c](../../port/linux/game/menu_functions.c) let both menu + frontends use their existing staging, Cancel and Save flow. + +For example, a visible Elite sword retains its original blade effect and +attachment animation. Weapon Glow selects only its named dynamic-light +attachment, enlarges its soft radius during rendering, and restores stock +attachment state at frame end. Turning the group off returns subsequent +draws to stock selection and shaders. Other lights on a custom sword tag do +not match the profile automatically. + +## Ownership, bounds and compatibility + +All additions are cosmetic and local. No protocol or host-policy code is +changed. Xbox, Custom Edition and MCC continue through their own loading +paths; the renderer only consumes their resolved object/tag interfaces. +Exact multiplayer vehicle aliases are explicitly listed where their assets +differ. A map lacking a supported object, light or marker remains stock for +that source; the feature does not manufacture replacement assets. + +Armed plasma grenades use the projectile's authored attachment. Unarmed +grenade equipment and explosion lights are not profiled. The teleporter +profile targets the visible portal scenery, not an unlit base or a gameplay +teleport flag. This matters on maps that have teleporter destinations without +a luminous portal surface. + +Authored attachments share the baseline's 128-entry temporary-state limit. +Enabled categories determine which object types are visited; with no live +flame stream, projectile-only lighting skips the emitter-owner walk. New +ambient samples share its existing eight-emitter limit; flame grouping +is also bounded to eight owners. When that pool fills, an existing held-weapon +or shield emitter can reclaim the weakest new ambient slot. Ambient additions +cannot evict those baseline emitters. Vehicle/world lights do not add an +independent light pool or GPU pass. The model point-light and eight-field +occlusion limits remain unchanged. Exceeding a budget does not remove stock +effects. It can reduce enhanced-light coverage, just as in the baseline. + +Disabling a category releases its owned lights; frame end disconnects them +before simulation. Map teardown clears profile identities and flame samples +through the existing emitter lifecycle. Recycled object IDs and changed +sample kinds cannot inherit an unrelated emitter's state. The stock shader +path and AMD/NVIDIA workarounds are unchanged; see [rendering](rendering.md). + +## Checks and limits + +### Render cost and shared integration + +[lighting_config.c](../../port/linux/game/lighting_config.c) caches local +lighting preferences until the settings generation changes. It does not +cache network shield policy or change configuration defaults and persistence. +Apply, Defaults and disabling a feature invalidate the values through the +existing configuration API. + +[plasma_collision.c](../../port/linux/game/plasma_collision.c) owns synchronous +ray-batch state. `trace_start` conservatively finds a collision-tree subtree +containing each octant of the ray cube. The shared +[collision_bsp.c](../../source/physics/collision_bsp.c) extension, +`collision_bsp_test_vector_from_node`, is needed because the existing public +query always starts at the root. It reuses the original intersection and leaf +traversal, with the original depth/node budgets reduced by the skipped prefix. +An optional bounded cache reuses identical node/plane lookups and distances +only within that batch. Simulation and other stock callers pass no cache and +start at the root. Xbox, CE and MCC use their existing collision BSPs; no map +conversion, ownership, family selection or limits change. Borrowed pointers +are cleared when the batch ends. + +`field_texture` in [plasma_occlusion.c](../../port/linux/game/plasma_occlusion.c) +compares new texels to the last successful upload. Byte-identical results skip +backing-memory writes and GPU conversion/upload; visibility history still +updates at every rendered pose. The fixed 384 KiB cache is cleared with the +fields on reset. Failed uploads invalidate it before retrying. +If visibility, radius, specular extent and admission are unchanged, successful +pass textures also remain valid across views. Directional profile/axis changes +invalidate them independently, so rotating an AR cannot reuse its old cone. +Moving geometry retains the 12 ms collision refresh cadence. Unchanged stationary +fields reuse exact collision inputs through +[plasma_collision_scene.c](../../port/linux/game/plasma_collision_scene.c): +`plasma_collision_scene_revision` snapshots nearby blocker identities, bounds, +cluster membership, permutations and collision-node poses, plus map identity, +breakable surfaces and collision debug flags. It stores values, not borrowed +pointers. Each field has a bounded 64 KiB snapshot; overflow refuses reuse. +New blockers or changed geometry invalidate reuse at the next normal refresh. +The visibility filter still advances at every rendered pose. Its seven linear +interpolations agree with the weighted form within the tested floating-point +rounding tolerance before 8-bit upload. + +`trace_object` rejects spheres disjoint from the batch ray cube once per batch, +with conservative margins. Borderline/invalid bounds use the original sphere +query; a later ray outside the cube uses the stock query. This changes only the +feature-owned batch, not simulation collision or map-family adapters. +`trace_sphere` retains the engine's finite-segment sphere predicate, reusing +origin/sphere terms per batch and vector length per ray. Its regression test +compares the predicate against the actual engine implementation. `trace_start` +proves an independent common BSP prefix for each of eight ray octants. Each +endpoint box includes the origin, so its plane bounds cover the whole ray. +Boundary planes and malformed trees retain the checked engine traversal. + +`trace_prepare` also collapses one-sided chains below branching nodes. It +prepares at most 512 nodes per octant, using the same conservative volume +test as `trace_start` through `trace_side`. Eight bounded caches occupy 96 KiB +of synchronous scratch (88 KiB more than the former single cache). Preparation +and eviction can reduce cache coverage without changing the query result. +The shared traversal consumes these optional hints because feature modules +cannot skip private internal traversal steps through the existing root-entry +interface alone. It still charges every skipped node to the original depth +and visit budgets, and falls back to normal traversal if either budget would +be exceeded. It preserves plane crossings, ordered leaf visits and all +surface tests. Stock callers supply no cache; model batches leave skip counts +zero. No map data is modified, and batch cleanup clears all borrowed pointers. + +`plasma_collision_depths` gathers eligible object/ray pairs using the same +cluster, sphere and parent/child gates. The bounded pending bitsets add 96 KiB +to synchronous batch scratch. [plasma_collision_models.c](../../port/linux/game/plasma_collision_models.c) +then visits each model node once, reusing its inverse transform, transformed +origin and BSP cache for those rays. Node order, nearest-hit limits and the +clear-ray sentinel remain unchanged. Unsupported batches rerun stock queries; +invalid model regions retain the original diagnostics and model queries. +No model pointers or matrices survive the batch. The shared model query is +unchanged, and Android excludes this feature module. + +Plasma Prong Lighting is independent of Weapon Glow, including saved preferences. +Its Plasma Rifle/Pistol profiles reach 0.3 world units in the stock maps, with a +broad forward angular fade. Spill radius eases away between three and six world +units from the nearest local camera; stock flares remain visible. The short +prong volume uses a 4-by-4 ray grid per cube face (96 rays), retaining the 16-cubed +filtered output. Other emitters retain their 16-by-16 face grids (1536 rays). +Prongs still share the eight-field budget; this setting does not reserve slots. + +[plasma_occlusion_gl.c](../../port/linux/src/plasma_occlusion_gl.c) resolves each +immutable model-mask texture once per view and skips identical per-program +uniform writes. Its bounded texture-name cache expires at each view/reset; +failed lookups retry. Units 6/7 remain separate from the four stock stages. +Unchanged material bindings reuse those exclusively owned units. A resource +upload or new view invalidates that binding state. Desktop multi-bind changes +only these two units without querying or changing the active unit; OpenGL ES +and sampler-allocation failure retain the explicit bind-and-restore path. +Repeated reset requests while disabled skip clearing already-empty field storage. + +Moving-field history uses `reproject_rows` to share x/y interpolation between +adjacent cells, then interpolates z in the update loop. Its calculation order +matches `sample_axes` exactly. Only the source rows reached by the sample axes +are prepared. `half_sample_axes` lets the common half-size texture pass reuse +that interpolation at exact quarter-texel weights; other scales retain +`sample_field`. These paths are compared against the original per-cell +calculations by the occlusion tests. + +`field_for` and `field_texture` handle cache lookup without large local buffers. +Only `update_field` and `prepare_field_texture` reserve reconstruction/pixel +scratch on a miss. Reconstruction uses 32 KiB of cell scratch; a collision +refresh adds a 24 KiB ray/depth batch and roughly 18 KiB for one model +node's nearest depths and BSP cache, plus the engine traversal stack. +The helpers explicitly prevent inlining: source-level separation alone allowed +Clang to put their stack allocation back into frequent cache hits. The storage +is temporary and render-local. Unchanged stationary targets use a flat fade loop; +ordinary model masks use a flat conversion. `texture_row` converts four pixels +together on SSE2 CPUs for half/unit-scale radial masks and angular model masks. +It retains interpolation, admission, directional and radial multiplication +order, exact division and square roots. Other architectures use the scalar row; +arbitrary radial scales retain the general calculation. Tests compare every +specialized output pixel against that calculation, including AR, Needler and +prong profiles. Fade history below `1e-20` settles +to zero before it can persist as subnormal floating-point values (values below +the normal float range). This is far below an 8-bit mask step; visible fades, +ray cadence and the simulation's floating-point mode are unchanged. The tests +cover long blocked fades and reopening at 30/60/120/240 FPS. + +`depth_visibility` avoids distance feathering only when all four sampled ray +depths prove the cell clear. It still returns the original ordered sum of +weights, including floating-point rounding; blocked or boundary samples retain +the original square root and feather calculations. The comparison test runs +both paths against the same field updates. + +`reconstruct_visibility` prepares one row at a time. On SSE2 CPUs, +`depth_visibility_row` computes four receiver cells together, retaining exact +divides, square roots, strict face-selection ties and weight order. Other +architectures retain scalar reconstruction. The 16-cubed output, ray grids, +refresh cadence, history reprojection and fades are unchanged. Tests compare +every cell against scalar arithmetic, including translated origins, both ray +grids and the scalar fallback. This is render-only arithmetic; it does not +change the simulation's floating-point mode or network state. + +The [local validation record](../dynamic_emitter_expansion_acceptance.md) +distinguishes implementation checks, rendered observations and remaining +platform/performance limits from the historical 1.0 acceptance. + +Asset-free tests execute the production profile, aggregation and menu +functions: [authored profiles](../../tools/harness/tests/test_authored_emitter_lighting.py), +[ambient samples](../../tools/harness/tests/test_ambient_emitter_lighting.py), +[emitter lifecycle](../../tools/harness/tests/test_covenant_emitter_lighting.py), +and [grouped menu staging](../../tools/harness/tests/test_lighting_menu.py). +The [Android exclusion tests](../../tools/test_android_dynamic_lighting.py) +check build graphs, defaults and inert hooks. These are not visual or driver +validation. + +The capture-only [fixture](../../tools/fixtures/plasma_lighting_capture.c) and +[runner](../../tools/plasma_visual_run.py) create ordinary objects in isolated +local maps, record selection/occlusion and capture rendered frames. Neither +the fixture nor its input controls is linked into normal builds. FPS from +captures includes readback and logging; it does not establish the current +sustained 240 FPS target or universal device compatibility. + +Baseline first-use shader hitches, local occlusion approximation and the +remaining performance/memory limitations documented in the +[release guide](../dynamic_lighting_release.md) remain applicable. diff --git a/docs/reading/enhanced_bots.md b/docs/reading/enhanced_bots.md new file mode 100644 index 0000000000..57dc280913 --- /dev/null +++ b/docs/reading/enhanced_bots.md @@ -0,0 +1,226 @@ +# Standalone enhanced bots + +Enhanced bots are an optional GulchCE controller, selected with +`bots.enhanced` when a map loads. Stock bots keep their original Slayer +combat, navigation and recovery algorithms. Exactly one controller generates +actions for a bot; enabling enhanced mode does not run the stock decision loop. +`bots.vehicles` and `bots.thread` remain off by default. Network admission, +player creation, engine physics and player action replication remain shared +engine services. Clients replay host actions and never run bot decisions. +Both controllers use the same [network population policy](bot_population.md). + +## Ownership and reading order + +1. [bots.c](../../port/linux/game/bots.c), `bots_initialize_for_new_map`, + `bots_update_actions` and `bots_dispose_from_old_map`: latch the controller, + dispatch before the stock loop, and dispose the selected owner. Common + settings, admission and management interfaces remain here and in + [bots_network.c](../../port/linux/game/bots_network.c). +2. [enhanced_bots_controller.c](../../port/linux/game/enhanced_bots_controller.c), + `enhanced_controller_update`, `bots_choose_goal`, `bots_follow_path` and + `bots_goal_failed`: independent combat state, strategic intent, current + navigation goal, paths, search budget and recovery. +3. [enhanced_bots.c](../../port/linux/game/enhanced_bots.c), + `enhanced_bots_goal` and `enhanced_bots_capture_approach`: objective policy + using existing read-only engine queries. Roles, lanes, vantage points, + powerups, Infection and link navigation remain enhanced-owned helpers; + see [the earlier feature guide](bots_and_android_features.md). +4. [bots_vehicles.c](../../port/linux/game/bots_vehicles.c), + `bots_vehicle_player_goal`, `bots_vehicle_choose_goal` and + `bots_vehicle_action`: seat claims, entry approach, progress deadlines, + driver/passenger roles, ground driving and ordinary Use-button entry/exit. +5. [enhanced_bots_flight.c](../../port/linux/game/enhanced_bots_flight.c), + `flight_search`, `enhanced_flight_action` and `enhanced_flight_can_exit`: + bounded 3D routing, takeoff, cruise, approach, descent and grounded exits. +6. [bots_worker.inl](../../port/linux/game/bots_worker.inl), + `bots_worker_submit` and `bots_worker_job`: private graph snapshots and + rejection of answers from an old goal, unit, parent vehicle or seat. + +The controller derives from OpenCE's BirchWoodGod bot implementation +(`7ea7b0bf7`) and the existing GulchCE adaptations, rather than importing an +unreviewed fork wholesale. Adapted navigation/vehicle code retains its +GPL-3.0-only notices and [recorded provenance](bots_and_android_features.md#credits-and-source-provenance). +The new aircraft planner is independently implemented against engine APIs. + +## A seat approach without goal churn + +An attacker heading toward the enemy flag sees a friendly human in a nearby +transport. The controller keeps its strategic destination separately from the +seat entrance. It reserves a legal seat, follows that entrance across ticks, +and presses Use only when the engine's nearby-seat check returns that exact +seat. Refreshing the same entrance no longer alternates between objective and +vehicle goals and invalidates the path twice each tick. Close approaches can +steer around the hull. A moving entrance can update the route; lack of progress +releases the claim instead of pursuing it forever. + +Friendly human transports can interrupt optional weapon detours, without a +minimum journey length or a Warthog-only restriction. Candidate entrances must +be near enough and slow enough to approach; a large hull does not hide a +nearby door merely because its origin is farther away. A carrier keeps returning the flag; +a bot holding the hill keeps its scoring position. Bot drivers briefly wait for +teammates with active boarding claims. Passengers stay with a friendly human +driver instead of dismounting immediately beside their previous goal. Gunners +retain their seats during quiet journeys. The engine still checks animation, +occupancy, hostility and reach. There is no forced attachment or teleport. + +Boarding, changing seats and dismounting invalidate the old navigation mode. +Passengers do not request pedestrian routes; drivers use vehicle-width ground +paths or the flight controller. Vehicle searches do not use pedestrian ladder +or jump recovery, and ground drivers wait for a usable route instead of using +the pedestrian straight-line fallback. Learned obstacles invalidate current +and pending routes. Search admission rotates among waiting bots rather than +always favoring the first three player slots. + +## Objective behavior + +CTF and King goals no longer lose priority to Slayer's last-seen-enemy chase. +Attackers retain flag destinations instead of choosing precision-weapon vantage +points, and keep advancing while fighting. Defenders can still cover their stand. +A bot on the hill does not leave for a powerup. Failed objectives release +claims and get a retry delay. A flag carrier's return remains urgent; near the +home stand, it walks onto the actual capture point and can jump onto a raised +stand instead of stopping at the normal path tolerance. The final approach +runs after ordinary combat/recovery movement arbitration, and requires a clear +collision ray so it cannot bypass the route through a base entrance. + +Path steps require horizontal and vertical proximity, avoiding false arrival +on a different floor. Teleporter/ladder traversal still uses the existing +bounded enhanced link planner and ordinary player controls. Objective state, +vehicle reservations and flight paths reset on respawn/map changes; live +removal also releases reservations. Worker shutdown joins before freeing map +snapshots, including partial preparation. + +## Custom vehicles and map families + +Vehicle discovery uses loaded unit/vehicle tags, seat definitions and physics +type, not names such as Warthog, Pelican or Longsword. Human-plane and +alien-fighter physics select flight navigation; tank, jeep and scout physics +select ground navigation. Stationary gunner seats keep turret behavior. +Custom aircraft therefore qualify when their authored physics, animations and +seats support ordinary player controls. Flight clearance uses the loaded +physics mass points, testing segments from each point at the current attitude, +relative to the physics center of mass. This follows the engine's vehicle-motion +queries for map and object geometry. Physical thickness determines cruise +height; a flat aircraft does not require its wingspan in headroom. Missing or +invalid shape data falls back to seven rays around its bounding sphere. The +engine uses unscaled mass points for vehicle physics, so visual object scale +does not rescale this hull. Nine terrain probes choose a cruise altitude over +the journey; a craft keeps its altitude until approach instead of descending +early toward a distant destination floor. +Each aircraft has at most 1024 search nodes and 32 route steps; it expands four nodes +with up to 26 neighbors each every eight ticks, with at most 256 expansions +per search. Human-plane tags can use vertical +lift; alien-fighter routes use sloped segments and reject vertical shortcuts. A search that exhausts its budget can return a +validated partial route that makes progress; it backs off when no useful route +is found. Steering uses +the vehicle's heading independently of combat aim, including while waiting +for a route. Hover craft stabilize vertical drift while a search is pending; +otherwise neutral lift slowly drops them back onto the ground. +`debug.bot_trace` also reports flight phase, search budget, route and recovery +state. Takeoff uses ordinary lift +input and turns toward the departure route before accelerating. Hover craft +keep level so their lift does not push them backwards at low thrust; bounded +search steps can align a large hull with an exit. Route lookahead lets heavy +transports skip small intermediate cells when the shortcut is clear. Progress +toward a climb waypoint counts even when it increases distance to the final +objective. Approaches brake according to speed and remain committed as the +craft slows. Landing selection checks up to 25 nearby descent columns so a +roofed objective can be reached on foot from an open landing site. Hover +aircraft align above that column before descending. Pilot fire is retained +only while steering remains aligned with the shot. +Forward-flight craft descend in a circuit around the landing site; hovering +craft use crouch lift. Forward-flight steering retains positive thrust while +airborne because its velocity correction depends on that input. The glide +permits contact with upward-facing ground while rejecting walls. +Aircraft use settled ground contact or a controlled low approach before +attempting to dismount. The latter checks height, horizontal speed and descent +rate; it avoids forcing a forward-flight craft to stop completely in the air. +These checks also apply when vehicle use is disabled. After 45 seconds +without progress along the route, a pilot with detected ground below +recovers by descending and leaving the vehicle when settled. The bot can then +resume its objective on foot. Dismount clears flight state, and a failed trip +avoids that craft for two minutes. Grounded passengers also leave a driverless craft +without requiring their old objective to be nearby. + +This is not a guarantee for every modded tag. Script-driven transports, +missing player entry animations, inaccessible entrances, water-only boat +routes and aircraft with unusual control/landing requirements need targeted +support and map tests. Mass-point segments and fallback rays are not a swept animated +mesh proof, and large aircraft require sufficient navigable space. + +Xbox and CE use their existing loaders and engine data. MCC adaptation stays +in [mcc_seats.c](../../port/linux/game/mcc_seats.c): `mcc_seat_controller` +reports the controlling player for an existing MCC seat-bearing biped. +Discovery can then offer its passenger seats without interpreting its biped +tag as a vehicle definition. No Xbox/CE loading path is repurposed. The +separation adds no shared-engine hook, packet field, physics or scoring rule; +host-generated actions use the existing protocol, so no version bump is needed. + +## Checks and evidence + +`tools/harness/tests/test_bots_stock_preservation.py` compares normalized +stock function bodies with hashes from the original implementation; admission +and dispatch are checked separately. This guards source preservation, not +runtime equivalence on every map. Its lifecycle check executes the real +initialization/disposal functions across stock/enhanced/stock map ownership, +including setting changes before disposal. + +`test_enhanced_controller.py` exercises repeated seat pursuit, objective +cooldowns, capture approach and search fairness using actual controller +functions. `test_bot_decisions.py` covers real seat selection, slowly moving +human transports, excessive speed, short journeys, reservations and recovery. +`test_enhanced_flight.py` exercises the real flight planner against an open +route, obstructing wall, sealed space and hull clearance, plus descent, exit +conditions, takeoff and retargeting. Worker tests reject stale answers after +respawn, goal changes, boarding and seat changes. These fake-world tests do not +establish flight quality for a particular map's physics. + +Validation on Windows, 3-4 November 2026: + +- Windows release, Android guest/host and web builds completed. Android/device + play and a native Linux runtime were not available in this environment. +- The focused bot, worker, lifecycle, MCC-seat, web-build and network-comparator + suite passed 198 checks, with six environment-dependent skips. All 36 web + JavaScript tests passed. Negative controls verify that removing seat commitment + or the final capture collision check makes its regression fail. +- All eight local game scenarios passed on the integrated testing baseline: + stock Blood Gulch (Normal and Veteran) and Chill Out (Heroic), enhanced + Slayer, CTF and King, network bots disabled, and an unopposed CTF return + with a completed capture. King recorded hill score. These are bounded + scenarios, not a claim of competitive play + quality on every objective layout. +- Exploratory local runs completed on CE Death Island and custom Hugeass. + The integrated candidate also completed MCC Digsite MP 1 with 15 bots. Hugeass bots naturally entered modified ground vehicles and + four custom jet seats. The controlled human-driver scenario observed a bot + approaching and boarding a Warthog through ordinary Use input. +- Host/client comparisons passed on the integrated candidate with 15 bots + and two humans for stock Xbox Slayer, enhanced Xbox CTF, CE Death Island + CTF and MCC Digsite MP Slayer. Both machines used the same candidate build. + Comparisons covered 67-75 seconds after warmup with no sustained divergence + at the comparator's tolerances and no log parse errors. A separate live + CTF run completed three removals and three additions, including slot reuse, + without sustained divergence. Quit-player statistics records remain until + match end; they are not active bot ownership. +- A dedicated server and client completed four worker lifecycles across Xbox + and CE rotations. Its existing rotation parser omitted the MCC package + entry before loading it (`maps/1.map` lookup), so this does **not** validate + MCC-to-legacy map transitions. MCC standalone network play and adapter + activation/isolation are checked separately. +- Aircraft fixtures use real loaded tags and engine physics. Initial pilot + placement and destinations are controlled; these fixtures do not prove + natural discovery of every aircraft. They exposed lift, braking, ground-exit + and flat-hull clearance problems, which have regression coverage. On the + integrated build, the Pelican travelled 496 units and dismounted 3.0 units + from its destination; the Longsword travelled 1,206 units and dismounted + 2.6 units from the authored destination. The custom jet also completed a + map-authored takeoff and delivery, dismounting on a controlled low approach + and reaching the flag on foot. A separate short approach checks early + deceleration. All three original pilots survived. This establishes delivery, + not automatic parking of every aircraft. +- Native/browser WebRTC validation was attempted but the existing test runner + fails on a Windows file-URL path (`C:\C:\...`) before compiling its helper. + Browser/native internet crossplay remains unverified here. + +Detailed run logs and isolated validation scripts are retained under the +worktree's ignored `build/enhanced-validation/` directory. Original maps and +saves are not changed; copied maps and caches are removed after each run. diff --git a/docs/reading/field_of_view.md b/docs/reading/field_of_view.md new file mode 100644 index 0000000000..831a395514 --- /dev/null +++ b/docs/reading/field_of_view.md @@ -0,0 +1,267 @@ +# Following a field-of-view setting + +This walkthrough follows GulchCE's existing first-person FOV feature from +a menu choice to the picture you see. It explains the implementation, not +a change to it. Keep the [glossary](glossary.md) nearby for unfamiliar terms; +the [reader's guide](README.md) explains the repository's structure. + +## What you see + +Video Setup's FOV AND VIEWMODELS screen has separate settings for the world +and the weapon and hands. Widening the world lets you see more around you. +By default, the weapon keeps its existing projection so that nearby arms +and a gun do not stretch along with the world. The aiming reticle adjusts +to the world view. + +Both angle settings default to `0`, meaning stock. The menu offers DEFAULT +and 80 through 150 degrees in steps of 5; the configuration accepts 20 +through 150. These are horizontal angles at 16:9. Other window shapes keep +the same vertical angle. The player-facing reference is +[Field of view](../../port/linux/README.md#field-of-view). + +The example below assumes a living local player on foot, in first person, +outside a cinematic or scripted camera, with an ordinary unzoomed view +narrower than the requested 120 degrees. + +## Open these files in order + +| Step | File and names to find | What to look for | +| --- | --- | --- | +| 1 | [port_config.c](../../port/linux/src/port_config.c): `config_settings`, `display.fov`, `config_write`, `config_changes` | The setting's default and the way readers notice a change. | +| 2 | [port_settings.py](../../tools/port_settings.py): `SCREENS["video_settings/fov_viewmodels"]`; [menu_functions.c](../../port/linux/game/menu_functions.c): `setting_changed_save`, `setting_write` | How a menu choice becomes a configuration value. | +| 3 | [main.c](../../source/main/main.c): `set_window_camera_values` | The point where an observer result becomes a local render camera. | +| 4 | [view_fov.h](../../port/linux/game/view_fov.h), then [view_fov.c](../../port/linux/game/view_fov.c): `render_fov_vertical`, `render_fov_adjust` | The feature's interface, guards, angle conversion and zoom behaviour. | +| 5 | [hud_draw.c](../../source/interface/hud_draw.c): `hud_draw_bitmap_with_meter`, `hud_draw_bitmap_internal` | Where the stored reticle scale affects the drawing. | +| 6 | [view_fov.c](../../port/linux/game/view_fov.c): `viewmodel_projection_begin`, `viewmodel_projection_end`; [rasterizer_xbox_models.c](../../source/rasterizer/xbox/rasterizer_xbox_models.c): `_rasterizer_model_begin`, `_rasterizer_model_end` | A temporary weapon camera and one pair of callers that restores it. | + +The flow below shows dependencies. The menu saves a setting once; rendering +reads the current setting as views are drawn. These are not all calls in a +single stack. + +```mermaid +flowchart TD + A[Menu choice saved] --> B[Configuration value and change count] + B --> D[render_fov_vertical] + C[Observer camera result] --> E[set_window_camera_values] + E --> D + D --> F[Adjusted world camera] + F --> G[World projection and visibility] + D --> H[Per-player reticle scale] + H --> I[HUD reticle drawing] + D --> J[Saved original vertical angle] + J --> K[Weapon projection begin] + B --> K + K --> L[Weapon draw passes] + L --> M[Weapon projection end restores camera] +``` + +## 1. A menu choice becomes a value + +In `config_settings`, `display.fov` is a real-valued setting with default +`0.0` and environment variable `HALO_FOV`. `display.viewmodel_fov` has its +own default and environment variable. The nearby strings become explanatory +comments in `config.toml`. + +The menu generator associates its FOV row with the same setting name. +When the user saves a changed selection, `setting_changed_save` passes its +text value to `setting_write`. For this non-profile setting, that delegates +to `config_write`, which updates the in-memory value, attempts to save it +to `config.toml`, and advances `config_change_count`. Its return value +reports whether the file write succeeded; updating memory and persisting +the file are distinct steps. + +`render_fov_adjust` caches the converted setting in `requested_tangent`. +It reads the configuration on its first call and whenever `config_changes()` +differs from its saved `read_at`. It does not repeat the setting conversion +for every view. This count covers configuration changes generally, not just +FOV. The menu XML is generated output; the generator is the place to change +the choices. + +## 2. Change the render camera at its boundary + +`set_window_camera_values` receives a window and a read-only observer +result. It copies camera position and orientation and computes the native +vertical FOV. It then uses `render_fov_vertical` to choose the angle for +the local render camera. The observer's result is not rewritten by this +FOV adjustment. + +The input angle is already part of the game's camera convention. +`render_camera_get_adjusted_field_of_view_tangent` in +[render_cameras.c](../../source/render/render_cameras.c) multiplies the +half-angle tangent by `0.85`; the conversion in `main.c` also applies +`0.75`. Follow those expressions when tracing a stock angle rather than +assuming a number from a unit tag is the final on-screen angle. + +Later, [render.c](../../source/render/render.c) builds frustums from the +prepared cameras. Applying the FOV before that step makes the projected +picture and the visibility calculations use the chosen angle together. +Changing only the final picture could leave objects outside the old view +excluded from drawing. + +On `online-third-person`, `set_window_camera_values` first lets +`third_person_camera` resolve the shoulder camera and collision, then +chooses the FOV. Its `render_fov_vertical` keeps the native angle while +`third_person_active` is true, and `viewmodel_is_visible` also hides the +first-person weapon in that mode. The first-person path described here +applies when that mode is inactive. This branch-specific ordering matters +when locating the call in `main.c`. + +The director now selects the feature-owned `third_person_camera_update` +callback, which retains the stock first-person eye calculation. Its reported +perspective follows the resolved shoulder view, including collision fallback. +This lets body and particle rendering use the ordinary director query while +hidden viewmodel poses and sounds remain live for immediate fallback. Read +[the shoulder-camera walkthrough](third_person.md) for the selection order, +controls and host-owned combat path. + +## 3. Read the reasons for doing nothing + +Inside `render_fov_adjust`, several early returns preserve the incoming +angle. The adjustment needs a valid requested angle and local-player +index, a suitable first-person director state, and a live unit. It is +bypassed during cinematics, scripted cameras or inhibited camera facing, +and for a unit attached to a parent object or marked dead. The parent +check covers the usual vehicle case. Invalid native or unit-definition +angles also leave the view unchanged. + +`unit_index` is a datum handle, not a direct subscript. The function checks +for `NONE`, asks `unit_try_and_get` for the unit, and checks the returned +pointer before reading it. These guards explain the feature's scope as +well as avoiding invalid accesses. + +## 4. Follow 120 degrees through the calculation + +The setting describes a horizontal angle, but the renderer needs a vertical +one. The code first calculates: + +```c +tan(degrees * _pi / 360.0) * (9.0 / 16.0) +``` + +`degrees * pi / 180` would convert degrees to radians. The divisor is 360 +here because the calculation uses half the angle. Imagine a triangle from +the eye to the centre and top edge of the view: the tangent of the vertical +half-angle is its half-height divided by distance. Multiplying the +horizontal half-angle tangent by `9/16` converts half-width to half-height +at the reference aspect ratio. + +At 120 degrees, `requested_tangent` is approximately `0.9743`. Converting +back with `2 * atan(requested_tangent)` gives about `88.5` vertical degrees. +These are illustrative rounded values, not an exact floating-point test +or a claim about every map's stock camera. + +For the unzoomed example, `blend` is one and `native_tangent` equals the +unzoomed reference. This expression therefore reaches the requested tangent: + +```c +adjusted_tangent = native_tangent + (requested_tangent - unzoomed_tangent) * blend; +``` + +The function returns `2.0f * atanf(adjusted_tangent)`, the vertical angle +in radians. The calling code can now build the view from it. + +## 5. Zoom changes the calculation + +For a request wider than the stock unzoomed view, the extra width fades +away as the weapon zooms. `weapon_get_field_of_view` supplies the weapon's +scoped reference; the blend measures where the current camera lies between +the scoped and unzoomed tangents, clamped to zero through one with `PIN`. +At or beyond the scoped threshold, the function returns the native angle. + +The `1.000001f` tolerance at that threshold handles the small rounding +difference described by the code comment: converting through arctangent +and tangent can land slightly above the scoped value. Returning the input +also avoids recalculating an angle that should stay unchanged. + +A request narrower than the stock view takes a separate branch. It scales +the native tangent by `requested_tangent / unzoomed_tangent`, narrowing +the zoom too. "Scopes keep their stock view" therefore describes the +widening case, not every possible setting. + +## 6. Keep the reticle and weapon consistent + +`render_fov_vertical` also writes two arrays indexed by local player: + +| State | Written value | Reader | +| --- | --- | --- | +| `reticle_scales` | Native half-angle tangent divided by adjusted half-angle tangent, or one when unchanged or unusable. | `render_fov_reticle_scale`, used by HUD drawing. | +| `authored_vertical` | The incoming vertical angle when the adjustment changes it, otherwise zero. | `render_fov_authored_vertical`, used as the default weapon angle. | + +For a widened view, the scale is below one. In `hud_draw_bitmap_with_meter`, +only crosshair bitmaps anchored at the centre receive this scale. +`hud_draw_bitmap_internal` scales their vertices about the view's centre, +including the offsets of separate pieces. It does not scale the entire +HUD. [hud_weapon.c](../../source/interface/hud_weapon.c) distinguishes +scope overlays from the reticle drawing that receives this adjustment. + +The weapon can use `display.viewmodel_fov` explicitly. With that setting +at zero, `viewmodel_projection_begin` falls back to the saved incoming +angle when the world FOV changed. Despite the comments' emphasis on +widening, the assignment to `authored_vertical` uses `adjusted != native`: +it records the original for a narrowing adjustment too. + +The begin function checks whether a suitable primary first-person view is +being drawn, saves both the render and rasterizer cameras and frustums, +changes their angles, and rebuilds the frustums using their saved bounds. +Those bounds preserve the crop of a split-screen view. The weapon's pose +and attachment markers are not moved by this projection change. + +Several weapon passes can nest. `projection_depth` counts unmatched begin +calls: only the outermost begin saves and applies a camera, and only its +matching final end restores it. Even a begin that skips the adjustment has +increased the depth and needs an end. `projection_applied` distinguishes +"entered the scope" from "actually replaced the camera". + +These saved structures are shared drawing state, not per-player arrays. +The contract is balanced, nested use within the current render view; +the helper does not provide independent state for concurrent render calls. +Restoring the camera prevents the temporary weapon projection affecting +later drawing. The model begin/end functions are one example; lighting, +transparent geometry and sprite rendering also bracket weapon passes. + +## What is inherited and what the port adds + +The observer and director, unit and weapon definitions, weapon zoom and +render-camera machinery belong to the existing engine. The port's FOV +module adds the configuration-driven render adjustment, reticle scaling +and temporary weapon projection. Its integration points in `source/` +carry `port:` comments. GulchCE's third-person branch adds the extra +camera selection described above. + +The module's opening comment explicitly states that the observer, +transitions and network data retain the game's own camera. The traced +code supports that separation by modifying render state. This is an +explanation of the implementation and its documented intent, not a new +claim based on a multiplayer run. + +## Checks and limits + +This walkthrough was checked against the configuration, menu save path, +camera calls, FOV module and drawing consumers. No game session was run +to write it. The 120-degree example explains the calculation, not visual +behaviour on a particular map or platform. + +The existing [harness](../../tools/harness/README.md) tests include FOV +cases for [first-person legs](../../tools/harness/tests/test_first_person_legs.py) +and [arm shield geometry](../../tools/harness/tests/test_viewmodel_shield.py). +Those exercise their own features; they do not establish coverage of +`render_fov_adjust` or the full projection begin/end lifecycle. + +On `online-third-person`, `tools/test_third_person.py` adds +`test_real_fov_restoration`, which extracts the real `render_fov_adjust` +and `render_fov_vertical` functions into a fake world. It checks selected +angles, scoped behaviour, restoration after third person and separation +between local players. `test_perspective_paths` also checks the wrapper's +third-person bypass, with the adjustment helper stubbed. These tests were +inspected, not run, for this guide. No dedicated test of the FOV functions +was found on `main`, `testing`, `dynamic-lighting-test` or `vulkan-renderer`. +These third-person tests do not cover the full projection begin/end lifecycle. + +When changing this feature, useful checks would cover the stock sentinel, +angle boundaries, excluded camera states, widening and narrowing through +zoom, separate local-player values, and balanced nested projection calls. +A visual check should compare DEFAULT and a wide angle, zoom transitions, +reticle alignment, default and explicit weapon FOV, and split screen at +different aspect ratios. Third-person builds also need the transition into +and out of that camera checked. These are suggested checks, not recorded +test results; platform requirements still come from [AGENTS.md](../../AGENTS.md). diff --git a/docs/reading/glossary.md b/docs/reading/glossary.md new file mode 100644 index 0000000000..05385cd6a8 --- /dev/null +++ b/docs/reading/glossary.md @@ -0,0 +1,83 @@ +# Code reader's glossary + +These definitions are a starting point for reading GulchCE, with examples +from the subsystem chapters and [FOV walkthrough](field_of_view.md). Return to the +[reader's guide](README.md) for a reading route. + +## Engine concepts + +| Term | Meaning here | Example or source | +| --- | --- | --- | +| Stock / native / authored | The existing game's value or behaviour before the feature's adjustment. "Native" can also mean a platform build elsewhere; in `native_vertical_field_of_view` it means the incoming camera angle. "Authored" often refers to values stored in game data. | `render_fov_adjust` in [view_fov.c](../../port/linux/game/view_fov.c). | +| Tag | A typed piece of game data describing something such as a unit, weapon, bitmap or sound. It is not a Git tag. | [Tag structures](../../source/tag_files/tag_groups.h); [mods](../mods.md) describes editable tag files. | +| HRTF / DSP | Head-related transfer function: the direction-dependent filtering and delay reaching each ear. Digital signal processing: computations such as filtering, resampling and reverb. | [Xbox audio processing](xbox_audio.md). | +| Doppler | The change in heard pitch caused by motion towards or away from the listener. Source channels (mono/stereo assets) are separate from output speaker channels. | [Doppler audio](audio_doppler.md). | +| Definition / instance | A definition describes a kind of thing; an instance holds the state of one thing that currently exists. Multiple units can refer to the same definition. | FOV reads `camera_field_of_view` from the unit definition, but reads death and parent state from the live unit in [view_fov.c](../../port/linux/game/view_fov.c). | +| Datum / datum index | An entry in an engine data pool, and the handle used to find it. A datum index can combine a slot number with an identifier that distinguishes uses of that slot; it is not generally a plain array subscript. | `datum_try_and_get` in [data.c](../../source/memory/data.c) splits and checks these parts. | +| Syntax node / expression root | A node stores part of a compiled script expression and links to other nodes. The root handle identifies the expression's entry point; it must remain valid while a thread can resume it. | [Console checkpoints](console_checkpoints.md), [hs_scenario_definitions.h](../../source/hs/hs_scenario_definitions.h). | +| Interpreter stack frame | A record of a script call that has not finished, including its expression handle, result destination and arguments. It belongs to the script thread and is distinct from the C call stack or a rendered frame. | `hs_stack_frame` in [hs_runtime.c](../../source/hs/hs_runtime.c); [console checkpoints](console_checkpoints.md). | +| Unit | A game object of the kind used for characters and vehicles. A player controls a unit; the player record and the unit are different things. | `player_control_get_unit_index` and `unit_try_and_get` in the [FOV module](../../port/linux/game/view_fov.c). | +| Local player | A player on this machine. There can be several in split screen. A local-player index is not a network-wide player identity or an object datum index. | The `reticle_scales` array in [view_fov.c](../../port/linux/game/view_fov.c) stores a value for each local player. | +| Tick / frame | A tick advances the simulation; a frame is a drawn picture. The game's normal simulation rate is 30 ticks per second, while smooth motion can draw more frequently. | [Frame rate](../../port/linux/README.md#frame-rate). | +| Interpolation | Blending between known states to produce an intermediate state, such as the position drawn between simulation ticks. | [Frame rate](../../port/linux/README.md#frame-rate). | +| Prediction / authority | Prediction lets a client respond to its own input before hearing back. Authority identifies who decides the accepted game result: the host. | [Distributed netcode](../../port/linux/NETCODE.md). | +| Observer / director | Camera systems: the observer supplies a camera result, while the director's state includes the viewing perspective. A render camera is prepared from that result. | `set_window_camera_values` in [main.c](../../source/main/main.c); the director checks in [view_fov.c](../../port/linux/game/view_fov.c). | +| FOV / aspect ratio | Field of view is the angular extent of a camera's view. Aspect ratio is width divided by height. A horizontal angle and a vertical angle describe different extents. | Settings use a horizontal angle at 16:9; [view_fov.c](../../port/linux/game/view_fov.c) converts it to the vertical angle used for drawing. | +| Projection / frustum / culling | Projection maps 3D positions onto the screen. The frustum describes the camera's viewing volume. Culling excludes things outside the view from rendering. | Camera and frustum structures in [render_cameras.h](../../source/render/render_cameras.h). Changing FOV must keep drawing and visibility calculations consistent. | +| Viewmodel / render pass | The viewmodel is the first-person weapon and hands. A pass is a drawing stage; the weapon can participate in several stages, including lighting and transparency. | The begin/end functions in [view_fov.c](../../port/linux/game/view_fov.c) temporarily change the camera around weapon passes. | +| HUD / reticle | The heads-up display includes meters, text and aiming graphics. A reticle is an aiming graphic; changing its scale does not mean scaling the whole HUD. | `hud_draw_bitmap_with_meter` in [hud_draw.c](../../source/interface/hud_draw.c). | +| ABI | The binary conventions code must agree on: type sizes, structure layout and how arguments and results are passed. Correct-looking C can still fail if those conventions differ. | [The compiler](../../port/linux/README.md#the-compiler) and the [Android guest](../../port/android/README.md). | +| Invariant / lifecycle | An invariant is a rule that must hold, such as restoring a temporary camera change. A lifecycle describes when state is created, used and cleared or restored. | Every `viewmodel_projection_begin` needs a matching `viewmodel_projection_end`, including nested calls. | + +## Concepts used across the chapters + +| Term | Meaning here | Where to follow it | +| --- | --- | --- | +| Scenario / BSP | A scenario describes a level and its content. A structure BSP supplies spatial geometry, collision and related visibility data; a scenario can switch between BSPs while remaining the same level. | [Maps and resources](maps_and_resources.md), [scenario.c](../../source/scenario/scenario.c). | +| Cache file / resource | A map cache packages game data. A resource is data it needs, such as bitmap pixels or sound samples, which may live in a separate file. This use of "cache" does not mean the map is disposable temporary data. | [Maps and resources](maps_and_resources.md). | +| Relocation / runtime tags | Converting stored addresses or references into representations usable in the loaded runtime. Parsed file bytes and usable engine structures are different stages. | [CE format reader](../../port/linux/game/cache_file_formats.c), [MCC loader](../../port/linux/game/mcc_cache.c). | +| Map family / namespace | Xbox, CE and MCC content have distinct paths and compatibility implementations. A namespace such as `mcc_maps` identifies the intended family before its tags are loaded. | [Maps and resources](maps_and_resources.md). | +| Content identity / package binding | Identity describes the admitted content; binding resolves it to local package files. Equivalent network content can have different local folder names. A matching basename alone is insufficient. | [mcc_identity.c](../../port/linux/game/mcc_identity.c). | +| Game engine / gametype | In names such as `game_engine_running`, this often means the match-rule machinery, such as Slayer or CTF, rather than the entire running application. | [Startup](startup_and_loop.md), [game.c](../../source/game/game.c). | +| Action / input blob | A game-level description of movement, facing and controls derived from device input. It is not a direct assignment of world position. | `get_local_player_input_blob` in [player_control.c](../../source/game/player_control.c). | +| Reconciliation / correction | Bringing a local simulation copy toward authoritative state. For an owned player, the code can compare matching historical positions and apply their difference to the present. | [Networking](networking.md). | +| Framebuffer | A render target holding image attachments. OpenGL has separate read and draw bindings; read binding zero selects the default window framebuffer. | [Rendering and presentation](rendering.md). | +| Reliable stream / datagram | A reliable connection preserves ordered delivery; datagrams can arrive late, out of order or not at all. The message's meaning determines which is appropriate. Neither makes incoming data trustworthy. | [Network transport](../../port/linux/NETCODE.md#transport). | +| Admission / capability | Admission accepts a peer into a session after checks. Capability advertises protocol support; it does not prove identity or grant gameplay authority. | [third_person_protocol.c](../../port/linux/game/third_person_protocol.c). | +| PVS / occlusion | A potentially visible set is a conservative map visibility aid. Occlusion concerns something being hidden by other geometry; CPU culling and GPU queries can answer different visibility questions. | [Rendering](rendering.md), [visibility queries](../visibility_queries.md). | +| Shader / GLSL / SPIR-V | A shader describes GPU computations. GLSL is shader source used by the translation paths; SPIR-V is an intermediate representation used by the experimental Vulkan backend. | [Rendering](rendering.md). | +| Render target / GPU fence | A render target receives drawing output. A fence signals completion of submitted GPU work, which matters before reading results or reusing resources. | [Rendering](rendering.md). | +| Guest / host / ILP32 | On Android, the game guest uses 32-bit integers, longs and pointers in AArch64 code, while the surrounding host app is 64-bit. Here "host" is a runtime role, distinct from a network host. | [Platforms](platforms_and_testing.md). | +| Harness / fixture / stub | A harness runs code in a controlled setup. A fixture supplies test data or state. A stub substitutes a dependency so a smaller piece can be tested. | [Harness reference](../../tools/harness/README.md). | +| Origin / OPFS | An origin is a site's scheme, hostname and port. The Origin Private File System keeps that origin's files privately in browser storage; it is separate from the user's ordinary filesystem and other origins. | [Browser map imports](browser_imports.md). | +| Web Lock / storage lease | A browser lock coordinates same-origin tabs and workers. Shared game guards allow several readers; an exclusive import guard or MCC mutation lease permits one writer. Releasing the callback and completing release are distinct asynchronous steps. | `lock` and `startGame` in [map-import-storage.js](../../port/web/site/map-import-storage.js). | +| Transaction journal / commit record | A journal records the bounded paths an unfinished operation owns. A commit record is written after validation; recovery uses both to preserve completed packages or remove only unfinished owned files. An uncertain reply does not prove failure. | [Browser storage lifecycle](browser_imports.md#state-visibility-and-lifecycle). | +| Negative control / mutation | Deliberately faulty extracted code that a test must reject. This checks that the test notices a particular defect, without introducing that defect into production source. | [Testing evidence](platforms_and_testing.md). | + +## C conventions in the walkthrough + +| Form | How to read it | +| --- | --- | +| `real`, `boolean` | Project type names. [cseries.h](../../source/cseries/cseries.h) defines `real` as `float` and `boolean` as `byte`. | +| `struct unit_datum *unit` | `unit` is a pointer to a unit structure. The pointer gives access to an existing object; the declaration alone does not create or allocate that object. | +| `unit->object.parent_object_index` | Follow the pointer to `unit`, then read its `object` member and that member's `parent_object_index`. A dot accesses a member directly; an arrow accesses it through a pointer. | +| `&render.camera` | The address of the camera, passed to a function that needs to read or modify that structure. Check the function's contract to see which it does. | +| `const struct observer_result *observer` | This pointer provides read-only access to the observer result through this parameter. It does not make every other reference to that object read-only. | +| `NONE`, `NULL`, `0.0f` | Different meanings: `NONE` is the engine's `-1` sentinel for no index; `NULL` is no pointer; `0.0f` is floating-point zero. In the FOV setting, zero specifically selects stock behaviour. | +| `static real render_fov_adjust(...)` | At file scope, `static` limits the function's visibility to this C file. Other files call the exposed wrapper `render_fov_vertical`. | +| `static unsigned long read_at` inside a function | This local variable retains its value across calls. In FOV it remembers which configuration change count was last processed. It is not automatically per-player or thread-safe. | +| `!value`, `a && b`, `a \|\| b` | "Not value", "both", and "either". `&&` and `\|\|` stop once the result is known; `!unit \|\| unit->...` therefore avoids dereferencing a null pointer. | +| `condition ? a : b` | Use `a` when the condition is true, otherwise `b`. The FOV conversion uses this to select a valid converted setting or the zero sentinel. | +| `TEST_FLAG(flags, bit)` | Test one bit in a collection of flags. In FOV, `_object_dead_bit` identifies the death flag; it is not the whole flag value. Defined in [cseries.h](../../source/cseries/cseries.h). | +| `PIN(value, low, high)` | Clamp a value to a range. FOV uses `PIN(..., 0.0f, 1.0f)` to keep a blend fraction between zero and one. Defined in [cseries.h](../../source/cseries/cseries.h). | +| `0.5f`, `(real)value` | The `f` suffix makes a floating-point literal a `float`. The cast explicitly converts a value to the project's `real` type. | +| `#include`, `#if` / `#ifdef` | Instructions processed before C compilation: include declarations or conditionally compile code. They are not runtime branches. | + +An early `return native_vertical_field_of_view;` means "leave the incoming +angle unchanged for this case". Reading these exits first often makes a +large function easier to understand than starting with its calculations. + +Ordinary-looking maths calls can be redirected by project headers. The +game's native maths use the shared implementation described in +[halo_math.h](../../port/include/halo_math.h). Seeing `tan(...)` in source +does not establish that the system's maths library is being called. diff --git a/docs/reading/hud_corrections.md b/docs/reading/hud_corrections.md index fb61da932c..bc87f986d8 100644 --- a/docs/reading/hud_corrections.md +++ b/docs/reading/hud_corrections.md @@ -1,42 +1,165 @@ -# High-resolution reticle and zoom-label corrections +# High-Res HUD artwork corrections With High-Res HUD enabled, the stock rocket reticle, sniper reticle and supplied -zoom labels use the contributor's [original pictures](../../port/assets/hud/corrections/README.md). -The sniper reticle and the Xbox's 2x and 10x zoom labels retain the -low-resolution artwork's visible size and center. -Input, simulation, zoom magnification and sprite geometry are unchanged. +zoom labels use the owner's [original pictures](../../port/assets/hud/corrections/README.md). +Xbox Classic button letters are transparent cutouts. Tutorial thumbsticks use +the existing high-resolution controller path, including animated stick presses. +These are display changes; input bindings, simulation and networking are unchanged. ## Reading route -1. [hud_corrections.py](../../tools/hud_corrections.py) records the source crops and - atlas rectangles. [hud_assets.py](../../tools/hud_assets.py), `build_asset`, - converts black-background luminance to premultiplied white coverage and scales - proportionally. It never redraws shapes or substitutes a font. Visible reticle - bounds match the stock 9x9 texel footprint within one generated high-res pixel. - The Xbox zoom labels are placed on their stock glyphs, not their sprites, - which have empty texels around the glyphs: 10x matches the stock 32x14 - texels within one high-res pixel, 2x the stock 21x14 within three (the - supplied 2x is a little wider for its height). -2. Xbox uses its existing texture override and atlas. The setting and original - pixel signature gate replacement in [hud_hires.c](../../port/linux/src/hud_hires.c). - CE's rocket uses the existing compatible-sheet registration. -3. CE's separately packed scope contains the supplied 2x and reticle. The map's - existing 8x artwork is preserved. `hud_hires_crosshair_bitmap` in - [hud_hires_tags.c](../../port/linux/game/hud_hires_tags.c) selects only those - verified sprites through the existing placeholder mechanism. Sequence 1, - frame 1 remains the original 8x. -4. The small marked hook in [hud_weapon.c](../../source/interface/hud_weapon.c) - is necessary because a whole-sheet override would replace that 8x frame too. - It runs after the source texture is resident. Custom art failing the stock - signature checks keeps its original pixels, as does High-Res HUD OFF. - -For example, CE's first sniper zoom shows the supplied 2x picture while the next -still shows its own 8x. Xbox uses the supplied 2x and 10x pictures. No zoom values -or weapon behavior change. Placeholders belong to the existing map lifetime and -are released by `hud_hires_tags_unloaded`. - -[Correction tests](../../tools/test_hud_corrections.py) verify original source -hashes, exact supplied-pixel packing, the stock visible footprints of the reticle -and the Xbox zoom labels, and -CE's frame selection, including disabled, custom-art and failed-match fallbacks. -Actual maps and renderers additionally require runtime checks. +1. [hud_corrections.py](../../tools/hud_corrections.py) records the crop and atlas + rectangles. [hud_assets.py](../../tools/hud_assets.py), `build_asset`, converts + black-background luminance to premultiplied white coverage and proportionally + resizes the supplied pixels. It does not reconstruct their shapes or font. + The sniper reticle fits the stock visible footprint, not the larger padded + sprite cell: 9x9 texels on Xbox/CE and 36x36 on MCC's four-times-resolution + sheet. These bounds were measured from stock alpha coverage; the supplied + image matches their size and centre within one generated high-resolution + pixel. Sprite geometry remains unchanged. Xbox 2x and 10x label pixels fit the stock + glyph bounds rather than their padded sprites: 10x within one high-resolution + pixel, 2x within three because the supplied glyph is proportionally wider. + CE and MCC retain their separate label placements. +2. Xbox retains its existing texture replacement path and atlas layout. + [hud_hires.c](../../port/linux/src/hud_hires.c), `hud_hires_override_find`, checks + the setting and original pixel signature. CE's rocket uses its existing + compatible stock-sheet registration. +3. CE's scope has a different layout and an 8x label. Its separate atlas contains + only the supplied 2x and reticle. In + [hud_hires_tags.c](../../port/linux/game/hud_hires_tags.c), + `hud_hires_crosshair_bitmap` selects those sprites through the existing + CRC-checked placeholder machinery. Sequence 1, frame 1 keeps the original 8x. + The small [hud_weapon.c](../../source/interface/hud_weapon.c) hook is needed + because a whole-texture override cannot preserve one frame of a sequence. + It runs after the source bitmap is resident and changes no sprite bounds, + placement, zoom values or tag contents. Other map families return their original + bitmap. CE embedded/custom art still fails stock registration or pixel checks. +4. [mcc_texture_bridge.c](../../port/linux/src/mcc_texture_bridge.c), + `mcc_hud_texture_asset`, recognizes the complete converted stock MCC sheets by + dimensions, format, byte count and CRC, including the `_r` variants. It uses + independently packed MCC atlases. No Xbox/CE loading or registration is used. + `xgpu_mcc_texture_get` checks High-Res HUD at draw time; disabling it returns the + original texture immediately. Failed replacement uploads also fall back. +5. [button_assets.py](../../tools/button_assets.py), `classic`, masks the existing + letter out of the coloured oval. The bounds in + [hud_button_layout.h](../../port/linux/game/hud_button_layout.h) match the + committed alpha mask, keeping the existing visible size and text anchoring. + +For example, CE's first sniper zoom uses the supplied 2x picture, while its next +zoom still draws the map's 8x. Neither label changes the actual magnification. +Custom textures that do not match the stock signatures keep their artwork. + +## State and checks + +CE placeholders belong to the existing map lifetime and are released by +`hud_hires_tags_unloaded`. MCC holds only an asset index in its own texture entry; +the embedded-HUD service owns replacement GPU textures. MCC teardown frees the +entry and its original GPU texture, without deleting the borrowed replacement. + +[Correction tests](../../tools/test_hud_corrections.py) check supplied-pixel +packing, transparency and CE's untouched 8x selection. +[MCC bridge tests](../../tools/test_mcc_texture_bridge.py) check stock/custom +identity, settings changes, upload failures and ownership. +[Button tests](../../tools/test_hud_button_style.py) and +[MCC HUD tests](../../tools/test_mcc_hud.py) cover control animation, prompt +geometry and split-screen scaling. Runtime captures are needed in addition to +these isolated tests to verify actual map loading and draw paths. + +## Custom Edition authored HD scaling + +A CE map can ask for smaller HUD geometry through bitmap flags, independently +of the High-Res HUD artwork setting. The setting still controls the supplied +replacement pictures. Correctly interpreting a map's own flags is part of CE +compatibility and is always active when CE tags are loaded. + +[custom_edition_hud_scale.h](../../port/linux/game/custom_edition_hud_scale.h), +`custom_edition_hud_scale`, composes the flags: + +| Placement high resolution | Bitmap flags | Geometry multiplier | +| --- | --- | --- | +| No | Neither | 1 | +| Yes | Neither | 1/2 | +| Either | Force high resolution | 1/2 | +| No | Half scale | 1/2 | +| Yes | Half scale | 1/4 | +| Either | Half scale and force high resolution | 1/4 | + +For example, a 256-pixel bitmap with both bitmap flags occupies 64 HUD units +before the ordinary viewport scaling. The two halvings are independent; +placement high resolution and bitmap force-highres describe the same halving. + +Read [cache_file_formats.c](../../port/linux/game/cache_file_formats.c), +`hud_conversion_placement`, for the bounds-checked conversion of statics, +meters, crosshairs and overlays. Crosshair and overlay items ignore placement +high resolution, retaining the existing CE behavior. Number placements retain +their flag: `hud_draw_numbers` scales digit geometry separately from authored +spacing. The known-map `hud_number_scale` correction already halves metrics +and supplies bitmap half-scale, so its placement flag cannot halve again. +`disable_bitmap_hud_scale_flags` still clears both bitmap flags before conversion. + +[custom_edition_hud_draw.c](../../port/linux/game/custom_edition_hud_draw.c) +owns the runtime CE interpretation for numbers and draws without converted +placements: pickup icons, waypoint arrows, friendly markers, damage arrows, +scope expansion and convolution masks (the texture that shapes the scope's +screen effect). These hooks are necessary because the engine constructs their +geometry at draw time. Pickup text advance scales only the bitmap width; +authored offsets and absolute widths retain their meaning. Stock controller +glyphs and MCC icon handling retain their existing early returns. + +`interface_draw_screen` borrows the selected mask only across its synchronous +`rasterizer_screen_effect` call. `custom_edition_hud_mask_transform` accepts +only that bitmap, then `custom_edition_hud_mask_end` clears both pointer and +scale before another view or map can draw. The renderer hook adjusts texture +coordinates as well as mask size; a viewport fallback or cinematic texture is +not treated as a CE HUD mask. No shared screen-effect structure changes layout. +All runtime helpers return identity outside CE, and MCC's own canvas, loaders, +textures and cleanup remain in MCC modules. Existing CRC-based artwork +replacement, warning placement, reticle selection and digit spacing are retained. + +The selective backport follows [ChupathingyCE #352](https://github.com/ChupathingyCE/chupathingyce/pull/352) +by Boom Pen / ugoboom and [#545](https://github.com/ChupathingyCE/chupathingyce/pull/545) +by Milenko, under GPL-3.0-or-later. Flag composition is adapted from +[Chimera's `check_half_scale_bitmap_flag`](https://github.com/SnowyMouse/chimera/blob/master/src/chimera/fix/hud_bitmap_scale.cpp), +under GPL-3.0-only, as marked in the header. These licenses are compatible with +this repository's AGPL-3.0-or-later distribution; the derived header retains its +GPL-3.0-only notice. The backport does not import upstream's older placement +rewrites or its unrelated replacement art. + +[Converter tests](../../tools/test_cache_file_formats.py) exercise real synthetic +tag conversion across all flag combinations. [Draw tests](../../tools/test_ce_hud_scaling.py) +compile the implementation's functions to check number exceptions, pickup +geometry, split-screen scaling, controller/MCC ownership and mask scope through +map-family transitions. They do not establish visual compatibility for every +custom map; runtime checks must include authored HD assets and stock Xbox/CE/MCC +maps, with the artwork setting both disabled and enabled. + +## MCC corner frames and screen-effect masks + +MCC compatibility belongs to [mcc_hud_draw.c](../../port/linux/game/mcc_hud_draw.c). +Within `hud_draw_screen`, `mcc_hud_view_begin` reads the active unit HUD for the +current player, including its split-screen selection. When conversion has +recognized that HUD's native layout, messages and corner-anchored weapon panels +use its common safe frame. For example, customizing the numbers inside an ammo +panel must not move the entire panel to a different margin from the grenade +counter. Authored offsets stay intact. Center and edge anchors retain their +separate meanings; an unknown custom unit HUD retains the existing component +classification. `mcc_hud_view_end` clears the selection before the next view. +The existing stock-layout fingerprints are still a compatibility exception, +not a general description of every custom HUD; this change adds no fingerprints. + +Screen-effect masks take a different route: `interface_draw_screen` supplies +the selected bitmap directly to the rasterizer. They do not pass through HUD +placement. `mcc_hud_mask_begin` borrows that pointer across the synchronous +screen-effect call; `mcc_hud_mask_transform` applies the bitmap group's half-size +flag to both geometry and texture-coordinate units. It excludes the ordinary +MCC placement-canvas factor, which would shrink the mask twice. The end call +clears the pointer and scale. Untagged generated bitmaps retain native units; +other render-target and cinematic textures do not match the borrowed bitmap +and remain unchanged. Both hooks are neutral +outside MCC, preserving the existing Xbox/CE paths. + +[View-frame tests](../../tools/test_mcc_hud_view.py) cover player selection, +authored offsets, custom anchors and view reset. [Mask tests](../../tools/test_mcc_hud_mask.py) +cover flag composition, linear/normalized coordinates, borrowed-pointer +ownership and the shared call sites. Actual rendered comparisons and their +limits are recorded in [Milestone 15](../mcc_refactor_validation.md#milestone-15-mcc-hud-corrections-and-shared-cinematic-aim). diff --git a/docs/reading/keyboard_prompts.md b/docs/reading/keyboard_prompts.md index f6bcedae74..9f0a8ca5d1 100644 --- a/docs/reading/keyboard_prompts.md +++ b/docs/reading/keyboard_prompts.md @@ -1,146 +1,183 @@ -# Keyboard and mouse prompts +# Keyboard and mouse prompt glyphs -Gamepads > Button Appearance offers KEYBOARD GLYPHS, off by default. Turn it on -with AUTO BUTTON DETECTION to show keycaps after keyboard/mouse activity and -controller artwork after controller activity. With detection off, BUTTON STYLE: -KEYBOARD forces keycaps independently of the opt-in. Existing controller-family -and manual preferences are retained. MENU GLYPHS is a separate opt-in for existing -PC-menu face-button legends, using the same keyboard/controller style selection. -Neither keyboard mode requires High-Res HUD; High-Res Text controls font rendering. +AUTO DETECTION is on by default and follows keyboard/mouse or controller activity. +Keyboard/mouse selects binding-aware keycaps in supported gameplay prompts and +modern menu footers. There is no separate Keyboard Glyphs switch. Old +`display.keyboard_glyphs` entries are ignored; they no longer gate detection. -For example, rebinding Action from E to F in Controls Setup makes a supported -pickup/tutorial prompt show F on its next lookup. The primary valid binding wins; -an unbound primary uses the secondary, and neither bound displays `Unbound`. -Mouse buttons and wheel directions have symbols; longer labels widen the keycap. +In modern Settings > Interface, turn AUTO DETECTION off and select KEYBOARD under +MANUAL STYLE to keep keyboard and mouse prompts even when a controller is used. +The existing Gamepads > Button Appearance screen offers the same manual style. +Automatic mode shows a read-only BUTTON STYLE: KEYBOARD row while keyboard/mouse +is active, without changing the saved manual or controller-family preferences. +Keyboard and controller glyphs require High-Res HUD. High-Res Text controls font +rendering independently. Modern Settings hides all glyph appearance controls when +its pending High-Res HUD value is off, preserving every saved choice. With High-Res +HUD off, modern menus use text prompts and stock PC menus retain native prompts. -## Reading route and boundaries +Modern Settings > Interface also exposes **STOCK MENU GLYPHS**, off by default +(`display.menu_button_glyphs`, `HALO_MENU_BUTTON_GLYPHS`). The classic Button +Appearance screen calls it **MENU GLYPHS**. It replaces recognized PC-menu +navigation pictures with the selected keyboard, Xbox, PlayStation or Switch art, +including PC pause footers on Xbox, Custom Edition and MCC maps. It follows the +existing automatic/manual style policy within the High-Res HUD gate. Modern +footer prompts remain separate from this toggle; Xbox menu selection stays native. + +Compact pause keys use 85% lettering and four units of side padding, retaining +their blue, full-height outline. The layout keeps eight units between CANCEL +and the Enter keycap. Gameplay and ordinary modern keycaps keep their dimensions. +Confirmation legends with small button slots use the same compact layout even +under `confirm_buttons` as well as `button_key` and `button_key_sm`. A short +authored gap is expanded as needed, including Revert and Restart confirmations. +PC join prompts are centered as complete text-and-glyph lines, and duplicate +Enter/Esc text is hidden while keyboard menu glyphs are active. + +[menu_button_glyphs.c](../../port/linux/game/menu_button_glyphs.c) owns this +optional presentation. [menu_button_widgets.inl](../../port/linux/game/menu_button_widgets.inl) +supplies `menu_functions_glyph_offset`, moving recognized legend groups and their +mouse targets together. The MCC-owned `mcc_pause_key_button` +and `mcc_pause_key_offset` expose only owned widget semantics and layout; foreign +tags are rejected and teardown invalidates their handles. No map identity list +or loader changes are needed. + +The widget hooks run before drawing loses the parent/child context. Generic +text-state readback and scoped scaling let the feature center smaller lettering +and restore formatting, indentation and transforms after each draw. These small +engine interfaces are necessary because feature modules cannot read private +renderer state. Modern, stock PC and gameplay controller glyphs share each +artwork placeholder: the high-resolution registry accepts one texture per asset. +The existing HUD teardown owns those caches; MCC bindings acquired after a menu +draw retain their release callback. Modern footer sizing stays unchanged. + +Menu navigation uses its fixed controls (arrows, Enter, Esc and Tab). Gameplay +icons use the current bindings from Controls Setup, including mouse buttons and +wheel directions. The primary valid binding is shown; a valid secondary binding +is used if the primary is unbound. An action with neither shows `Unbound`. +For example, changing Action from E to F makes a semantic pickup/tutorial prompt +show F on the next frame. Changing Jump does not relabel menu Select. + +## Reading order and ownership 1. [keyboard_prompts.c](../../port/linux/src/keyboard_prompts.c), `keyboard_prompt_pad`, `keyboard_prompt_keys`, `keyboard_prompt_touch` and - `keyboard_prompt_enabled`: physical activity and setting policy. Keyboard - ownership follows XInput port zero, independent of viewport order. Another - player's controller cannot take its keyboard prompts. Android starts with - touch presentation; touch returns to native icons. A manual choice is global. + `keyboard_prompt_enabled`: + physical input activity and the manual/automatic policy. Keyboard ownership + follows XInput port zero. Android starts with touch presentation; touch + activity retains native HUD icons, including after a controller disconnect. + Other local players' controller activity cannot + steal that keyboard's prompts. A manual choice is global and stays fixed. 2. [xinput_sdl.c](../../port/linux/src/xinput_sdl.c), `XInputGetState` and - `halo_keyboard_binding_label`: observe physical input before remapping/merging, - then read the existing binding cache without consuming input or changing it. - Labels use the existing `halo_input_shown_name` layout policy: physical bindings, - ASCII/Latin-1 display labels, and Android's existing US-name fallback. Full - Unicode labels and translated special-key names are outside this change. + `halo_keyboard_binding_label`: observes input before controller remapping or + keyboard/touch merging and reads the existing binding cache. It does not + consume input, change controls or introduce another binding table. 3. [keyboard_glyphs.c](../../port/linux/game/keyboard_glyphs.c), - `keyboard_hud_prompt`, `keyboard_hud_inline` and `keyboard_glyph_draw`: resolve - semantic actions and map each viewport to its input port, measure visible text, - and draw the label. The scoreboard helper replaces only the identified hint's - known BACK or PC `%s` token; surrounding wording and unknown wording survive. + `keyboard_hud_prompt`, `keyboard_hud_inline` and `keyboard_glyph_draw`: + semantic action resolution, viewport-to-port mapping, actual visible font + bounds, label padding, and fractional positioning. Color and text offsets + are restored after drawing. The score-hint helper only receives the identified + scoreboard hint and replaces its known BACK or PC `%s` token, preserving + surrounding wording. Unrecognized wording stays native. 4. [keyboard_glyph_art.c](../../port/linux/game/keyboard_glyph_art.c): original - geometric shapes rasterized at 128 pixels with 4-by-4 coverage samples per texel. - Three horizontal slices preserve rounded ends on wide labels. The thirteen-entry - cache is bounded to 832 KiB of CPU pixels plus GPU copies. Allocation failure - falls back to text. `keyboard_glyphs_dispose` releases it through the existing - [HUD teardown](../../port/linux/game/hud_hires_tags.c), including when High-Res - HUD is off. Activity state owns no map pointers and can persist between maps. -5. [controller_button_menu.inl](../../port/linux/game/controller_button_menu.inl) - uses pending opt-in and detection values for its read-only Keyboard row. Save, - Cancel and Defaults use the existing settings flow. [port_settings.py](../../tools/port_settings.py) - generates the stock screens; no frontend module is required. - -The [HUD message hook](../../source/interface/hud_messaging.c) must precede -controller translation, where the original semantic action would otherwise be -lost. The [inline hook](../../source/interface/ui_widget.c) runs only for HUD and -scoreboard callers. A separate opt-in menu hook replaces recognized face-button -legends and inline tokens when PC menus are selected. The -[score hint hook](../../source/game/game_engine.c) preserves the hint's identity -before it becomes ordinary text. [Text rendering](../../source/rasterizer/rasterizer_text.c) -adds visible-ink measurement and scoped fractional positioning: existing logical -font bounds include padding, so they cannot accurately center the keycap labels. -These helpers leave ordinary drawing unchanged when unused. Each shared source -addition is marked `port:`; prompt-specific policy and layout live in the modules. - -Supported semantic actions include Action, Grenade, Fire, Flashlight, Jump, -Melee, weapon/grenade switching, Crouch, Zoom, Accept/Back, Move, Look, -Start and Scoreboard. Ambiguous literal controller buttons and authored custom -icons stay native. This does not add prompts, reinterpret Action as Reload, -change Xbox/Custom Edition loading, or change bindings, packets or simulation. -The network version is therefore unchanged. - -## PC-menu legends - -[menu_button_glyphs.c](../../port/linux/game/menu_button_glyphs.c) keeps the -existing click targets and fixed menu controls. A uses Enter, B uses Esc, X uses -Del and Y uses Tab. Keyboard caps extend left from the original icon -slot to fit readable names while retaining the following label position. Inline -tokens reserve their full cap width. Known bottom legend groups expand from -right to left by each later keycap's extra width. Compact pause footers instead -retain eight units between CANCEL and SELECT, expand the accept group to the -right, and balance the added width around the original center. This leaves room -for both keycaps inside the narrow campaign and multiplayer panels. Their compact -16-by-20 slots draw key names at 85% size with four units of padding per side -and a complete, full-height outline. Other menus and gameplay retain the imported -GulchCE dimensions. Click targets -move with their labels. The optional offset hook runs before target -registration; tag definitions and saved state are unchanged. The join screen suppresses duplicate plain -Enter/Esc hints in keyboard-glyph mode, retaining the independent Space-to-join -hint and temporary notices. `menu_button_glyph_join_draw` measures both localized -text runs plus the selected glyph, centering the complete line within its PC -player panel. The context adapter offers only the identified PC join widget; -Xbox menu selection and unrelated text retain their original layout. Gameplay rebindings do not change -these meanings. Other icons, custom HUD entries, ordinary OK/Cancel text buttons -and the Xbox menu selection retain their existing drawing. Partially clipped -widget slots fall back to native rendering. - -`menu_button_glyph_draw` receives the widget's already-established button identity -and controller port. `menu_button_glyph_inline` handles literal face-button tokens. -These hooks are necessary because a feature module cannot intercept native bitmap -or inline draws through existing interfaces. The menu module owns selection and -layout; the source hooks only offer the existing draw to it. - -MCC pause definitions remain owned by [mcc_pause.c](../../port/linux/game/mcc_pause.c). -`mcc_pause_key_button` identifies only its own footer icons; `mcc_pause_key_offset` -reads those owned child bounds to apply the compact keyboard layout. The context -adapter calls these only in PC keyboard mode. MCC controller drawing, map tags, -Xbox menu selection and disabled-feature behavior are unchanged. The bitmap hook -is needed because MCC's generated key items do not have legacy button-tag names; -foreign handles and handles from disposed/rebuilt menus are rejected. - -Controller artwork shares the existing gameplay caches through -`controller_glyph_bitmap` and `hud_hires_button_bitmap`: the high-resolution -registry permits only one placeholder per asset, so a separate menu cache would -invalidate gameplay textures. Original cache allocation, failure and teardown -behavior is retained. No new map-loading state is introduced. - -The generic `draw_string_get_format` and `draw_string_get_indents` read back -private renderer state so the menu adapter can restore its caller after selecting -the small UI font. Existing setters alone cannot restore unknown formatting. -Both gameplay and menu keycaps use the imported `keyboard_glyph_draw` and -`keyboard_glyph_art.c` directly, including GulchCE's blue menu outline, rounded -geometry and font-based dimensions. `keyboard_glyph_draw` retains the original -12-unit horizontal padding; `keyboard_glyph_draw_compact` uses eight with smaller -lettering only for compact menu slots. Both restore the caller's indentation, -and scoped text scaling restores the caller's transform. The OpenCE adapter -positions caps and measures space for the surrounding legend. Keyboard menu artwork works with High-Res HUD off. - -## Provenance and checks - -Adapted from [GulchCE](https://github.com/chestahh/GulchCE), commits -`e4bef11d9d870fac808953ce63ed258298eb3586` and -`a0cebafba3da2b74bfaf0b54df80360087c9af3d`, under AGPL-3.0-or-later. -The artwork is original procedural geometry with the active project font. -The GulchCE mock-up was a visual reference; none of its generated pixels ship. -This extraction excludes the modern frontend. OpenCE testing now includes MCC -support; its generated pause keys use the MCC-owned adapters described above. - -[test_keyboard_glyphs.py](../../tools/test_keyboard_glyphs.py) exercises production -policy, semantic resolution, live labels, secondary/unbound bindings, custom-icon -fallback, ink metrics, padding, opacity, allocation failures and repeated cleanup. -[test_menu_button_glyphs.py](../../tools/test_menu_button_glyphs.py) exercises -PC-only gating, complete-line centering, keycap spacing, original menu palette, -legacy/controller families, formatting restoration and failure fallbacks. -[test_mcc_keyboard_glyphs.py](../../tools/test_mcc_keyboard_glyphs.py) runs the -complete MCC pause builder and checks footer identities, group spacing and stale -handles across disposal/rebuild. -[test_controller_buttons.py](../../tools/test_controller_buttons.py) covers pending -opt-in/detection settings, family transitions, manual Keyboard, focus recovery, -and generated screens. A mocked layout lookup verifies binding-reader delegation; -it is not physical international-keyboard validation. Runtime visual checks and -platform results are recorded in the contribution commit; automated tests alone -do not establish hardware or complete gameplay compatibility. + procedural shapes rasterized at 128 pixels with 4-by-4 coverage samples per + texel. Three horizontal slices preserve rounded ends on wide keys. The bounded + thirteen-entry cache occupies at most 832 KiB of CPU pixels plus GPU copies; + `keyboard_glyphs_dispose` releases it at the existing map-unload boundary. + Failed allocations fall back to the label; no map bitmap is replaced. +5. [frontend_prompts.c](../../port/linux/game/frontend_prompts.c) supplies the + fixed menu actions. [port_settings.py](../../tools/port_settings.py) and + [frontend_menu.py](../../tools/frontend_menu.py) generate the preference rows; + they use existing pending-settings Save/Cancel/Defaults behavior. The detected + Keyboard row has no setting spinner, so it cannot overwrite a preference. + +The geometry is original code, with the project's active font. The approved +AI-generated mock-up is a visual reference only; none of its pixels are shipped. +No font or bitmap is extracted from a commercial map for the new artwork. + +## Necessary shared hooks and preserved paths + +The icon hook in [hud_messaging.c](../../source/interface/hud_messaging.c) +runs before controller translation loses an icon's semantic action. A feature +module called only by the final bitmap renderer cannot recover that information. +The HUD-only inline hook in [ui_widget.c](../../source/interface/ui_widget.c) +handles the same vocabulary in HUD/scoreboard strings. Widget/menu callers use +their original icon renderer unless Stock Menu Glyphs is enabled. The identified score-hint callback in +[game_engine.c](../../source/game/game_engine.c) preserves its semantic context +before it becomes ordinary text. + +[rasterizer_text.c](../../source/rasterizer/rasterizer_text.c) exposes visible +ink bounds using the actual high-resolution glyph metrics (or native pixel ink), +and a scoped fractional text offset. The old font-tag bounds include padding and +cannot center high-resolution lettering. These generic helpers change no +ordinary text drawing when unused; all prompt-specific layout stays in the +feature modules. Every shared source addition carries a `port:` comment. + +Semantic Action, Grenade, Fire, Flashlight, Jump, Melee, weapon/grenade switching, +Crouch, Zoom, Accept/Back, Move and Look are supported, plus Start/Scoreboard. +Ambiguous literal A/B/X/Y/trigger/stick icons and custom map icons stay native; +they cannot safely be inferred to mean a particular remapped action. The feature +does not create new gameplay prompts or reinterpret Action as keyboard Reload. +Xbox/CE loaders and MCC adapters remain separate. Existing starting menus, +pause-menu layouts, native server browsers and map-family paths are preserved. + +[touch_input.c](../../port/linux/src/touch_input.c) reports finger and overlay +activity to the prompt module. These small hooks are necessary because only the +touch reader sees that physical input before it becomes an emulated gamepad. +They change no touch bindings, gesture handling or input consumption. Touch +returns to its native prompts; fresh keyboard/mouse input restores keycaps. + +Physical activity can persist across map changes; it owns no map references. +Artwork cannot persist past map teardown. Binding labels are looked up afresh +through the existing configuration-generation cache. The feature does not +change packets, input mapping or simulation, so no network version change is needed. + +## Checks + +[test_keyboard_glyphs.py](../../tools/test_keyboard_glyphs.py) compiles production +policy, action resolution, layout and artwork code. It covers manual forcing, +automatic activity edges, Android/touch defaults, disconnects, split-screen +ownership, live label changes, secondary/unbound bindings, custom-icon fallback, ink centering, padding, alpha, +supersampled coverage, cache failures and repeated cleanup. The existing frontend +binding test checks the shared binding reader and keyboard-layout labels. +The footer regression executes the production selection and draw dispatch with +both High-Res HUD values: when enabled, detected or forced Keyboard draws all +seven keycaps and controller input draws four navigation icons. With it off, +all artwork is suppressed. Touch keeps its own text in either case. +Menu tests cover read-only detection, pending manual choices and focus recovery. + +The original glyph implementation's runtime observations, platform build results +and limits are recorded in the Phase 7 validation section of [menu_redesign.md](menu_redesign.md). + +The automatic-detection simplification was checked against testing base +`b09a96012`: 411 focused input, menu, Xbox/CE/MCC HUD and web-build checks passed, +with one Windows socket-harness skip. The original policy and footer both fail +the new keyboard expectations. Seven additional config-writer harness cases +could not compile on Windows because their POSIX `pthread.h` was unavailable; +the touch gesture executable passed using the Windows CRT instead of `-lm`. + +The portable Windows release build passed with PGO and LTO off. The web build +passed after substituting local Python equivalents for its POSIX copy and SDL +preparation commands. All four affected Android translation units compiled; +the complete Android target remains blocked by POSIX shell preparation steps +on this Windows host. These local build adaptations are not repository changes. + +Before the High-Res HUD gate was restored, hidden Windows captures verified the modern Interface page and keycap footer +at 640x480 with automatic selection, at 854x480 with manual Keyboard, and with +High-Res HUD off. A forced Xbox style retained controller icons. Legacy submenu +visibility and pending choices were checked by the compiled menu harness; its +hidden visual opener returned to the main menu, so that run is not visual +validation of the submenu. Physical controllers, Android touch hardware and +gameplay map-family transitions were not exercised in these runtime checks. + +The GulchCE integration was checked with 448 focused glyph, frontend, MCC pause, +HUD and web-build tests passing and one platform skip. The MCC pause harness +also exercises allocation failures, borrowed resources, teardown and its bound +texture negative control. Windows portable release built with PGO/LTO off; +changed translation units compiled for Android and web. Full local targets +remain limited by Windows-host staging; CI validates complete platform builds. + +Hidden Windows captures cover PC multiplayer/campaign, Custom Edition and MCC +pause footers; keyboard, PlayStation and native/off presentation; and modern +Interface at 640x480 and 854x480. With High-Res HUD off, saved glyph choices stay +hidden in Interface, modern prompts use plain text, and the PC pause footer +retains native buttons. These checks do not cover physical controller hardware, +Android hardware, full campaign completion or cross-machine play. diff --git a/docs/reading/loading_presentation.md b/docs/reading/loading_presentation.md new file mode 100644 index 0000000000..9fb204e115 --- /dev/null +++ b/docs/reading/loading_presentation.md @@ -0,0 +1,78 @@ +# Widescreen loading and the Xbox chant + +`display.widescreen_loading` (Video > Graphics > Widescreen Loading) is +on by default. Xbox, Custom Edition and MCC use the original loading effect: +the installation's 320x240 picture, the 128x16 sweep mask, the original +feedback blur and glow trails, progress wobble and fade. Widescreen changes +only the horizontal framing. It neither crops the artwork nor introduces +replacement art, cubic filtering, a new sweep shader or a different glow. +The complete 4:3 composition expands horizontally to fill the screen. + +An existing saved `false` preference still takes precedence over the default; +enable the setting in Video > Graphics to adopt it. Off keeps the central +4:3 presentation. The Xbox chant plays with either framing. + +## Reading order + +1. [progress_bar.c](../../source/interface/progress_bar.c): + `progress_bar_begin` starts a presentation session, then + `progress_bar_load_loading_texture` reads `maps/loading.tga` through the + established cache path. `progress_bar_render` runs the stock renderer in + both modes. Only the projection's horizontal scale differs: widescreen + uses the full viewport; off retains the original central 640 columns. + The original mask, samplers, blending, `draw_fade_layer` and + `draw_initial_layer` remain responsible for every visual effect. +2. [loading_widescreen.c](../../port/linux/src/loading_widescreen.c): + `loading_widescreen_begin` reads the setting once per loading session. + `loading_widescreen_active` supplies that same decision to drawing and + capture. `loading_widescreen_end` clears it on completion, failure or + shutdown. There are no owned textures, shaders or map pointers. +3. [d3d8_gl.c](../../port/linux/src/d3d8_gl.c): `front_buffer_take` + copies the completed loading frame back into the original 640x480 + feedback texture. During widescreen loading it copies the full width; + otherwise it keeps the existing central capture. The next loading frame + blurs and fades this image exactly as before. Capture still happens at + `BlockUntilVerticalBlank`, before any download overlay is drawn. +4. [game.c](../../source/game/game.c): the ordinary Xbox and Custom Edition + loading path calls the shared progress interface around map loading. + [mcc_loading.c](../../port/linux/game/mcc_loading.c) owns MCC's conversion + progress and calls that same interface. Its guards, stages and session + ownership are unchanged. It never draws a normal game frame against + partially converted tags just to update the loading screen. + +For example, at 1920x1080 the stock effect occupies the whole target when +widescreen is on. Its completed frame is reduced to the existing 640x480 +feedback image, which the following frame draws over the same whole target. +With widescreen off, both drawing and capture use the central 1440x1080 +region. At 4:3 the two modes have the same framing and effects. + +## Integration and isolation + +Drawing and feedback capture must agree on framing: widening only the +projection would feed a cropped middle section back into the next frame, +changing the trail. These two small integration points are necessary because +the projection lives in the game's progress renderer and front-buffer +capture is private to the device. Feature state remains in its own module. +No map loader, map-family boundary, texture import, network message or +simulation value changes. MCC uses the shared presentation service without +routing Xbox or Custom Edition data through MCC modules. + +The chant's original four voices and volume envelopes remain in the progress +renderer. `progress_bar_end` stops them on success or failure without waiting +for a normal frame. See [maps and resources](maps_and_resources.md) for the +audio implementation and its validation limits. + +## Checks + +`tools/test_loading_widescreen.py` records calls made by the actual stock +renderer and device feedback-capture function. Across 4:3, 16:9 and ultrawide +widths it checks that only the projection changes: mask/blur shader use, +fade, progress, color and chant volumes agree. It also checks matching +capture bounds, session reset and the disabled path. The former tests for +the removed custom shader are replaced by these stock-effect checks. + +`tools/test_mcc_loading.py` checks MCC controller guards, viewport and +success/failure lifetime. `tools/test_loading_chant.py` checks the mixer and +voice lifetime. These recording tests do not prove visual output or full +map compatibility: inspect native captures and transitions as well, and +report actual Android/web build and runtime limits separately. diff --git a/docs/reading/maps_and_resources.md b/docs/reading/maps_and_resources.md index 9da28ef6a4..52c64f4160 100644 --- a/docs/reading/maps_and_resources.md +++ b/docs/reading/maps_and_resources.md @@ -1,33 +1,388 @@ -# MCC maps, resources and sharing +# From a map name to loaded resources -Selecting `mcc_maps\\package\\mission` identifies an MCC level; it does not -select an Xbox campaign index. Xbox `maps`, CE `custom_maps` and MCC `mcc_maps` -have separate readers, resource roots and loading state. +Selecting a map identifies content; it does not yet create a running world. +This chapter follows the loading boundary, using an MCC package level as +the concrete example while keeping the Xbox and Custom Edition paths distinct. +Read [startup](startup_and_loop.md) for the caller and the [glossary](glossary.md) +for tags, BSPs, resources and relocation. ## Reading route -1. [mcc_maps.c](https://github.com/chestahh/GulchCE/blob/1131d624b5c4e1f6e4d12174c4929452acf65285/port/linux/game/mcc_maps.c): `mcc_maps_scan` and - `mcc_map_browser_open` build the installed catalog and folder selection. -2. [cache_files.c](../../source/cache/cache_files.c): `scenario_tags_load` - dispatches by map identity; `scenario_tags_unload` releases that family's state. -3. [mcc_cache.c](https://github.com/chestahh/GulchCE/blob/1131d624b5c4e1f6e4d12174c4929452acf65285/port/linux/game/mcc_cache.c): `mcc_cache_tags_load` and - `mcc_cache_tags_unload` own conversion, publication and failed-load cleanup. -4. [mcc_cache_format.c](https://github.com/chestahh/GulchCE/blob/1131d624b5c4e1f6e4d12174c4929452acf65285/port/linux/game/mcc_cache_format.c) and - [mcc_resources.c](https://github.com/chestahh/GulchCE/blob/1131d624b5c4e1f6e4d12174c4929452acf65285/port/linux/game/mcc_resources.c) read bounded cache - structures and resolve the selected package's required resources. -5. [mcc_tag_validate.c](https://github.com/chestahh/GulchCE/blob/1131d624b5c4e1f6e4d12174c4929452acf65285/port/linux/game/mcc_tag_validate.c) validates the - converted graph through an independently owned context. Shared validator - callbacks dispatch only while that context owns the request. -6. [mcc_identity.c](https://github.com/chestahh/GulchCE/blob/1131d624b5c4e1f6e4d12174c4929452acf65285/port/linux/game/mcc_identity.c): - `mcc_identity_prepare_host`, `mcc_identity_host_settings` and - `mcc_identity_refusal` connect package content to admission and diagnostics. - -For example, a local `mcc_maps/example/a10.map` remains an MCC package level -when its internal scenario is also named a10. It cannot replace Xbox a10 or -CE `custom_maps/a10`. Matching content digests, not display labels or Workshop -IDs alone, establish which files a host and joiner share. An identity mismatch -does not establish which copy is newer. Host preparation, disconnect and map -unload clear the relevant cached identity and converted resources. +| Order | Source and names to find | What to follow | +| --- | --- | --- | +| 1 | [game.c](../../source/game/game.c): `game_load`; [scenario.c](../../source/scenario/scenario.c): `scenario_load`, `scenario_unload` | A game option becoming a scenario and world. | +| 2 | [cache_files.c](../../source/cache/cache_files.c): `scenario_tags_load`, `scenario_tags_unload` | Dispatch to the selected map family's loader. | +| 3 | [custom_edition_cache.c](../../port/linux/game/custom_edition_cache.c), [cache_file_formats.c](../../port/linux/game/cache_file_formats.c) | CE runtime integration and bounded file parsing. | +| 4 | [mcc_maps.c](../../port/linux/game/mcc_maps.c), [mcc_package.c](../../port/linux/game/mcc_package.c) | MCC discovery, names and package paths. | +| 5 | [mcc_cache.c](../../port/linux/game/mcc_cache.c): `mcc_cache_tags_load`, `mcc_cache_tags_unload`; [mcc_cache_format.c](../../port/linux/game/mcc_cache_format.c) | MCC I/O, conversion lifetime and format validation. | +| 6 | [mcc_resources.c](../../port/linux/game/mcc_resources.c), [mcc_identity.c](../../port/linux/game/mcc_identity.c) | Required resources and admitted content identity. | + +## Namespaces select different implementations + +| Family | Example identity | Data location and implementation | +| --- | --- | --- | +| Xbox | `levels\a10\a10` | Xbox data in `maps`; the engine's cache path. | +| Custom Edition | `custom_maps\example` | CE data in `custom_maps`; the separate CE parser and conversion path. | +| MCC | `mcc_maps\solar_flare\m0` | MCC data in `mcc_maps`, optionally within a package; MCC-owned readers, conversion and resources. | + +These names prevent an MCC level whose internal scenario name resembles +Xbox A10 from replacing that Xbox level. `scenario_tags_load` checks the +requested namespace and returns through the selected loader's path. A +failed CE or MCC load is not an invitation to try a stock map with the +same basename. + +The CE reader is standalone C with fixed-width types and bounds-checked +little-endian reads. The host reporting tool and tests use the same parser +as the game. MCC has its own parser and conversion modules; a shared runtime +tag shape does not imply a shared on-disk format or resource owner. + +For CE bitmap admission, read `custom_edition_bitmaps_verify` and +`custom_edition_bitmap_raw_2d` in +[custom_edition_bitmaps.c](../../port/linux/game/custom_edition_bitmaps.c). +A synthetic single-level DXT1 texture of 200 by 112 pixels needs 11,200 +bytes of compressed blocks. Its sides cannot be represented by the Xbox +descriptor's power-of-two fields. The narrow CE-owned branch in +`texture_cache_initialize_hardware_format` in +[xbox_texture_cache.c](../../source/cache/xbox_texture_cache.c) records its +exact dimensions in the Size word; `xgpu_texture_describe` in +[xbox_textures.c](../../port/linux/src/xbox_textures.c) keeps compressed +textures addressed with normalized coordinates. These shared additions are +necessary because the existing cache constructs and decodes the hardware +header outside the CE module. Admission and layout selection remain CE-owned. + +`custom_edition_cache_contains` checks the loaded tag allocation rather than +just a global CE setting. The loader publishes that allocation after successful +conversion and clears it on unload, so unrelated resources and later Xbox +sessions cannot inherit this exception. The MCC guard preserves its independent +texture bridge. See the [bitmap restrictions](../custom_edition_caches.md) +and [synthetic regression checks](../../tools/test_ce_npot_bitmaps.py). + +## Workshop identity in join refusals + +For MCC join refusals, also follow `mcc_identity_prepare_host`, +`mcc_identity_host_settings` and `mcc_identity_refusal` in +[`mcc_identity.c`](../../port/linux/game/mcc_identity.c), then the sidecar reader +and bounded record helpers in [`mcc_workshop.c`](../../port/linux/game/mcc_workshop.c). +A package named `2899609719`, or a descriptive package with that id in +`workshop_id.txt`, can identify its Workshop item to a joiner. An older local +copy of that item may lack the requested level; item presence is therefore +checked independently of level names. An unidentified same-name level is not +evidence that the item is installed. SHA-256 and level matching remain +authoritative even when ids differ. Metadata is cached with host preparation +and cleared on disconnect; changing a sidecar during a session requires fresh +host preparation after disconnect. Identity checks do not require Steam. +See [installation and messages](../mcc_maps.md#installation-and-menus) and the +[MCC wire contract](../../port/linux/NETCODE.md#gulchce-network-agreement). +Focused checks are `test_mcc_workshop.py`, `test_mcc_identity.py` and +`test_mcc_protocol.py` under [`tools`](../../tools/). + +Desktop discovery is separately enabled by `game.workshop_maps`. Follow +`steam_workshop_scan` in [steam_workshop.c](../../port/linux/src/steam_workshop.c) +from library manifests to installed map records, then `mcc_maps_scan` and +`mcc_map_browser_open` in [mcc_maps.c](../../port/linux/game/mcc_maps.c). +The `libraries` function checks `paths.steam` first, then Windows Steam registry +installations and standard folders. `steam_workshop_windows_roots` in +[win32_steam_workshop.c](../../port/windows/src/win32_steam_workshop.c) reads the +current-user path and both machine-wide registry views without changing them. For example, +an installation registered at `C:\Steam` is found with `paths.steam` empty; +its `libraryfolders.vdf` adds libraries on other drives. Missing or invalid +registry values leave the existing fallback discovery available. Android and +web keep discovery disabled and do not call Windows APIs. +On Linux, `linux_roots` checks the Steam launch environment and XDG data location +before the home-folder fallbacks, including Debian, Flatpak and Snap. `linux_root` +rejects relative, control-character and oversized paths rather than truncating +them. For example, `XDG_DATA_HOME=/mnt/data/player` adds +`/mnt/data/player/Steam`; the existing Steam symlinks can point elsewhere, and +library manifests add other drives. Manual `paths.steam` stays first. Tests +exercise root bounds on all hosts and native filesystem/symlink discovery on +Linux; these checks do not establish gameplay or sandbox access permissions. +For example, a Workshop item becomes `mcc_maps\2899609719\pat_beavercreek`; +the MCC-only branch in `platform_translate_path` resolves it in place unless a +local package already owns that folder. A rescan retries an exact host identity +before searching aliases. Xbox and CE roots retain their own resolution. + +For resource discovery, follow `steam_workshop_resource_path` in +[steam_workshop.c](../../port/linux/src/steam_workshop.c), called only inside the +MCC branch of [xbox_files.c](../../port/linux/src/xbox_files.c)'s virtual path +resolver. This small shared-file-service hook is necessary because the resource +reader opens virtual paths through `fopen`; MCC map conversion does not own host +file translation. Xbox and CE resolution is unchanged. + +For example, `mcc_maps/12345/bitmaps.map` first respects a local package, then +its Workshop item's beside-level resource, then that item's `halo1/maps` file. +If a required type is absent, `mcc_package_resource_open` retains the explicit +MCC-root fallback; `mcc_resources_select` then checks the two shared sets. +Missing local shared files can resolve to the installed MCC game through the +same Steam libraries. A package may supply custom textures while its sounds +come from a validated shared set. A present invalid package file is refused, +not replaced. See [resource precedence](../mcc_maps.md#subscribed-steam-workshop-items). + +The resolver stores no selected resource or open stream. Existing MCC runtime +ownership in `mcc_resources_dispose` handles failed loads and unloading; changing +maps causes fresh selection. Content hashes cover the selected bytes, so moving +identical resources between supported locations does not change network identity. +The synthetic path and resource-reader tests establish discovery and admission +rules; runtime loading and map-family transitions require separate checks. + +Within the selected file, `mcc_resource_read` finds a unique member or group by +name and validates the requested range. Directory entries need no offset sort: +overlapping ranges do not imply ownership, and duplicate names remain ambiguous +regardless of entry order. CRC and SHA identities cover the original file bytes, +including its directory, rather than this private in-memory metadata. + +`game.mcc_collections` optionally groups installed items using the fixed table in +[workshop_collections.c](../../port/linux/src/workshop_collections.c). +An imported package's `workshop_id.txt` also supplies its group without Steam. +Folder selections store their kind and collection number as well as their name, +so a package named `PRO EDITION` remains distinct from that collection. Browser +storage allows each map to belong to every supported group. Discovery and +grouping both default off; reopen the map list after changing settings. +See [Workshop installation](../mcc_maps.md#subscribed-steam-workshop-items). +The asset-free regressions in `test_steam_workshop.py` and `test_mcc_maps.py` +check these paths, bounds, selection restoration and disabled settings; they +do not establish gameplay compatibility for every discovered map. + +## MCC sharing policy + +Read [`mcc_share_rules.h`](../../port/linux/game/mcc_share_rules.h), then +`mcc_share_decide` in [`mcc_share_rules.c`](../../port/linux/game/mcc_share_rules.c). +The policy accepts eligible local and Workshop packages under the same checks. +It requires host opt-in, portable package/level names, a known gameplay +fingerprint and a host-established custom-content classification. Loose maps, +`_shared`, known stock content and unknown classification remain refused. +Workshop IDs identify a source; they do not establish permission or content identity. + +The classification provider is the host's own `mcc_share.txt`, parsed by +[`mcc_share_list.c`](../../port/linux/game/mcc_share_list.c): one line contains +`<64 hexadecimal digits> `. The digest covers the map and its used +resources, independent of installation name. Required JSON has a separate +identity. A matching list entry is the host's explicit approval of those +content bytes, not a signature from the maker or a substitute for receiver +validation. A missing maker or an unlisted digest blocks the offer. + +[`mcc_share_package.c`](../../port/linux/game/mcc_share_package.c) owns file +selection. `mcc_share_package_build` obtains the actual selected dependencies +through `mcc_validation_resources` in +[`mcc_validation.inl`](../../port/linux/game/mcc_validation.inl). +That accessor rechecks the same file stamps as admission; it does not repeat +map parsing or hash every resource on each request. The selection comes from +`mcc_resources_check_paths` in +[`mcc_resource_check.inl`](../../port/linux/game/mcc_resource_check.inl), after +`mcc_resources_select` validated the map's external references. +A self-contained map sends no unrelated resource siblings. A used package +resource follows the platform's resolved path, including Workshop `halo1/maps` +fallbacks. A required root/shared resource refuses the offer with its path in +the host log; it is never silently copied as package content. An invalid +present override fails validation rather than falling back to another file. + +## MCC package sharing between machines + +Native sharing and its validation are recorded in +[Milestone 13](../mcc_refactor_validation.md#milestone-13-implementation-evidence). +Browser playability and asynchronous admission have separate Milestone 14 +checks; compilation or successful publication alone does not establish play. + +For example, a host plays `mcc_maps\solar_flare\m0` and a joiner has another +version in a local folder of that name. The host enables `network.mcc_map_share` +and lists its gameplay fingerprint and maker; the client enables the existing +`network.map_download` preference. The original local package stays intact. + +1. Read `mcc_identity_accept` and `mcc_identity_update` in + [`mcc_identity.c`](../../port/linux/game/mcc_identity.c). Matching installed + gameplay and required-metadata identities need no transfer. Uncached checks + run asynchronously after the host acknowledges a bounded validation hold + in [`mcc_admission.c`](../../port/linux/game/mcc_admission.c), using the + authenticated transport adapter in + [`mcc_admission_game.c`](../../port/linux/game/mcc_admission_game.c). + This hold is independent of download permissions. Otherwise + `mcc_share_missing` in [`mcc_share.c`](../../port/linux/game/mcc_share.c) + requests an offer. Client downloads off means no request: show manual + installation and, when a valid Workshop ID exists, the Workshop page. +2. `mcc_share_package_build` applies the local list/policy and builds a bounded + offer containing the current map, used package resources, recognized JSON, + referenced supported PNG previews and permitted attribution text. A local + map-only folder needs no JSON or thumbnail. `mcc_share_metadata_plan` in + [`mcc_share_metadata.c`](../../port/linux/src/mcc_share_metadata.c) includes + campaign and mission JSON upfront, but only the current mission's map and + selected previews. Later mission binaries are requested when needed. +3. [`mcc_share_session.c`](../../port/linux/game/mcc_share_session.c) hashes + files and sends paged manifests on the host's reliable connection. The + client enters `MCC_SHARE_CLIENT_WAITING`: it has an offer, not permission + to create files. The frame update opens the generated prompt. Accepting + through `mcc_share_game_prompt_action` starts the download only while the + same session, map, gameplay digest and metadata digest remain current. + The prompt shows size and maker. Host sharing off or client downloads off + removes the download action; a Workshop page and cancellation remain + available when applicable. Differing content is not labelled older/newer. + When downloading cannot proceed, `mcc_share_game_update` leaves the session + and presents manual guidance at the main menu. Its copied text and Workshop + origin survive only that deliberate disconnect, so the host's playerless + timeout cannot replace the guidance. Dismissal, a new session or leaving the + menu clears it; no offline prompt can accept a download. +4. [`mcc_share_stage.c`](../../port/linux/game/mcc_share_stage.c) exclusively + creates an owned `mcc_staging/dl_` directory on native platforms. + The browser uses a hidden journaled destination instead, as explained in + [browser storage](browser_imports.md). Files arrive in order + through `mcc_share_stage_write`, with size and SHA-256 checks. Required JSON + is reparsed and its reference allowlist rebuilt; invalid optional PNGs are + discarded, while invalid required metadata refuses installation. The + gameplay check owns its worker and readers. `mcc_package_stage_redirect` + is scoped to opening/selecting files and taking snapshots; the worker + never reads through mutable global routing. Verification continues to + service networking under the existing bounded transfer lifetime. +5. `mcc_share_stage_install` publishes the whole directory without replacing an + existing destination under `mcc_maps/dl_`. The identity layer checks + that specific installed snapshot before successful `DONE` and joining. + SHA/CRC/resource-selection facts are promoted only while all candidate + file stamps match, avoiding another full hash. Cancel/failure + deletes only owned staging entries. Native filesystem checks reject links, + reparse points, devices and unsafe paths; they do not sandbox an adversarial + process already running with the same user's filesystem authority. + +The host is the only sender. CE sharing keeps its own messages and behavior; +MCC borrows only the necessary lobby hold, per-frame and cache-admission hooks. +Disconnects, changed identities, disabled downloads and host preparation +revision changes cancel stale work. No stage or consent carries into Xbox/CE. +Successful completion also crosses a small admission boundary: the client +resolves the installed identity before sending `DONE` and adding its player. +`mcc_share_host_finished` grants a maximum 15-second grace period for that +following request. The existing timeout hook includes this grace, while +`mcc_share_game_machine_needs_map` reports unfinished transfers or installed-file +validation, so completed checks release held players. Admission or +session/content changes clear the grace; replayed completion cannot renew it. +The wire limits and protocol versions are in +[NETCODE.md](../../port/linux/NETCODE.md#mcc-package-sharing). + +Before a pregame host starts synchronous map loading, +`mcc_ui_network_download_pending` in +[`mcc_ui_network.inl`](../../port/linux/game/mcc_ui_network.inl) checks joined +machines for active MCC offers, transfers, installed-file checks or +completion-to-admission grace. +The existing MCC start check holds loading while these are active. The update +keeps an already running, unpaused countdown at least three seconds from +expiry, allowing normal networking to service the joiners. It preserves longer, +stopped and manually paused countdowns. Once download/admission activity ends, +the ordinary exact-map readiness checks govern starting. This prevents a +blocking host load from starving an admitted downloader; it does not provide +network service for a new request arriving after that load has already begun. + +Managed-copy receipt, storage-use display and removal controls use +[`mcc_share_storage.c`](../../port/linux/game/mcc_share_storage.c) and +[`mcc_share_menu.c`](../../port/linux/game/mcc_share_menu.c). +The ownership contract permits removal only of verified recorded files, keeps +unrelated additions and saves, and requires the caller to exclude the active +session package. Native UI inspection verified the corrected main-menu gate, +confirmation caption and removal while preserving the source snapshot. +Browser persistence and publication use the independent OPFS transaction +boundary described in [browser imports](browser_imports.md). Runtime results +and remaining gates are recorded separately under Milestone 14. + +The game harness compiles the real adapter, planner, session and stage over +synthetic files. Engine/UI/identity and metadata-parser calls are stubs there; +`test_mcc_resources.py`, `test_mcc_validation.py` and metadata tests separately +exercise their production helpers. Neither category proves real-map network +play or a complete campaign transition. See the +[PR review and draft response](../mcc_refactor_validation.md#pr-95-review-and-draft-contributor-response). + +## Explicit MCC campaigns and Android imports + +Enable `game.mcc_campaigns` to use an installed campaign's metadata. Start with +[`mcc_manifest.c`](../../port/linux/src/mcc_manifest.c): `mcc_manifest_load` +reads the complete mission list, rejects ambiguous names and keeps missing +binary entries in the authored sequence. `mcc_manifest_for_level` selects the +metadata belonging to the actual resolved package, so an overridden Steam item +cannot supply unrelated local campaign metadata. The parser shares the existing +Workshop mission-text reader; it does not require Steam on Android or web. + +Next read `mcc_maps_campaign_metadata` and `mcc_maps_next_mission` in +[`mcc_maps.c`](../../port/linux/game/mcc_maps.c). The catalog stores mission +order, display titles and explicit next-level identities; package selections +remain stable across sorting. For example, a manifest listing `z10` followed by +`a10` displays and advances in that order. An absent `a10` stops progression; +an unrelated map with a similar name is never substituted. Settings changes +invalidate the catalog when it is next used. + +The small completion hook in `main_won_map_private` delegates to +[`mcc_main_campaign_won`](../../port/linux/game/mcc_main.c), guarded by a loaded +MCC campaign and the setting. Solo games retain difficulty and queue the next +map. Network clients do not choose; hosts use the existing co-op lobby/settings +transition. `mcc_ui_network_campaign_won` records a one-use request for that +server, round and next mission, returning the host to the ready lobby with +the intended selection. A different selection or session teardown cancels +the request; ordinary same-selection identity validation does not. The download +barrier described above lets missing clients acquire the next mission before +the host loads it. No progression cursor survives unload: the current level +and its own package identify the next mission. Standalone and final levels return to +the menu or lobby. Xbox and CE still use their existing completion code. + +Managed downloads retain this package boundary. If mission `z10` is in one +`dl_` folder and `a10` in another, matching campaign JSON or Workshop +IDs do not authorize joining those folders: the metadata has no per-mission +binary digests. `mcc_maps_next_mission` refuses a missing within-package next +mission, even if another snapshot contains that leaf name. Each downloaded +mission remains individually selectable. Connected clients instead follow +the host's next-mission settings and exact gameplay/metadata identities; a +complete Workshop/manual installation is needed for offline or rehosted +campaign progression. `test_downloaded_campaign_does_not_splice_other_snapshots` +in [`test_mcc_maps.py`](../../tools/test_mcc_maps.py) exercises this catalog +boundary with one or multiple candidates sharing the same ordered metadata +and Workshop ID; it does not test receipt validation or a network transition. + +For Android, follow +[`MccImportActivity`](../../port/android/app/src/main/java/com/halo/decomp/MccImportActivity.java) +from the document picker into +[`MccPackageImporter.prepare`](../../port/android/app/src/main/java/com/halo/decomp/MccPackageImporter.java). +ZIP and document-tree streams enter the same bounded staging path. The importer +flattens only the package's maps, retains metadata, and records its Workshop ID. +The pure Java [`MccJson`](../../port/android/app/src/main/java/com/halo/decomp/MccJson.java) +reader retains numeric IDs exactly. `Prepared.install` publishes a complete +directory, with replacement rollback and next-import recovery after an +interruption. It never installs into `maps`, `custom_maps` or saved-game folders. + +Checks cover authored order, malformed/duplicate/missing metadata, local +precedence, full-length titles, completion ownership, import traversal, +cancellation, replacement recovery and legacy/save preservation. Native Ruby +checks establish parsing of ten real mission records and forced A10-to-A30 and +final-mission transitions; they are not a complete campaign playthrough. +The Java importer tests do not substitute for Android document-provider and +device testing. See [Android importing](../../port/android/README.md#importing-mcc-packages) +and [campaign constraints](../mcc_maps.md#installation-and-menus). + +## Follow an MCC package level + +Consider selecting `mcc_maps\solar_flare\m0`. This is an illustrative +installed package identity, not a map loaded during this documentation work. +The catalog and package code retain the package path and filename. Map +category comes from checked content rather than an assumption that a +particular filename must be campaign or multiplayer. + +`game_load` reaches `scenario_load`, which calls `scenario_tags_load`. +The MCC branch calls `mcc_cache_tags_load`. That loader first unloads any +previous MCC cache state, resolves the local package binding and opens the +source for reading. It reads and validates the tag data through the MCC +format layer before exposing converted data to the engine. + +The next steps select required resources, check their checksum and admitted +identity, reserve MCC tag storage, preserve the canonical scenario identity +for saved games, and prepare tags, scripts, geometry, audio and bitmaps. +Converted tags must pass validation. Only after successful preparation does +the loader mark the MCC cache loaded and begin campaign state. + +```mermaid +flowchart TD + A[Selected level identity] --> B[Map-family dispatch] + B --> C[MCC file and bounded format reader] + C --> D[Resource selection and identity checks] + D --> E[MCC-owned conversion and validation] + E --> F[Expose runtime tags and load scenario] + C --> G[Failure cleanup] + D --> G + E --> G +``` + +This is a summary of stages, not the complete list of operations or failure +sites. The `problem` string and `failed` label in `mcc_cache_tags_load` make +the exact failure path especially readable. ## MCC model strips @@ -63,41 +418,608 @@ needs rendering and map-family transitions. ## MCC loading feedback -[mcc_loading.c](https://github.com/chestahh/GulchCE/blob/1131d624b5c4e1f6e4d12174c4929452acf65285/port/linux/game/mcc_loading.c) reports bounded conversion -stages through the existing loading-screen service. It does not run simulation -or bypass network readiness. Long conversions update progress between bounded -units of work; a single blocking operation can still pause the display. -The Xbox installation supplies the original loading art. Missing art does not -establish a stalled converter. [Format evidence](../mcc_maps.md#loading-feedback) -records failure diagnostics and the observed limits. +[mcc_loading.c](../../port/linux/game/mcc_loading.c) owns a local progress +session around `game_load`'s `scenario_load` call. This small shared hook is +needed because successful tag conversion is followed by menu integration and +initial BSP setup; completing the screen inside `mcc_cache_tags_load` would +report success too early. Non-MCC loads, headless runs and an already-owned +native progress screen do not start MCC visual feedback. Every normal success +or failure return pairs `mcc_loading_begin` with `mcc_loading_end`; MCC network +work reporting has its own lifetime even when visual feedback is unavailable. -## MCC package sharing between machines +`mcc_cache_tags_load` advances the stage after resources, tags, scripts, +geometry, audio, textures and validation. Converter loops report completed +items; bounded inner audio/texture and resource-read steps call +`mcc_loading_pulse` to refresh even while one item is still in progress. +Stage weights describe work, not seconds remaining. Progress never goes +backward, and only a successful scenario load reports completion. + +Drawing uses the inherited `progress_bar_begin`, `progress_bar_display` and +`progress_bar_end` interface and direct device presentation. It deliberately +does not render normal game frames, widgets or run the game/network loop: +those paths can access partially converted tags. Presentation pumps existing +platform window events. Refreshes are separated by at least 50 milliseconds; +blocking file reads, allocation and individual codec operations can still +pause the animation. Before drawing, the controller selects the backbuffer +with no depth surface, so an earlier scene's offscreen/depth targets cannot +be paired with the loading effect. The next normal game window installs its +own targets and viewport. + +The effect uses the installation's `maps/loading.tga`, imported by OpenCE from +the Xbox disc image; MCC packages do not supply or replace it. Missing art has +the existing loading renderer's black-texture behavior. Catalog browsing reads +only headers and descriptions. Menu probes do not begin a loading screen. +`mcc_resources_inspect` can still pulse an enclosing actual map load. +Presentation never signals readiness: peers still finish their own conversions +and send the existing loaded acknowledgment. Conversion work separately feeds +the [bounded MCC loading contract](../../port/linux/NETCODE.md#mcc-package-sharing), +including on headless hosts, without dispatching incoming messages during a load. + +The optional [widescreen presentation](loading_presentation.md) scales this +same stock effect horizontally to fill the render target, retaining the +original mask, feedback blur and glow trails. MCC retains the controller +and ownership described above. + +The shared loading effect also plays the Xbox's embedded monk chant from +[`progress_bar.c`](../../source/interface/progress_bar.c). Its four looping +Xbox ADPCM voices use the buffer API in +[`dsound_sdl.c`](../../port/linux/src/dsound_sdl.c): `SetBufferData` decodes an +owned copy, `SetPitch` selects each voice's pitch, and `progress_bar_render` +swells their volumes with progress. Xbox pitch is absolute: zero means 48 kHz, +with 4096 units per octave, as described in the public +[APU research](https://xboxdevwiki.net/APU#Pitch_calculation). +`mix_buffers` adds them to the front +speakers under the master and effects volumes, without the map's reverb. +`progress_bar_end` stops them on success or failure; a quick subsequent +`progress_bar_begin` restarts retained voices, and `progress_bar_dispose` +releases them if shutdown precedes normal frame cleanup. MCC uses this +existing presentation service without changing its map or resource ownership. +`tools/test_loading_chant.py` checks the actual mixer, buffer controls and +loading audio lifetime without maps or a sound device; it does not establish +device playback quality or campaign compatibility. + +Host selection uses [mcc_validation.inl](../../port/linux/game/mcc_validation.inl), +included by `mcc_cache.c`, and the existing pregame update in +[mcc_ui_network.inl](../../port/linux/game/mcc_ui_network.inl). A click schedules +validation; pregame updates open and check the package, then a worker hashes its +complete map and required resources through +[mcc_resource_check.inl](../../port/linux/game/mcc_resource_check.inl). Only private readers and hash state run on +the worker; engine diagnostics and result publication stay on the main thread. +The worker checks cancellation between slices of at most 4 MiB, with elapsed +time checked after each 16 KiB to end a slice at 2 ms. If worker creation fails, +pregame advances one slice per update. Opening and dependency parsing are a +separate step, so this is not a hard time bound on all I/O. Cancellation joins +the worker before closing readers. No validation runs during gameplay. +Host readiness polls only completed results, and settings cannot be +sent until the checksum and content identity are ready. + +The four-entry successful-result cache retains checksums and SHA-256 digests so +selection, local admission and readiness do not repeatedly read unchanged files. Its +[mcc_precache_snapshot](../../port/linux/game/mcc_precache.c) includes the map, +package and root overrides, and both shared resource sets, even absent files. +A cache miss or changed metadata requires validation again; failed metadata +queries prevent reuse, and changes during validation refuse the result. Catalog +rescans can retain this checksum because every use checks those inputs again. +Reselection, unload and disconnect cancel unfinished work and close its readers. +Disconnect still clears session identities; successful file facts survive it, +with their metadata rechecked on every use. Remote admission and actual loading +still check the content identity; actual loading fingerprints the opened content. +The older single-checksum cache remains for synchronous remote admission. This is +not a persistent cache or proof against edits that preserve all recorded metadata. +The first host check takes time while the menu remains responsive. Starting a +game remains gated on validation and the existing peer-readiness checks. An +early start request waits in pregame; pending validation is not a connection error. +Admission explanations pass through this same cache: a successful reuse clears +stale caller text, while a failed fresh check returns its resource explanation. +An install changing during validation gets its own refusal message. +[test_mcc_validation.py](../../tools/test_mcc_validation.py) exercises reuse, +changed inputs, failed validation, identity checks and checksum disagreement. + +[test_mcc_loading.py](../../tools/test_mcc_loading.py) exercises the controller's +ownership, stage ordering, rate limit, timer wrap, re-entry, failed device +queries and cleanup. Converter tools use a headless display stub while retaining +their real conversion and validation code. Runtime checks must additionally +cover visible output, failed/repeated loads, co-op and Xbox/CE transitions. + +## Resources are dependencies, not interchangeable files + +A level can contain its own data or reference external bitmaps and sounds. +For MCC, a package-local resource takes priority, followed by an explicit +legacy resource at the MCC root. Where neither exists, compatible installed +shared sets are considered. Selection is independent for each resource type. + +An explicit but damaged override fails; it is not silently replaced with +another package's data. Required references must match a complete resource +file; partial matches are not assembled from several files. Multiple +different complete matches require the intended resource to be made +unambiguous. Self-contained levels need no external resource selection. +See [MCC maps](../mcc_maps.md) for the exact installation and matching rules. + +No MCC resource lookup should wander into Xbox `maps` or CE `custom_maps`. +Likewise, the availability of a resource file called `bitmaps.map` says +nothing by itself about its format or suitability. Network content identity +must account for the map and required resources, not just a convenient +folder name. Peers can bind equivalent MCC content under different local +package names. + +When MCC is selected at host creation, `mcc_cache_checksum` in +[mcc_cache.c](../../port/linux/game/mcc_cache.c) also calls +`mcc_identity_prepare_host` in [mcc_identity.c](../../port/linux/game/mcc_identity.c) +before the lobby opens. Fast network setup can +instead open a temporary lobby and request MCC while its local client is +still joining. `mcc_ui_network_defer_map` in +[mcc_ui_network.inl](../../port/linux/game/mcc_ui_network.inl) retains that selection until local +admission completes; `mcc_ui_network_update_map` then applies it through the +ordinary map-change function. A pending selection prevents starting the +temporary map, and legacy selections or teardown cancel it. These paths keep +package work outside the local client's five-second joining state. +`mcc_identity_host_settings` reuses that digest only while the map and all +resource-candidate file stamps match, including absent overrides. Changed +files require fresh validation; disconnect clears the cache. Local admission +also reuses the prepared hash when its canonical path, complete snapshot and +all digest bytes match, avoiding another scan of the host's unchanged package +while remote clients wait. Other machines compute their own fingerprints; +actual loading always rehashes the opened content. This timing change is +MCC-owned and changes neither Xbox/CE paths nor network timeouts or packet +formats. It does not eliminate arbitrary storage or main-thread stalls. + +For an authored MCC campaign follow-on, `mcc_main_campaign_won` in +[mcc_main.c](../../port/linux/game/mcc_main.c) passes the manifest-selected +mission to `mcc_ui_network_campaign_won` in +[mcc_ui_network.inl](../../port/linux/game/mcc_ui_network.inl). After the +ordinary reliable round transition succeeds, an MCC-owned token identifies +the server, new round and selected mission. The existing pregame UI hook +consumes it after the current map unloads and opens the ready lobby instead +of the multiplayer map picker. Its countdown waits for package validation, +active downloads and ordinary precache readiness. A same-name checksum +update during validation preserves the token; another selection, session +disposal or mismatched round invalidates it. Campaign end and a missing next +mission retain their existing postgame/error handling without automatically +replaying the last mission. `test_mcc_ui_network.py` exercises the real UI +dispatcher, including the former paused-map-picker failure; +`test_mcc_lifecycle.py` covers the campaign completion adapter. + +Before any MCC network mission starts, `mcc_ui_network_download_pending` +holds an already-running countdown at no less than three seconds while a +joined machine has an active offer, download or the bounded post-install +admission grace. Normal countdown messages keep those clients connected. +The direct-start guard enforces the same barrier. A stopped/paused timer is +left alone, and a longer countdown is never shortened. Once the download +and admission finish, the normal precache acknowledgment gates the player's +readiness. This is needed because MCC conversion runs synchronously: starting +the host while another client waits for content can otherwise leave that +client without messages long enough to lose its connection. Xbox and CE +retain their existing start policy; in-game late joining is unchanged. +This protects downloads already admitted before loading, not a new request +the host has not received when synchronous conversion begins. + +Once loading begins, [mcc_load_network.c](../../port/linux/game/mcc_load_network.c) +and its [game adapter](../../port/linux/game/mcc_load_network_game.c) distinguish +ongoing conversion work from a silent client. MCC conversion checkpoints send +a small reliable progress message at most every five seconds, using only the +existing transport write service. They never dispatch incoming messages or +run game frames while tags are incomplete, and reporting works without a +renderer. The exact advertised content identity and round bind each message. + +The ordinary host loading deadline remains sixty seconds after the first +machine finishes. Only an MCC peer with advancing work can remain beyond it: +its last advance must be under thirty seconds old, and the round has a fixed +four-minute loading budget. Replayed progress cannot extend either limit. +The budget allows twice the roughly two-minute browser conversion observed +in testing; it does not promise support for arbitrarily slow clients. Only +the existing loaded acknowledgment completes loading. The host also reports +its own conversion work, keeping faster clients connected through their +ordinary prestart transport timeout; clients enforce the same absolute budget. +Disconnect, another map/round and departed peers retire the corresponding +state. Xbox and CE retain their existing loading deadlines. +`test_mcc_load_network.py` exercises the real adapter and server deadline, +including the former removal of a progressing client, expiry and stale input. + +## Loading and unloading must agree about ownership + +The MCC runtime owns its source stream, tag window, converted geometry, +audio, bitmap resources and associated state. `mcc_cache_tags_unload` +clears precache and feature state, disposes dependent resources, releases +tag storage, closes the stream and clears the runtime structure. The load +failure path frees its temporary raw buffer and calls the same unload path. + +On Windows, `mcc_window_initialize` in +[mcc_memory.c](../../port/linux/src/mcc_memory.c) reserves the usual 64 MiB +tag window at `0x50000000` before the first SDL call. The Windows linker +delay-loads SDL without changing its ASLR protection. This ordering must +precede CE's constructor, which calls SDL while reading settings; waiting +until renderer startup is too late. `mcc_memory_log_startup` reports any +saved failure after `windows_startup` connects the port log. Unloading an +MCC map decommits its pages but retains the reservation for the next load. +[test_windows_mcc_startup.py](../../tools/test_windows_mcc_startup.py) checks +loader ordering and deferred logging with a disposable DLL deliberately +linked inside that window; [test_mcc_memory.py](../../tools/test_mcc_memory.py) +checks ownership, conflicting allocations and reloads. These tests do not +establish compatibility with arbitrary injected modules. + +In `scenario_tags_load`, the shared engine installs the returned tag table +only after a loader succeeds and performs the relevant menu/HUD/mod wiring. +Additional integration can still fail and require teardown. Thus "the +format parser succeeded" is earlier than "the map is ready to play". + +BSP loading is another lifecycle within a scenario. A campaign can switch +its active spatial region without choosing a new menu map. BSP-dependent +geometry and collision must be ready before simulation or network corrections +place players there. [Networking](networking.md) explains why that transition +also needs agreement between host and clients. + +## Evidence and compatibility limits + +MCC HUD conversion also owns layout and texture interpretation. In +[`mcc_hud.c`](../../port/linux/game/mcc_hud.c), +`mcc_hud_bitmaps_prepare` converts the canvas while +[`mcc_hud_layout.inl`](../../port/linux/game/mcc_hud_layout.inl) recognizes +known stock layouts for the native safe margins. First read +`mcc_hud_plan_prepare` in +[`mcc_hud_ownership.inl`](../../port/linux/game/mcc_hud_ownership.inl): it plans +from pristine data, marks aliased roots for a single conversion, and snapshots mutable block +consumers before publishing their pointers. For example, two overlay definitions +sharing one authored placement must each receive the original offset and scale; +the first conversion must not become the second one's input. Pointer-free +items can be interned outside the HUD tree, so each consumer receives a copy. +The later validator still rejects malformed pointer-bearing overlaps. +Planning records are temporary; copies live in the MCC tag arena and follow +its unload and failed-load cleanup. + +Layout recognition reads each distinct root once, and conversion applies the +chosen marker alongside normalization. Bitmap names are validated but do not +select safe margins. The retained structural profiles are a conservative +compatibility exception: anchor and scale fields alone do not establish the +author's intended safe frame. Their evidence and removal condition are in +[the MCC format notes](../mcc_maps.md). Replacement ammo/grenade +artwork can still use a stock panel layout; genuinely custom placements keep +the wider MCC frame. `mcc_hud_weapon_frame_begin` follows the outermost +populated parent layout, and `mcc_hud_weapon_frame_end` clears that choice. +These functions +in [`mcc_hud_draw.c`](../../port/linux/game/mcc_hud_draw.c) scope that choice +to a complete weapon/parent draw, preventing inherited components from using +different margins. Stock gameplay message offsets also use native margins; +High-Res controller glyph dimensions and text spacing match the native HUD. + +Chapter titles share [`cinematic_render`](../../source/cutscene/cinematics.c), +which resolves the authored/default rectangle in the 640-column layout. Its +widescreen translation uses the text's left edge, right edge or center according +to its justification, preserving that anchor's relative screen position and the +box's size. For example, Xbox `b30` authors a right-aligned title ending at 597; +on an 852-column screen it ends at 794. Translating by the box center instead +pulled it inward to 695 ([issue #86](https://github.com/chestahh/GulchCE/issues/86)). +At 640 columns the translation is zero for every alignment. The same positioning +applies to Custom Edition and MCC without changing tags or retaining state. + +MCC cutscene titles then have a separate drawing adjustment: +`mcc_hud_title_bounds` in +[`mcc_hud_draw.c`](../../port/linux/game/mcc_hud_draw.c) expands non-wrapping +lines toward the screen edges while preserving their left, right or center +anchor and vertical bounds. Warthog Rally authors centered titles in a +160-unit box even for longer trophy messages; the native clipping rectangle +would hide their endings. Wrapping titles retain their authored rectangle. +Only the temporary draw rectangle changes, so unloading MCC leaves no title +layout state behind and Xbox/Custom Edition keep the native path. See the +[title regression tests](../../tools/harness/tests/test_cinematic_titles.py) +and [MCC evidence](../mcc_maps.md#cutscene-title-layout). + +For example, Descent's curved meters use RGB as shape coverage and alpha as +fill order. `mcc_meter_usage` and `mcc_channels` in +[`mcc_bitmaps.c`](../../port/linux/game/mcc_bitmaps.c) create the appropriate +owned clone; `mcc_texture_bridge_meter` in +[`mcc_texture_bridge.c`](../../port/linux/src/mcc_texture_bridge.c) selects +filtered edges and sharp fill cutoffs through existing renderer interfaces. +The descriptor belongs to that clone and is released on MCC texture teardown. +Xbox-order meters and the Xbox/CE loaders do not take this conversion path. +See [MCC conversion details](../mcc_maps.md) for the layout evidence and tests. + +`mcc_bitmap_valid_texture` in `mcc_bitmaps.c` finds the exact owned descriptor +and checks its handle, byte range, format and required storage. Both +`mcc_bitmaps_valid` and `mcc_bitmaps_pixels` use that result; the latter returns +the already validated allocation without searching the texture table again. +Copied descriptors and changed ranges cannot borrow another texture's pixels. +The lookup retains no state across calls or map unloads. + +During conversion, `mcc_bitmaps_prepare` gives each bitmap tag its own bounded +virtual byte stream. Original descriptors are appended as complete tag groups; +`mcc_bitmap_specialize` appends each clone as another complete group with a +fresh runtime handle. Reusing a clone appends nothing. Preparation therefore +keeps a local stream cursor, resets it when that handle changes, and advances +it only after `mcc_texture_prepare` succeeds. The resource handle can be shared +by clones and must not be used for this boundary. Per-texture, per-tag and +aggregate storage limits still apply; no cursor survives preparation or unload. + +The Xbox cache/scenario machinery is inherited. CE conversion is a port +addition, documented in [Custom Edition caches](../custom_edition_caches.md). +MCC conversion, package identity and its compatibility boundaries are +GulchCE additions. OpenSauce requirements remain unsupported in the CE path; +the presence of an extra header alone is different from requiring its features. + +[test_cache_file_formats.py](../../tools/test_cache_file_formats.py) checks +valid and malformed CE inputs, resource dependencies and conversion cases. +[test_mcc_cache_format.py](../../tools/test_mcc_cache_format.py) checks the +independent MCC reader, including invalid ranges. +[test_mcc_checkpoint.py](../../tools/test_mcc_checkpoint.py) addresses another +boundary: saved state and native hooks. Actual validation and its limits are +recorded in the [refactor evidence](../mcc_refactor_validation.md). + +See the [MCC implementation reference](../mcc_maps.md) for its boundaries. +Recognition, conversion, loading, reaching gameplay, crossing a +BSP boundary and finishing a campaign are separate claims. A new loader +change needs malformed inputs, failed-load cleanup and Xbox/CE/MCC transitions +checked as well as a successful load of its target map. + +## Load refusal messages + +The two loaders own their explanations separately: +[`custom_edition_errors.c`](../../port/linux/game/custom_edition_errors.c) and +[`mcc_errors.c`](../../port/linux/game/mcc_errors.c) translate parser statuses +and bound the displayed map names and reasons. They do not relax validation. +For example, an MCC level without a matching external sound resource names +`sounds.map` and directs the player to install its resources beside the level. +It never recommends installing CE resources for an MCC level. +The small MCC dialog abbreviates long package/level names at the middle and +summarizes long reasons with an explicit `See debug.txt` pointer. Full resource +paths, script names and terminal conversion reasons remain in the log. + +Read `mcc_resources_probe_explain` in +[`mcc_resources.c`](../../port/linux/game/mcc_resources.c), then +`mcc_cache_present` and `mcc_cache_tags_load` in +[`mcc_cache.c`](../../port/linux/game/mcc_cache.c). Admission probes return +caller-owned text. Actual loading keeps the first detailed terminal failure +in `mcc_runtime.failure`, and copies it into the existing menu queue before +unloading clears the runtime. An unsuccessful shared-resource candidate does +not become a failure when a later candidate succeeds. The menu queue retains +the first error, so generic recovery text cannot replace a specific refusal. +MCC's existing menu return and network abort ordering remain intact. + +The MCC resource CRC and save-state CRCs use the port's existing prefixed +zlib through [`zlib_prefixed.h`](../../port/third_party/zlib/zlib_prefixed.h). +`mcc_resources_checksum` and the bounded checker in +[`mcc_resource_check.inl`](../../port/linux/game/mcc_resource_check.inl) start +with the map's stored checksum, then feed each selected resource's type byte, +complete file bytes and `0xff` terminator, in bitmap-then-sound order. zlib's +CRC interface applies the complements itself. Only the final published zero +becomes one, preserving the engine's reserved zero identity. The separate +SHA-256 content fingerprint retains its length/type framing and map bytes. +`mcc_checkpoint_checksum` and `mcc_threads_checksum` start at zero for each +saved block. The serialized layouts and the Xbox/CE CRC paths are unchanged. + +For CE, follow `custom_edition_cache_present`, `custom_edition_cache_tags_load`, +`custom_edition_cache_load_error` and `custom_edition_cache_display_error` in +[`custom_edition_cache.c`](../../port/linux/game/custom_edition_cache.c). +The last load's bounded reason survives resource cleanup until the fatal +caller consumes it; another load resets it and successful loading clears it. +Catalog probes cannot overwrite it. Precache failures still enter the fatal +media screen, and later load failures retain their existing error priority. + +The small hooks in the cache, main and network callers are necessary because +those callers own the original failure presentation. The CE module cannot +replace that text through a return value alone. `display_error_damaged_media_text` +in [`ui_widget.c`](../../source/interface/ui_widget.c) copies the supplied text +and delegates to the existing fatal screen and loop. Xbox callers retain their +fixed message; MCC keeps its separate deferred-message path. No wire format, +map-family limits or recovery decisions change. + +[`test_map_load_errors.py`](../../tools/test_map_load_errors.py) exercises actual +extracted loader and widget functions with injected failures, including cleanup, +message ownership, first-error retention, successful retries and the unchanged +fatal-loop calls. Resource selection and family lifecycle tests supplement it. +These tests establish control flow, not visual fit or full map compatibility; +those require a real game run with local assets. + +## MCC script and animation compatibility + +[`mcc_scripts_prepare`](../../port/linux/game/mcc_scripts.c) links MCC +script names to native services or MCC-owned adapters. Its private +`mcc_script_resolve` also serves `mcc_script_find`, keeping one name mapping. +Preparation runs before MCC activation and permits native fallback; runtime +lookup retains its loaded-MCC and null-name guards. A recognized alias such as +`player_effect_set_max_vibrate` resolves only its canonical rumble target. If +that target is missing, it must not fall back to a native function under the +original alias. Existing native tables and unsupported-name refusals remain. +`debug_score` gets ordinary map-local long-integer storage, like the existing `developer_mode` +adapter; it does not grant developer access or change multiplayer scores. +[`mcc_campaign.c`](../../port/linux/game/mcc_campaign.c) implements +`players_on_multiplayer_team` by selecting living player units on the requested +player team, including remote players. The team is not the unit's AI allegiance. +These adapters do not add names to the Xbox/Custom Edition function table. + +For MCC `(ai_deselect)`, follow `mcc_script_resolve`, `mcc_script_function` and +`mcc_ai_deselect_evaluate` in +[`mcc_scripts.c`](../../port/linux/game/mcc_scripts.c), then +`ai_scripting_deselect` in [`ai_script.c`](../../source/ai/ai_script.c) and +`ai_debug_select_actor` in [`ai_debug.c`](../../source/ai/ai_debug.c). +The zero-argument adapter invokes the real native selection-clearing service +when AI is initialized; it adds no saved state or new cleanup owner. Loaded-MCC +registry guards and existing unload behavior bound its availability. +`hs_syntax_node_refusal` in [`hs.c`](../../source/hs/hs.c) already validates +MCC definitions separately. Its native map allowlist remains unchanged, +including the refusal of `ai_deselect` and `ai_select` in Xbox/CE maps. + +Quarantine's authored `life_lost_0` is a concrete example: its valid call was +enough to disable the whole cooperative game-over script under native policy. +The MCC adapter applies to any accepted MCC map. This script-admission change +originally required MCC protocol 65 despite adding no message fields; it left +the then-current OpenCE 41 contract unchanged. Use the +[current agreement](../../port/linux/NETCODE.md#gulchce-network-agreement) for present builds. [`test_mcc_ai_deselect.py`](../../tools/harness/tests/test_mcc_ai_deselect.py) +extracts the actual native operation, adapter and policy functions, including +deliberate-fault controls. [`test_mcc_scripts.py`](../../tools/test_mcc_scripts.py) +checks name resolution, zero-argument validation and inactive registry guards. +Runtime observations and their limits belong to the +[refactor validation record](../mcc_refactor_validation.md). + +`sound_set_music_gain` multiplies the map's music volume by a finite value in +0 to 1, in addition to the player's volume setting. Only a local game or the host +can change it. Follow `mcc_campaign_mix_gain`, the campaign snapshot functions, +[`mcc_network.c`](../../port/linux/game/mcc_network.c) and +[`mcc_checkpoint.c`](../../port/linux/game/mcc_checkpoint.c): the value follows +host snapshots and checkpoints and resets when the map ends. Snapshot version 5 +adds the gain; older supported snapshots restore it to 1. This required MCC +protocol 56; the later thread-storage extension uses 57. The verified OpenCE +protocol is unchanged. + +For scripted inventory replacement, follow the MCC-only `player_add_equipment` +registration in [`mcc_scripts.c`](../../port/linux/game/mcc_scripts.c) to +[`mcc_player_add_equipment`](../../port/linux/game/mcc_player.c). A reset removes +the held weapon before calling the existing profile-assignment service. For +example, Meincrap 2 switches by readying a dummy weapon, then replacing it +with a profile's real weapon and fresh dummy. Keeping the old held dummy +prevents the switch from settling. Add-only calls retain existing equipment; +clients wait for the host's object and inventory replication. The adapter has +no persistent state, and Xbox/CE retain their original script registration. +See [equipment compatibility](../mcc_maps.md) for evidence and boundaries. + +Halo Kart's NPC steering and pickups run through the same deeply nested `main` +script. Exceeding the native 512-byte stack stopped that script. +[`mcc_script_threads.inl`](../../port/linux/game/mcc_script_threads.inl) +provides bounded 4,096-byte stacks for MCC, retaining the native 256-thread count. +Read `mcc_script_threads_prepare`, `mcc_hs_threads_activate`, and +`mcc_script_threads_dispose` for ownership: loading reserves proven-unused CPU +state space, script initialization selects it, and unloading restores the native +array and original bytes. Xbox/CE stack layouts and capacities are unchanged. +The interpreter needs only array-selection and stack-end hooks; the save system +provides a read-only arena-bounds accessor. + +[`mcc_script_parameters.c`](../../port/linux/game/mcc_script_parameters.c) +retains validated signatures and lexical owners, not live argument values. +`mcc_parameters_prepare` clears publication counts before preparing metadata; +failed preparation and cache unload clear them again. Live arguments, recursion +and sleeping calls remain in each saved stack through +[`mcc_script_runtime.inl`](../../port/linux/game/mcc_script_runtime.inl). +`mcc_hs_release_thread` releases parameter-held object lists on cancellation, +thread deletion and overflow; normal returns use `mcc_hs_release_arguments`. +The [runtime tests](../../tools/test_mcc_parameters.py) cover recursion, sleep, +cancellation and overflow. + +Follow `mcc_checkpoint_capture`, `mcc_script_threads_validate`, and +`mcc_script_threads_restore` for saves and the host's co-op revert image. +Validation checks array and frame bounds before accepting pointers. Old inline-stack checkpoints +can migrate after validation. Only the host runs race scripts and AI in co-op; +the existing object and animation messages carry their effects. Thread stacks +are not transmitted as a new message. This does not permit clients to submit +scripts or authoritative state. Asset-free coverage is in +[`test_mcc_script_threads.py`](../../tools/harness/tests/test_mcc_script_threads.py); +runtime race progress and pickup behavior require the actual maps as well. + +`game_state_image_accept` in +[`game_state.c`](../../source/saved%20games/game_state.c) calls MCC preflight +before copying the saved image over live state. `mcc_checkpoint_units` in +[`mcc_checkpoint.c`](../../port/linux/game/mcc_checkpoint.c) requires a nonzero +object identifier as well as matching salt, unit type and bounded storage. +For example, deleting slot 0 while slot 1 remains live leaves a valid native +array with an unused first slot. A CRC-correct grenade record with handle zero +must still be refused: matching zeroes do not identify a live unit. The +[checkpoint tests](../../tools/test_mcc_checkpoint.py) exercise the real native +lookup and grenade restore, checking refusal before live bytes or names change, +alongside a valid saved-unit control. + +The shared console lifetime fix saves temporary syntax and owned source text +with the threads that use them, then validates and restores them before those +threads resume. It applies to Xbox, CE and MCC without changing authored-map +permissions. The [console checkpoint walkthrough](console_checkpoints.md) +explains ownership, collection, map lifecycle and old-save incompatibility; +actual validation and limits remain in the +[refactor evidence](../mcc_refactor_validation.md). + +Halo Kart also exposes seated passengers attempting to find a danger-avoidance +destination, which the native position selector disallows. Follow +`mcc_seat_blocks_avoidance` in [`mcc_seats.c`](../../port/linux/game/mcc_seats.c) +and the two hooks in [`action_avoid.c`](../../source/ai/action_avoid.c): MCC +passengers cannot start that movement action, and seating ends an active one. +Xbox/CE and movable MCC actors retain their existing path. The focused test is +[`test_mcc_avoidance.py`](../../tools/test_mcc_avoidance.py). + +Firefight Descent's `vehicles\spelican\spelican` animation graph has two +unnamed, unlinked landing-gear node slots. Its associated models retain those +slots and agree on the remaining ordered node names and parent relationships. +`mcc_animation_model_tree` in +[`mcc_tag_validate.c`](../../port/linux/game/mcc_tag_validate.c) can recover +that hierarchy without changing animation or vertex node indices. Associated +models must agree, retained links must be consistent, and the resulting complete +tree still passes the usual cycle and reachability checks. Recovery is logged; +unrelated broken graphs are not automatically accepted. + +Issue #79 adds two narrower recoveries in the same MCC validator. Bot Bootcamp's +cyborg and Arbiter's Demise's Ghost omit child or sibling links; recovery requires +the associated models to agree on ordered names and every retained edge. +`mcc_collision_surface_edges` repairs a misplaced first edge only when the +surface's owned edges form one complete, bounded ring. The original collision +callback then checks the result; the repair never changes geometry or ownership. + +For Extended's dialogue, follow `mcc_audio_prepare`, `mcc_audio_reserve`, +`mcc_audio_read` and `mcc_audio_dispose` in +[`mcc_audio.c`](../../port/linux/game/mcc_audio.c). Empty sounds may have an +unspecified sample rate; a nonempty payload still needs a supported rate. +Converted audio belongs to each full sound-tag handle, so two sounds may use the +same virtual offset without sharing bytes. Each allocation stays below 256 MiB, +with a 1 GiB aggregate budget. The MCC cache passes the existing read's tag handle, +and the MCC validator checks the current tag's range. Failed loads and unloads +free every sound's allocation. This does not change Xbox/CE caches or wire data. + +`breadcrumbs_navpoints_enabled_override` accepts a literal enable because the +MCC breadcrumb service is already available. Reads return true; disabling it or +assigning a computed value is refused. `mcc_spawn_weapons_evaluate` wraps the +existing weapon-spawn service for MCC scripts, only while an MCC campaign owns +state and only on the local game or host. It adds no native function-table entry +or new network message. See [issue #79 evidence and limits](../mcc_maps.md#issue-79-map-compatibility) +for the maps checked and remaining unsupported behavior. + +The public [H1 script reference](https://c20.reclaimers.net/h1/scripting/) +documents the music-gain and team-query interfaces and identifies `debug_score` +as a long that does not affect multiplayer score. The map-local implementation +preserves reads and writes; it does not claim an MCC debug-score display. +Landslide's enabling of Catch, Mythic, Anger and Thunderstorm remains unsupported; +turning those requests into no-ops would change the later rounds' gameplay. + +Focused coverage lives in `test_mcc_campaign.py`, `test_mcc_scripts.py`, +`test_mcc_checkpoint.py`, `test_mcc_effects_gain.py` and +`test_mcc_tag_validation.py` under [`tools`](../../tools/). +The supplied `b30_vs.map` has a version-609 Custom Edition header, so it cannot +establish runtime coverage for the issue's MCC version-13 map. + +For issue #89, follow `mcc_script_find` and `mcc_scripts_prepare` in +[`mcc_scripts.c`](../../port/linux/game/mcc_scripts.c), then +`mcc_kill_thread_evaluate` in +[`mcc_script_runtime.inl`](../../port/linux/game/mcc_script_runtime.inl). +Halo RPG's self-termination calls discard the current invocation after releasing +parameter-held object lists; they must not return through the discarded stack. +Thread handles include their allocation identifier, so a stale handle cannot +cancel a replacement console thread. Existing checkpointed thread storage owns +all remaining state, with no new shared-engine hook. + +Ruined Halo extends `mcc_animation_model_tree` recovery to disconnected chains +with some zeroed parents. Matching associated models must agree on ordered +names and retained parent relationships; complete graphs stay unchanged and the +recovered tree still receives the normal validation. `mcc_particle_type_constants` +also supplies a bounded default for a missing jet orientation constant exposed +by the map's intro effects. + +Mission Z9's model-lighting writes are owned by `mcc_campaign_begin`, +`mcc_campaign_snapshot`, `mcc_campaign_restore` and `mcc_campaign_dispose` in +[`mcc_campaign.c`](../../port/linux/game/mcc_campaign.c). The script-startup entry +in [`mcc_script_threads.inl`](../../port/linux/game/mcc_script_threads.inl) +resets that value on restart. [`mcc_checkpoint.c`](../../port/linux/game/mcc_checkpoint.c) +stores the added value in reserved footer space so existing saved thread +addresses remain stable. MCC protocol 63 carries the larger campaign snapshot; +Xbox/CE keep OpenCE protocol 41. See +[issue #89 evidence and limits](../mcc_maps.md#issue-89-script-extensions-and-animation-recovery) +for the inspected Warthog hierarchy, integer edge policy, runtime coverage and +Mission Z9's lighting state and checkpoint compatibility. + +Continue with [platforms and testing](platforms_and_testing.md), or return +to the [guide](README.md). + + +## Campaign mission kinds + +`mcc_manifest_default_kind` in [mcc_manifest.c](../../port/linux/src/mcc_manifest.c) +accepts the supported `Default` mission kind regardless of ASCII capitalization. +The manifest and menu metadata readers share this rule; Android imports apply +it too. Missing kinds retain the default, while unsupported names and non-string +values remain invalid. A rejected campaign now logs its package and reason during +Workshop discovery instead of disappearing without a diagnostic. -[mcc_share.c](https://github.com/chestahh/GulchCE/blob/1131d624b5c4e1f6e4d12174c4929452acf65285/port/linux/game/mcc_share.c) owns the host/client transfer; -[mcc_share_package.c](https://github.com/chestahh/GulchCE/blob/1131d624b5c4e1f6e4d12174c4929452acf65285/port/linux/game/mcc_share_package.c) builds a bounded -plan and [mcc_share_session.c](https://github.com/chestahh/GulchCE/blob/1131d624b5c4e1f6e4d12174c4929452acf65285/port/linux/game/mcc_share_session.c) checks -transfer state. [mcc_share_stage.c](https://github.com/chestahh/GulchCE/blob/1131d624b5c4e1f6e4d12174c4929452acf65285/port/linux/game/mcc_share_stage.c) -publishes only verified files. Installed packages and original Workshop files -are preserved; host snapshots have their own receipts and removal ownership. - -Both host sharing and client downloads must be enabled. Otherwise the offer -provides the Workshop route when an item is known. Local map-only folders do -not require invented JSON or thumbnails. Complete packages carry required -metadata and supported previews. A campaign manifest is verified upfront; -each mission and its required resources arrive before that mission starts. -Clients do not seed MCC transfers. CE retains its own sharing implementation. - -The browser uses origin-private storage and transaction recovery instead of -native directory renames. Follow the [browser walkthrough](browser_imports.md) -for locks, delayed responses, publication and restart ownership. Follow -[NETCODE](../../port/linux/NETCODE.md#mcc-package-sharing) for message bounds, -authority and the shared OpenCE 42 agreement. - -## Verification and limits - -The `test_mcc_cache_format`, `test_mcc_resources`, `test_mcc_tag_validation`, -`test_mcc_identity`, `test_mcc_share_*` and lifecycle tests under -[tools](../../tools/) exercise production readers and state machines with -synthetic data. Real package validation also needs rendering, scripts, gameplay, -networking, unload/reload and campaign transitions. A successful conversion is -not a completed playthrough. +Combat Revolved's credits entry uses `default`. Rejecting that single spelling +previously hid all eleven missions. Regression fixtures use unrelated package +names, preserve authored order and original JSON bytes, and retain refusal cases. diff --git a/docs/reading/mcc_level_previews.md b/docs/reading/mcc_level_previews.md index f0717d6fca..c7e6c0a888 100644 --- a/docs/reading/mcc_level_previews.md +++ b/docs/reading/mcc_level_previews.md @@ -1,7 +1,8 @@ # MCC package images in the menus -MCC map and mission panels in the stock OpenCE menu display the image declared -by their installed package, retaining the existing thumbnail rectangles and typography. All MCC images are center-cropped and +MCC map and mission panels display the image declared by their installed +package. Modern, Classic PC, Stock and Xbox-style frontends keep their existing +thumbnail rectangles and typography. All MCC images are center-cropped and resized to fill the same 140 by 114 logical-pixel area as the question-mark placeholder, without stretching. An explicit clip prevents drawing outside that rectangle. Cropping happens while preparing the texture: the native @@ -50,25 +51,25 @@ folder, saved mission identity or network map name is renamed. 1. [menu_functions.c](../../port/linux/game/menu_functions.c): `mcc_map_description_show` and `lobby_map_show` supply MCC display indices. -2. [mcc_manifest.c](https://github.com/chestahh/GulchCE/blob/1131d624b5c4e1f6e4d12174c4929452acf65285/port/linux/src/mcc_manifest.c): +2. [mcc_manifest.c](../../port/linux/src/mcc_manifest.c): `mcc_manifest_package_root` follows the actual existing MCC path mapping. -3. [mcc_menu_metadata.c](https://github.com/chestahh/GulchCE/blob/1131d624b5c4e1f6e4d12174c4929452acf65285/port/linux/src/mcc_menu_metadata.c): +3. [mcc_menu_metadata.c](../../port/linux/src/mcc_menu_metadata.c): `mcc_menu_metadata_load` reads the explicit map list and `mcc_menu_metadata_find` refuses ambiguous basenames. The catalog reads each package/family once per scan for its labels. -4. [mcc_preview_image.c](https://github.com/chestahh/GulchCE/blob/1131d624b5c4e1f6e4d12174c4929452acf65285/port/linux/src/mcc_preview_image.c): +4. [mcc_preview_image.c](../../port/linux/src/mcc_preview_image.c): `mcc_preview_image_load` uses that metadata; `mcc_preview_png` decodes bounded PNG bytes. `mcc_preview_image_free` releases the platform allocation in its allocating module, rather than through the game's debug allocator. -5. [posix_mcc_preview.c](https://github.com/chestahh/GulchCE/blob/1131d624b5c4e1f6e4d12174c4929452acf65285/port/linux/src/posix_mcc_preview.c): +5. [posix_mcc_preview.c](../../port/linux/src/posix_mcc_preview.c): `posix_mcc_preview_read` performs bounded, regular-file reads below the selected root, rejecting relative-path escapes, devices and linked child paths. POSIX uses held directory descriptors; Windows checks reparse points and the opened file's final path. This file runs in the Android host through the generated `posix.h` guest bridge. -6. [mcc_menu_preview.c](https://github.com/chestahh/GulchCE/blob/1131d624b5c4e1f6e4d12174c4929452acf65285/port/linux/game/mcc_menu_preview.c): +6. [mcc_menu_preview.c](../../port/linux/game/mcc_menu_preview.c): `mcc_menu_preview_draw` owns texture caching, centered cropping and clipping. -7. [mcc_menu_text.c](https://github.com/chestahh/GulchCE/blob/1131d624b5c4e1f6e4d12174c4929452acf65285/port/linux/game/mcc_menu_text.c): +7. [mcc_menu_text.c](../../port/linux/game/mcc_menu_text.c): `mcc_menu_text_draw` measures package text in the active font, wraps it at word boundaries and breaks oversized words. It uses the existing small font when necessary and an ellipsis when the fixed panel still cannot fit it. @@ -81,32 +82,53 @@ display index as a frame in the loaded tag and draws text without MCC-aware wrapping. Only MCC indices on the level-picture tag enter the new image path; the original frame is the fallback. Text hooks accept MCC catalog fields and dedicated MCC folder fields. Neither hook repurposes the Xbox/CE providers. - -## Stock campaign and multiplayer flow - -The stock selector offers separate MCC singleplayer and multiplayer categories. -Campaigns require `game.mcc_campaigns = true` (the default). Package folders open -into mission lists; Back leaves the difficulty step, then the package, then the selector. -The host selects a mission and difficulty through the existing hosting flow. -The MCC catalog owns these identities; no MCC mission becomes an Xbox level index. -The same generated menu and callbacks run on native and browser builds. +The Xbox browser adds independently generated wrappers; existing selectors and +their definitions are unchanged. + +## Xbox campaign and multiplayer flow + +With `display.menu_frontend = "xbox"` and `game.mcc_campaigns = true`, the main +menu's selectable **MCC CAMPAIGNS** row, between **CAMPAIGN** and **MULTIPLAYER**, +opens **MCC Campaigns → Choose Profile → Choose Campaign → +Load Level → Choose Difficulty**. Campaign folders and missions use the native +three-card geometry, oversized arrows, fonts, plasma backing and thumbnail size. +Long descriptions stop above the reserved badge row and use an ellipsis when +needed. Long titles wrap within the native title area. +The profile chooser, difficulty descriptions, difficulty artwork, existing +headings and button key are native UI services/art from the player's `ui.map`. +The new MCC Campaigns heading is rendered with the project's OpenCE font. +The main-menu entry uses that same title font at the native 19.5-pixel capital +height, with unselected blue and selected white/glow bitmap states. It is +inserted into the live native list with its 36-pixel row spacing, preserving +the existing choices and their actions. Disabling MCC campaigns leaves the +native list untouched. X no longer opens campaigns from the main menu. +Back first leaves difficulty selection, then the campaign folder, then returns +to profile selection. It never selects a mission by an Xbox level number. + +The native multiplayer map selector gains an X **MCC Maps** prompt. This opens +the separate MCC browser and returns a selected MCC identity to the existing +native gametype flow. The Xbox/CE map selector remains available and unchanged. + +[mcc_xbox_menu.inl](../../port/linux/game/mcc_xbox_menu.inl) owns browser state, +selection and routing. It uses the existing frontend instance-attachment and +session-reset services; no widget pointers survive a screen change. The +input hooks are necessary because generated XML cannot append an entry to the native root or consume +X before its native handlers. [mcc_xbox_menu.py](../../tools/mcc_xbox_menu.py), +called by the frontend generator, owns the additional XML and heading redraw. +Geometry was checked against the Xbox build's `solo_level_select` widget tags +in the local `ui.map`; retail tag contents and images are not shipped. ## MCC completion badges -[mcc_progress.c](https://github.com/chestahh/GulchCE/blob/1131d624b5c4e1f6e4d12174c4929452acf65285/port/linux/game/mcc_progress.c) stores completion in +[mcc_progress.c](../../port/linux/game/mcc_progress.c) stores completion in `mcc_completed.dat` beside each player's native profile. Records identify the full `mcc_maps\\package\\mission` path, so equally named missions in different packages and different profiles do not share awards. Normal, Heroic and Legendary -use the stock selector's existing difficulty indicators. Easy is -recorded but has no indicator, matching the stock selector. Higher difficulty +use the native 44 by 48 completion glyphs at the native card positions. Easy is +recorded but has no card badge, matching the native selector. Higher difficulty does not invent awards for lower difficulties. Existing playthroughs cannot be reconstructed into completion records; awards begin with this version. -`mcc_map_description_show` reads the selected profile and full mission identity. -`mcc_progress_menu_flags` caches one selection for at most one second to avoid -reading the journal every frame; profile or mission changes bypass the timer. -Folder and multiplayer entries show no completion badges. - The existing MCC campaign-win hook records actual completion before advancing or returning to the menu. It follows the existing native authority model: local players on a solo/couch-co-op game or the host receive records; remote clients @@ -139,20 +161,21 @@ network downloads, execute code, or change MCC redistribution/map-sharing policy The decoder was independently implemented against the [PNG specification](https://www.w3.org/TR/png-3/). -[test_mcc_previews.py](https://github.com/chestahh/GulchCE/blob/1db929c5e34101a45f644436e031016b5584c7bf/tools/test_mcc_previews.py) executes the real +[test_mcc_previews.py](../../tools/test_mcc_previews.py) executes the real decoder and file reader with generated assets, including all five PNG filters, malformed files, path/link escapes, metadata fallback and local precedence. -[test_mcc_preview_menu.py](https://github.com/chestahh/GulchCE/blob/1db929c5e34101a45f644436e031016b5584c7bf/tools/test_mcc_preview_menu.py) exercises the +[test_mcc_preview_menu.py](../../tools/test_mcc_preview_menu.py) exercises the real presentation against deterministic font/GPU services, checking bounds, cache eviction/reset, wrapping and unaffected Xbox/CE indices. The -[Android importer tests](https://github.com/chestahh/GulchCE/blob/1db929c5e34101a45f644436e031016b5584c7bf/tools/tests/MccPackageImporterTest.java) verify -that folder and ZIP imports retain metadata and image bytes. The full source archive -ran preview reader checks on Windows and Linux, including Linux -address/undefined-behavior sanitizers. These tests are archived coverage; -they are not part of the focused testing-based contribution. These automated checks do not replace rendered menu inspection or +[Android importer tests](../../tools/tests/MccPackageImporterTest.java) verify +that folder and ZIP imports retain metadata and image bytes. CI runs preview +reader checks on Windows and Linux, including Linux address/undefined-behavior +sanitizers. These automated checks do not replace rendered menu inspection or Android device testing. -[test_mcc_progress.py](https://github.com/chestahh/GulchCE/blob/1db929c5e34101a45f644436e031016b5584c7bf/tools/test_mcc_progress.py) executes journal reads +[test_mcc_xbox_menu.py](../../tools/test_mcc_xbox_menu.py) checks the native +geometry, profile/folder/difficulty/back routes, host handoff and entry guards. +[test_mcc_progress.py](../../tools/test_mcc_progress.py) executes journal reads and writes, profile/mission isolation, duplicate awards, corruption, capacity and profile-rename copying. The existing MCC lifecycle test checks that awards are gated by MCC campaign activation and host/local authority. diff --git a/docs/reading/menu_redesign.md b/docs/reading/menu_redesign.md new file mode 100644 index 0000000000..e86106631b --- /dev/null +++ b/docs/reading/menu_redesign.md @@ -0,0 +1,970 @@ +# Optional modern frontend: Settings, navigation and legacy switching + +This is general feature work. Xbox and Custom Edition implementations stay +in place; MCC continues to own its pause UI. Modern is the default frontend; +an explicitly saved Stock, PC or Xbox choice is preserved. The frontend +does not change map-family selection, networking or simulation. Phases 1–3 established the isolated frontend, widescreen layout and input +prompts. Phase 4 provides the Settings tabs and scrolling subpages. The +starting menu stays unchanged. Phase 5 adds modern Multiplayer and Create Game +submenus. Phase 6 adds modern map and gametype selection, Server Setup, Bots +and lobby views. The Server Browser, LAN browser, Direct Link and their filters +retain their existing definitions and appearance. + +## Existing behavior and migration inventory + +| Area | Existing owner / route | Modern-menu plan | +| --- | --- | --- | +| Main menu, campaign, profiles, multiplayer | `tools/ce_menus.py`, generated `port/assets/menus/ce`, `menu_tags.c`, `menu_functions.c` | Keep the starting menu and profile editors unchanged; the campaign map chooser opts into the Modern layout. The PC multiplayer landing and explicitly listed hosting/lobby roots opt into modern views. | +| Video, audio, mouse, controller, interface and network settings | `tools/port_settings.py`, `port_config.c`; profile values use the profile editor | Reuse this inventory and the existing services across six tabs and eleven subpages. Profile settings use the existing profile editor transaction. | +| Keyboard/mouse remapping | Base-game input/profile bindings plus port Controls Setup | Keep binding ownership. Later prompt lookup resolves an action to its current binding, not a hard-coded key. | +| Controller mapping and glyph families | `controller_remap.c`, `controller_remap_game.c`, `controller_buttons.c`, `xinput_sdl.c`, existing HUD/menu glyph settings | Phase 3 connects action prompts to these services, including per-device automatic detection and preserved manual overrides. | +| Internet/LAN browser, hosting, lobby and co-op | Existing `menu_functions.c` callbacks and network modules | Phase 6 adds hosting/lobby views over these services. All browser views stay native; no transport or protocol change. | +| In-game Xbox/CE pause menus and map UI | `menu_tags_loaded`, `pause_patch`, `pause_campaign_patch`; map-provided resources | Pause roots continue using `display.menus`. Their Settings entry uses the selected frontend. Never rebuild or switch resources in gameplay. | +| MCC pause and Settings integration | `mcc_ui`, `mcc_pause`, `mcc_pause_runtime`, existing `mcc_settings` branch | Keep ownership, guards, profile session and pause-clock rules intact. The trusted generated Settings entry can route to the selected frontend. | +| Changelog, bots, mods and other GulchCE entries | Existing feature modules and generated CE screens | Keep their existing starting-menu routes; bots remain available through Settings and Server Setup, including the modern hosting view. | + +The current reader constructs native widget tags from XML. It is not a web +view or immediate-mode UI. A screen, its focused child and its history are +widget instances; their definitions and bitmap registrations belong to the +loaded map's tag table. Disposing that table beneath an active pause menu +would be unsafe. The prototype therefore switches instances only, at the +main menu, while retaining the frontend's complete tag set until map unload. + +## OpenH1 reference and provenance + +The reference is [OpenH1 at df16d2e](https://github.com/OpenH1/OpenH1/tree/df16d2e56c3b69be46f964f741a23fd2d3b4f57a), +particularly `tools/port_settings.py`, `tools/ce_menus.py`, `menu_tags.c`, +`menu_functions.c`, `menu_files.c` and the widget renderer. Its sectioned +rows and contextual help panel guide this layout. Its full settings and +wide-screen changes span the generator and engine; they are not a single +drop-in theme. The first prototype uses the existing 640-by-480 logical +canvas. Phase 2.5 now extends only the modern layout to widescreen; the +legacy screens keep their established geometry. + +The prototype's code and geometric art are original GulchCE work, not +copied OpenH1 source or assets. No upstream cherry-picks or vendored library +are included. If later phases adapt code, retain its notices and record the +exact upstream revision and licence beside the adaptation. Both projects +declare AGPL, but attribution alone does not fulfill its source/licensing +obligations. Art credits belong in AUTHORS; code provenance does not. + +## Reading route and ownership + +1. [frontend_menu.py](../../tools/frontend_menu.py): `document` and `generate` + own `port/assets/menus/modern` and update the asset manifest. Run + `python tools/frontend_menu.py`; do not edit generated XML or PNGs. +2. [frontend_menu.c](../../port/linux/game/frontend_menu.c): + `frontend_menu_map_loaded`, `frontend_menu_available`, `frontend_menu_root` + own the frontend availability latch and root policy. +3. [frontend_menu_files.inl](../../port/linux/src/frontend_menu_files.inl): + `frontend_menu_files_load` uses the existing parser for a separate cached + frontend set. The ordinary reader excludes `modern/` and remains the + source of Stock Settings when the feature is disabled. +4. [menu_tags.c](../../port/linux/game/menu_tags.c): `menu_tags_loaded` + chooses the frontend set when the active style is enabled, including + gameplay Settings through each family's existing loader. `menu_tags_unloaded` + disposes resources; the active style persists across gameplay map changes. +5. [frontend_menu_runtime.inl](../../port/linux/game/frontend_menu_runtime.inl): + `frontend_menu_can_edit`, `frontend_menu_attach`, `frontend_menu_shortcut`, + `frontend_menu_event` add the Xbox settings links and handle Apply/Cancel. + Gameplay uses paused page roots without main-menu initialization; closing + Settings returns through the existing pause history. +6. [ui_widget.c](../../source/interface/ui_widget.c): + `ui_widget_load_by_name_or_tag` offers the feature an attachment point; + `widget_instance_process_one_event_recursive` offers the guarded shortcut; + `main_screen_shell_load` selects the frontend root after closing widgets. + +The small shared hooks are necessary because feature modules cannot own +the engine's widget creation/event loop or select the initial shell root. +They contain no feature policy and are marked `port:`. Loader registration, +the setting, and callback names are additive. The stock Graphics generator adds only the Menu Style setting; all MCC +modules remain unchanged. No map paths are renamed or redirected. + +## Trying the prototype + +MCC package options use the same setting inventory in each frontend. Modern +Settings > Online > Map Sharing > MCC Packages is a Modern page with its own +help panel, tab navigation and pending Save/Cancel state. Stock and Classic PC +use the generated Network Setup screen; Xbox applies its generated controller +footers to that screen. Steam Discovery is desktop-only in every style. +Campaign and package folders use the existing map selector callbacks through +the Modern map/mission layouts, retaining MCC-owned ordering and identity. +See [campaign discovery and importing](maps_and_resources.md#explicit-mcc-campaigns-and-android-imports). + +Set `display.menu_frontend = "modern"` in the isolated run's `config.toml` +before loading `ui.map`. Modern is now the default; `"off"` preserves the +established Settings presentation. +`HALO_MENU_FRONTEND` provides the usual one-run override. The other enabled +values are `"pc"` and `"xbox"`. `display.menus` still controls the established +pause-menu policy independently. + +For example: open Settings in Modern mode, open Interface, select Xbox under +Menu Style, then OK. The next main-loop +iteration closes the current widget/history and opens the original Xbox +root. Xbox Settings > Video Setup > Graphics exposes Menu Style too; Tab/Y +at an enabled frontend's starting root remains a shortcut to Modern Settings. +Select Modern and OK to return to the unchanged starting menu with modern +submenus enabled. In gameplay, Settings exposes Menu Style but saves it as +a pending preference. `frontend_menu_style` retains the style selected on +departure from the main menu across Xbox, CE and MCC map transitions. The +new preference is adopted only when the main menu loads again; +editing config.toml externally does not promise live reload. + +Choice arrows edit widget-local selections. Changing pages captures pending +selections in feature-owned storage; no config is written. Cancel discards +the pending selections from every page. OK saves changed values across pages +and requests the main-menu transition when already there. In gameplay, OK +and Cancel return to the existing pause menu without changing its resources. +The existing configuration writer is not transactional: if persistence +fails, some values may already have changed in memory. The prototype keeps +the screen open with an error and offers retry; Cancel cannot undo an +earlier failed Apply. Missing frontend definitions fall back to the normal +legacy menu. Crossing between Off and an enabled style requests a fresh +`ui.map` load at `main_menu_load`, after closing the old widgets. Changes +between enabled styles reuse the loaded optional definitions. Neither path +rebuilds tags during a menu callback or during gameplay. + +Modern preserves the starting menu selected by `display.menus`; Classic PC +and Xbox explicitly select their established shell. Modern mode routes the +PC Multiplayer entry to the modern landing screen. The Xbox shell’s native +play routes remain unchanged. All six Settings tabs are functional; their specialized binding +and profile-management editors retain their established presentation. +Phase 3 replaces the temporary Tab/Y caption with device-aware prompts and +the existing controller glyph preferences. Phase 7 adds optional binding-aware +[keyboard/mouse glyphs](keyboard_prompts.md) using that lookup. A later +menu-style setting in a pause screen queues a preference, never switches UI. + +## Phase 5: multiplayer submenus; unchanged starting menu + +The starting screen is deliberately preserved, including its artwork, positions, +Campaign, Profiles, Mods, Changelog and Quit entries. Settings opens Modern +Settings when selected, and the campaign chooser has a Modern presentation. +The Tab/Y shortcut still opens Modern Settings. No modern main +screen or replacement main-screen art is generated. + +Read [frontend_navigation.py](../../tools/frontend_navigation.py), `SCREENS` and +`append`, for the two new screens. Multiplayer groups Server Browser, Local +Network and Join by Link above Create Game, Split-screen Co-op and Edit Gametypes. +Create Game selects Internet or Local Network. Existing callbacks own profile +selection, server creation, invites, map families, gametypes and the lobby. +Online campaign co-op remains a single-player map choice in Create Game; +split-screen co-op uses its existing second-controller/profile screen. There +are no placeholder Matchmaking, Party or Friends buttons without services. + +`frontend_menu_destination` in [frontend_menu.c](../../port/linux/game/frontend_menu.c) +recognizes the original PC multiplayer landing tag when modern mode is +active on a non-MCC main-menu map. The landing route still rejects active +network sessions; Phase 6 additionally permits its explicit hosting/lobby +roots in a pregame session. Missing tags, other styles and gameplay preserve +the requested destination. A minimal `port:` hook +in `ui_widget_load_by_name_or_tag` applies this to root instances only, before +allocation; it leaves history intact and never mutates existing definitions. +The hook is necessary because the unchanged main menu and profile prerequisite +open native tag references, which a feature module cannot otherwise intercept. +Phase 6 extends the same hook for hosting and lobby presentation, without +substituting MCC-owned loading paths. No protocol version change is required: +these phases change presentation and local dispatch only. + +[frontend_navigation.inl](../../port/linux/game/frontend_navigation.inl) owns +initial focus, contextual help and vertical scrolling. Rows, group captions +and separators move together; clipped rows remain navigable but are excluded +from drawing and mouse targets. New entries can exceed the visible area. +The native `main menu intialize` callback runs before navigation initialization +on both screens: returning from a cancelled host/browser must dispose that +abandoned network session before the main-menu editing guard runs. It also +restores the native profile/controller and variant lifecycle. No new global +navigation state persists between screen instances. + +For example, with `display.menus = "pc"` and `display.menu_frontend = "modern"`, +select Multiplayer on the unchanged starting screen. The native missing-profile +flow still runs first if needed. Select Local Network to enter the existing +LAN browser; Back restores the modern landing screen. Create Game → Local +Network enters the modern map chooser, with its existing Xbox, CE and MCC +categories and ownership. Cancelling hosting returns to Create Game and +cleans up that server; leaving the submenu returns to the original starting +screen. Settings Apply/Cancel likewise returns to the original starting screen. + +## Phase 6: hosting and lobby views; native browsers + +The user's final scope keeps the existing Server Browser, LAN browser, Direct +Link and filter/error/password screens. The attempted browser presentation was +removed, including its generated assets and routes. Joining through a native +browser can still enter the modern pregame lobby. The starting menu is unchanged. + +Read [frontend_multiplayer.py](../../tools/frontend_multiplayer.py), `PAGES` and +`append`, then [frontend_multiplayer.inl](../../port/linux/game/frontend_multiplayer.inl), +`frontend_multiplayer_update`. The six migrated roots are the connected map +chooser, connected gametype chooser, Server Setup, pregame lobby, in-progress +game preview and Bots settings. Specialized game-rule editors, profile selection +and bot management continue to use their existing services and screens. + +The generator reads the repository's generated CE declarations as a service +inventory. It creates separate `modern/network/` definitions, preserving semantic +widget leaf names, callback order, settings bindings and paged-list child order. +It copies only child/description dependencies; editor-opening callbacks keep +their established destinations. No CE definitions or generator outputs are edited. +Unreachable decorative declarations are removed from the new set. This is reuse +of this repository's menu contracts, not newly imported third-party code. + +[frontend_network_routes.inl](../../port/linux/game/frontend_network_routes.inl) +is an explicit generated whitelist. `frontend_menu_destination` accepts these +roots while `main_menu_is_active()` on the non-MCC `ui.map` latch, including an +active pregame host/client. Gameplay does not enable these multiplayer routes. +Only the explicit Settings root also routes during gameplay; its active style +stays latched until the main menu returns. Xbox/CE map UI and MCC pause ownership +keep their established paths. + +For example, Create Game → Local Network calls the original host service, then +shows the modern map chooser. The map-family spinner still calls the existing +Xbox/CE/MCC catalog adapters; folder navigation, map validity and difficulty +selection remain theirs. Selecting a multiplayer map advances to gametypes and +Server Setup. Its Start Game action creates the lobby through the native service. +Players can join through the unchanged browser. The lobby displays the native +player list, map preview, gametype and countdown; team, Start Now, Add Player, +Leave and host-only Bots actions retain their existing authority checks. No new +ready-state protocol or gameplay synchronization was introduced. + +The native list services still own their complete pages and selection indices. +The presentation adapter moves visible rows into a nine-row viewport, keeps +hidden conditional rows out of its count, and scrolls the focused row into view. +It never removes off-screen instances from navigation. The existing render/pointer +hook excludes them from drawing and mouse targets. Scroll state is derived from +live widget offsets, so it is discarded with the screen. Shared layout metadata +keeps text, outlines and hit targets aligned from 4:3 through ultrawide layouts. +Long selected Server Setup text values are also shown above the help text. + +The existing bitmap draw hook gained one narrow feature-owned policy call: +`frontend_menu_stretch_bitmap` in [frontend_layout.c](../../port/linux/game/frontend_layout.c). +New rounded artwork stretches; inherited map/gametype previews retain their +native padded-bitmap texel placement. A generator-only change cannot make that +renderer distinction. The hook is marked `port:` and is reached only for modern +widgets; legacy rendering and custom-map picture providers remain unchanged. +The right panel and row highlights reuse the existing plasma shader. Footer +prompts use the existing controller mapping/autodetection and keyboard labels. + +## Phase 4: Settings and scrolling + +The six tabs are Video, Audio, Controls, Online, Interface and Profile. +Video links to Advanced Graphics, First Person and Lighting; Online links +to Bots, Map Sharing and Server Browser. Interface includes menu style, +controller detection, saved manual/family glyph preferences, Multiplayer +HUD and Streamer Mode. Android gets its own touch/gyro page. Unsupported +platform rows are omitted by the existing XML reader, not shown as fake +options. Window Size and Resolution follow the pending display-mode choice. +The master-server status row uses the existing read-only service. + +[frontend_menu.py](../../tools/frontend_menu.py) imports `SCREENS` from the +existing generator without changing CE assets. `PAGES` and `LINKS` describe +modern navigation and generate [frontend_pages.inl](../../port/linux/game/frontend_pages.inl) +with the matching runtime routes. Add rows to the appropriate inventory or +modern page; there is no eight-setting limit. The pending store is bounded +at 256 changed settings, and a full store fails without discarding edits. +The current inventory is well below that limit. + +Up/Down, the controller stick/D-pad, and the existing mouse wheel/touch +navigation move through the list. The visible window holds eight rows. +`frontend_menu_help` keeps the focused row in view, repacks platform/visibility +filtered rows, and shows the visible range when more rows exist. Up from the +first row reaches the tabs; Down after the last row reaches the footer. +Tab/Y cycles tabs; the tab bar also supports Left/Right plus Select and direct +clicks. Escape/B returns from a subpage while preserving edits; on a top-level +tab it cancels Settings. The Cancel button always cancels the whole session. + +`frontend_menu_row_drawable` excludes rows outside the visible window before +both rendering and pointer-target registration. This small `port:` hook in +`widget_instance_render_recursive` is necessary: marking rows invisible would +make the engine skip them during navigation. All policy and scroll state stay +in the feature module. No legacy or MCC widget meets the ownership guard. + +All option labels and values use one text size per viewport. Narrow screens +use the small UI face consistently; at 832 logical columns and above they use +the large UI face consistently, with additional width shared by both columns. +`frontend_menu_font` chooses the face by viewport, never by individual caption. +The spinner's right arrow follows its expanded value bounds, preserving the +value's center between the arrows. The generator measures concise labels and +abbreviates exceptionally long enumerated captions for the narrow layout. +Headers, tabs and footer buttons keep their separate typographic roles. The +26-unit outlines, padding, heading gaps and Xbox plasma treatment are retained. + +`frontend_capture`, `frontend_restore` and `frontend_commit` in +[frontend_menu_runtime.inl](../../port/linux/game/frontend_menu_runtime.inl) +keep only tag handles and selection indices across page destruction. Apply +validates the batch, writes changed values through `setting_write`, saves an +owned dirty profile, and applies display settings. Defaults changes only the +current page's controls; it does not save them. Unvisited settings and custom +values whose nearest displayed choice was not edited are not rewritten. +The existing config writer can partially apply a failed save; the UI reports +that explicitly and retains the batch for retry. Cancel cannot undo those +already-applied writes. + +Profile uses player one's selected/last profile through `pc_menu_profile_edit_begin`. +With no profile, profile-value rows are hidden and Select Profile opens the +existing profile manager to select/create one. Changing profile is refused +while profile edits are pending, preventing edits intended for one player from +being applied to another. Name/color edits stay in the owned edit buffer; +Settings OK saves them and Cancel ends editing without saving. The frontend +releases only the profile-edit transaction it began. + +Controls opens the existing keyboard/mouse binding and per-player controller +remapping editors. Their own OK buttons commit their bindings independently; +this is stated in their help. Returning preserves other pending Settings. +Phase 7 adds the optional [keyboard glyph preference and artwork](keyboard_prompts.md); +these editors continue to own the bindings used by `halo_keyboard_binding_label`. + +A concrete sequence: change Audio volume, visit Interface, return to Audio, +and the pending volume is still shown. Cancel leaves the saved volume alone. +Repeat and choose OK to save both pages' changes. Switching menu style follows +that same Apply boundary, never a gameplay or pause-menu resource swap. +Map unload clears the pending store, scroll offsets and owned profile state +before tag handles become invalid. Legacy and MCC loaders, pause menus, map +folders and network protocol remain unchanged. + +## Review and validation boundary + +Validate default-off preservation, both enabled legacy roots, modern Apply +and Cancel, keyboard/mouse/controller navigation, missing resources, failed +persistence, repeated switching and map unload/reload. Check Xbox and CE +gameplay/pause, MCC's owned pause/Settings, and return-to-main transitions. +Android and web builds are required because these modules are shared. +This is presentation-only work: no network version change is warranted. +Any later gameplay or protocol changes need their own scope and checks. + +Source inspection and asset-free tests establish policy and wiring, not +full runtime map compatibility. Record actual build and runtime results +separately; a successful main-menu capture does not verify campaign, co-op, +split screen, custom UI bitmaps or every controller family. + +### Phase 2 validation, 1 November 2026 + +- Windows portable release build (`--pgo=off --lto=off`) passed. The linker + reported the existing Expat local-import warnings. +- 142 frontend, changelog, MCC UI/menu and web-build tests passed; one + POSIX socket-harness test was skipped on Windows. A further 13 MCC pause + runtime tests passed with Clang's `unused-but-set-global` warning disabled + for that existing test harness only. No MCC production code was changed. +- All six affected C translation units compiled for the Android guest and + web. Android was compiled to guest assembly, web to object files. Full + `ninja android` and `ninja web` were attempted but stopped at Unix-shell + staging commands (`sed`, `cp`, `ln`, shell builtins) unavailable to the + Windows build runner. These compile checks do not establish full links, + APK/browser runtime behavior or Android host/guest integration. +- Hidden Windows runs checked the new layout, staged selection/Cancel, + Modern-to-Xbox switching and reopening the modern screen with Y, the PC + route, and default-off behavior. Runtime captures caught clipped help + text; the generator now wraps it to the panel width. A final executable + run completed Modern-to-Xbox-to-Modern and retained `display.menus = "pc"`. +- Isolated local games on Xbox Blood Gulch and CE Death Island reached + gameplay, retained their existing pause layout, and ignored the modern + shortcut there. Initial sandboxed local-game attempts could not connect; + successful reruns used an isolated loopback address outside that sandbox. +- Source review verified the MCC admission/unload route; the existing MCC + action, Settings, pause-lifetime and ownership tests passed. Full MCC map + gameplay, network peers, split screen, touch, physical controller families, + and manual mouse/keyboard usability remain outside this prototype's + runtime evidence. These Phase 2 results predate the Phase 3 prompt integration below. + +Detailed logs and selected captures are kept under `build/frontend-*` in +this worktree. Test map copies and generated caches are disposable; inactive +test saves are preserved in verified archives before loose copies are removed. + +## Widescreen and prompts (Phases 2.5 and 3) + +The supplied OpenH1 screenshots are the layout and style reference, rather +than permission to invent a different theme. The current screen uses the +OpenCE title face, blue section rules, compact outlined rows, aligned values, +a full-height right information panel, and Defaults / OK / Cancel along the +bottom. These phases established the three-setting prototype; Phase 4 above +extends it to tabbed Settings and advanced subpages. Multiplayer contents +remain later migration work. + +The generated `nifty_fx` flag on the help panel, rows and buttons selects the +existing Xbox menu plasma-wave renderer. Transparent unselected row frames +leave no background; highlighted frames and the panel show the animated +shield pattern. The root background and title do not enable this flag. +No new shader, legacy shader change or MCC rendering path is introduced. + +[frontend_panel.c](../../port/linux/game/frontend_panel.c) draws modern rows +and the help panel in three horizontal pieces. Fixed 18-unit ends preserve +the rounded corners and border thickness while the middle expands. Its hook +in `draw_bitmap_in_rect` is necessary to reuse the engine-computed plasma +parameters unchanged. It is scoped to the current modern background draw and +cleared after that draw and at map teardown. Legacy bitmap drawing retains +its original path. + +Following visual review, option highlights and footer buttons are 26 logical +units high, with padded text and a separate gap below section headings. Row +labels and spinners share a three-unit child offset: the engine's spinner +renderer ignores `text_y`, so adjusting that attribute cannot align a value. +The value region is centered between the arrows, whose vertical centers also +match the row center. The information heading and selected value also have +a small gap. This gives the requested spacing while retaining +the reference's overall composition and plasma treatment. + +Read [frontend_layout.c](../../port/linux/game/frontend_layout.c), especially +`frontend_layout_geometry`, alongside `widget_instance_render_recursive` in +[ui_widget.c](../../source/interface/ui_widget.c). The renderer uses a local +copy of each modern definition for both drawing and pointer targets. Additional +width is divided between rows and help. Phase 4 selects a uniform option font +for narrow or wide viewports, as described above. +Content is centered and capped at 1280 logical columns on very wide displays; +the background still spans the screen. Dimensions are recomputed every frame. + +The original text renderer clips negative centered coordinates. A scoped +`frontend_menu_text_begin` / `frontend_menu_text_end` pair allows only the +current modern text draw to extend that clip through `frontend_menu_clip_text` +in [rasterizer_text.c](../../source/rasterizer/rasterizer_text.c). This hook +is necessary because changing widget bounds cannot change the renderer's +viewport clamp. It resets after each text draw and on map teardown. Help +wraps a fresh instance copy using unclamped font measurements on every draw; +resizing can therefore unwrap previous lines. The detached help widget has +no parent but must retain the incoming viewport clip; only the actual screen +container supplies a new viewport. Dynamic value/error widgets +have no generated string list: their allocated instance buffers must not be +replaced with short static strings by the renderer. + +[frontend_input.c](../../port/linux/src/frontend_input.c) owns only presentation +state. `XInputGetState` reports physical menu-button/stick edges before +remapping or keyboard/touch merging; the existing raw menu-stick threshold +rejects ordinary drift. A keyboard edge or the existing menu-pointer read +selects keyboard/mouse or touch. Holding a button does not repeatedly steal +prompts. Idle connections do not select a device; disconnecting the active +pad restores the last non-pad input source. State is enabled only for the +opt-in non-MCC `ui` map and reset at map boundaries. Debug scripted controller +input deliberately does not masquerade as a physical controller. + +[frontend_prompts.c](../../port/linux/game/frontend_prompts.c) defines Select, +Cancel and Menu Style (Tabs inside Settings) as menu actions, alongside the +navigation hint. They use the actual fixed menu controls: +South/A, East/B, North/Y; Return, Escape and Tab. Gameplay Jump remapping does +not relabel menu Select. Keyboard labels pass through the existing layout-aware +name resolver. Touch displays tap instructions. The generated prompt strip and +optional legacy entry use the existing post-text-draw menu adapter. + +[frontend_glyphs.c](../../port/linux/game/frontend_glyphs.c) resolves the active +physical port through `controller_button_style_for_port`. Automatic detection +remains on by default and saved manual/family choices are preserved. Modern +Xbox, PlayStation and Switch art uses `controller_glyph_draw_menu`; classic Xbox +faces use the shared `hud_hires_button_bitmap` allocator. Modern, stock PC and +gameplay draws share each registered artwork texture, while retaining their own +layout. Keyboard and controller menu glyphs require High-Res HUD. Caches +are bounded and disposed at map teardown. Missing artwork gets a physical +button-position label instead of an incorrect family glyph. + +Interface also exposes Stock Menu Glyphs for existing PC navigation and pause +legends. It defaults off and follows the same automatic/manual style selection. +Pending High-Res HUD enables the glyph controls, including Stock Menu Glyphs. +With High-Res HUD off, the modern footer uses text prompts. See the +[keyboard prompt guide](keyboard_prompts.md) for compact pause key sizing and +MCC-owned layout handling. + +For binding-aware gameplay keyboard prompts, `halo_keyboard_binding_label` in +[xinput_sdl.c](../../port/linux/src/xinput_sdl.c), declared in +[halo_keyboard.h](../../port/linux/include/halo_keyboard.h), reads the same +parsed binding cache as gameplay. It supports both binding slots, mouse and +wheel labels, keyboard-layout names, live configuration generation changes, +and empty results for invalid/unbound actions. It introduces no new remapping table. Phase 7 uses this reader for the optional +[keyboard/mouse prompt renderer](keyboard_prompts.md). + +### Phase 2.5 / 3 validation, 1 November 2026 + +The focused frontend, controller mapping/glyph, changelog, MCC UI/menu and +web-build suite passed 175 tests with one Windows socket-harness skip. A further +13 MCC pause runtime tests passed with the same harness-only warning override +noted for Phase 2. After the final generator-only spacing adjustment, all 12 +frontend tests passed again. The final Windows portable release build passed, with the +existing Expat linker warnings. Hidden runtime captures checked 4:3 and 16:9 +padding, section gaps, aligned values and arrows, focused footer buttons, and +the animated plasma. Earlier captures in this phase checked 16:10 and ultrawide +layout plus a live resize to 21:9; those predate the final control-height change. +The resize runner's posted mouse clicks did not confirm interaction, so these +captures are not evidence of end-to-end mouse usability. Production geometry +tests and source inspection establish shared drawing/target coordinates. + +Android and web full builds were attempted. Android staging stops in Unix +shell commands/CMake invocation on this Windows runner; web staging stops at +`cp`. All thirteen affected C translation units compiled independently for both +platforms (Android guest assembly, web objects). This is not a successful full +link or device/browser runtime test. Physical Xbox/PlayStation/Switch devices, +touch hardware, full MCC gameplay, split screen and network peers remain +hands-on/integration validation limits. Protocol and simulation code are +unchanged, so no network-version increment is required. + +The enabled frontend completed Modern-to-Xbox-to-Modern switching in a hidden +run, retaining `display.menus = "pc"`. Default-off captures retained the PC +frontend. Isolated Xbox Blood Gulch and CE Death Island runs reached gameplay +and exercised their pause UI with the modern preference enabled. The modern +shortcut did not open its screen there. These checks do not establish full +campaign or networking compatibility. + +The final self-review covered the complete optional frontend and its shared +hooks, settings/asset wiring, lifetime, tests and documentation. It corrected +stretched outlines, spinner baseline offsets, detached-help clipping and +dynamic text-buffer ownership. No legacy or MCC refactoring was needed. + +Temporary map copies and caches were removed. Inactive test saves were +archived with original paths and SHA-256 verification; selected captures and +logs remain. The Windows build (about 210 MiB) is retained for the next phase. +Android/web generated build inputs (about 75 MiB combined) remain available +for platform validation. A broad Android cleanup was rejected by automatic +approval review; only temporary source copies verified byte-for-byte against +their preserved originals were subsequently removed. Installed toolchains +and generated platform headers were retained. + +### Phase 4 validation, 1 November 2026 + +The final combined review covered the frontend modules, generated assets, +shared hooks, pending settings/profile ownership, input and glyph helpers, +tests and documentation. It removed per-row font sizing in favor of one +option face per viewport, confined right-arrow adjustment to spinners, fixed +the restore callback to match the existing boolean visitor signature, and +updated stale prototype descriptions. The MCC pause harness now extracts +only its existing MCC block, excluding the adjacent modern help hook; no +MCC production code changed. + +The final frontend, controller mapping/glyph, changelog, MCC UI/menu/pause +and web-build suite passed **207 tests, with one Windows socket-harness skip**. +The MCC harness needed its existing unused-global warning override. Generated +assets reproduce byte-for-byte; local documentation links and UTF-8 files +were checked, and `git diff --check` passed. + +The Windows portable release build passed with the existing Expat linker +warnings. Android/web full builds were attempted but stopped in the Windows +runner's Unix staging commands/CMake invocation. All thirteen affected C +translation units subsequently compiled for both Android guest assembly and +web objects, including the final callback fix. This does not establish a full +platform link, Android device run or browser runtime result. + +Hidden isolated Windows runs checked all six tabs, 4:3 and 16:9 typography, +the twelve-row graphics page scrolling down and navigating back up, returning +from a subpage, the keyboard binding editor handoff and return, and modern / +Xbox switching. A pending audio edit survived tab changes and Cancel left the +stored volume unchanged. An isolated profile copy saved a sensitivity change +and showed it after reopening Settings; SHA-256 checks confirmed the user's +original profile files were unchanged. The no-profile case retains Select +Profile while hiding unavailable profile values. The default-off run retained +the existing frontend. Xbox Blood Gulch and CE Death Island reached gameplay +and their existing pause menus with the modern preference enabled; Y did not +open modern Settings there. + +The runtime evidence is in this worktree's `build/frontend-smoke/phase4-*`, +with build/test logs under `build/frontend-phase4-*`. These scripted checks +do not establish full campaign/MCC gameplay, two-peer networking, physical +controller hot-plugging, touch interaction or end-to-end mouse-wheel behavior. +The production harness covers scrolling and input-source lifecycles; the +existing pointer navigation service is reused. Networking, simulation and +protocol formats are unchanged, so no network-version increment was needed. + +Phase 4 test processes have exited. Temporary map copies/caches, cross-compile +objects, the temporary SciPy test install, copied Android dependency sources +and disposable harness outputs were removed. Inactive test saves were +archived with original paths and verified SHA-256 contents before removing +loose copies. Selected captures, archives and logs for all phases occupy about +90 MiB. The required Windows build is about 212 MiB; generated Android/web +build inputs total about 78 MiB and remain for subsequent platform work. + +### Phase 5 validation, 1 November 2026 + +The combined implementation review checked feature ownership, root routing, +history, profile prerequisites, abandoned hosting sessions, scrolling, generated +assets and the existing input/presentation hooks. It removed the proposed +starting-screen replacement completely, removed its unused profile wrappers, +and fixed native session cleanup on return to the new landing screens. The +starting menu, CE XML and MCC production modules remain unchanged by Phase 5. +The only new engine integration is the guarded root-destination hook described +above; settings, renderer and glyph hooks retain their earlier boundaries. + +The final regression suite passed **209 tests with one Windows socket-harness +skip**. It covers generated destination references and reproducibility, native +mode callback names, a twenty-row navigation list scrolling both ways, the +45/55 widescreen split, root preservation, disabled/gameplay/MCC guards, +controller mapping/glyphs, changelog, MCC menu/pause and web-build contracts. +Windows portable release builds passed with existing Expat linker warnings. +All thirteen affected C units compiled independently for Android guest assembly +and web objects. Full Android and web builds were attempted but stopped in +this Windows runner's Unix executable/CMake staging and missing `cp`, respectively. +These are not successful full platform links or device/browser runtime checks. + +Hidden Windows runs verified the unchanged PC and Xbox starting screens, +opening Multiplayer from the PC starting menu and returning, the Settings +shortcut, native missing-profile creation followed by the modern landing +screen, LAN browser and Direct Link handoffs, and the Internet-disabled error. +Hosting reached the existing map chooser, gametype and Server Setup screens, +its Bots editor and the game lobby. Cancelling hosting restored modern +navigation and help after cleanup. Multiplayer layouts were inspected at +4:3 and 16:9. Xbox Blood Gulch and CE Death Island reached gameplay and their +existing pause screens; Y did not open modern Settings. User profile originals +were checked against the SHA-256 recorded before copying them into test saves. + +No live internet server join, two-peer session, full MCC gameplay, physical +controller/touch run or end-to-end mouse-wheel test is claimed. Those limits +remain separate from the verified local menu handoffs and production harness. +Detailed evidence is under `build/frontend-phase5-*` and +`build/frontend-smoke/phase5-*` in this worktree. + +All Phase 5 test processes exited. The feature-disabled runtime retained its +original multiplayer screen. Temporary maps/caches, copied Android dependencies, +cross-compile objects and the temporary SciPy/test outputs were removed. +Inactive test saves were archived with their original paths and verified hashes; +original user profiles were unchanged. Phase 5 captures, archives and logs occupy +about 32 MiB. The required Windows build and generated platform inputs remain +available for subsequent work. + +### Phase 6 validation, 1 November 2026 + +The combined review checked the generated widget dependencies and service +contracts, routing, viewport state, bitmap placement, lifecycle guards and +earlier Settings/input integration. It removed the abandoned browser routes, +assets and helper, pruned unreachable declarations, and removed unused test +imports. Native list indices, callbacks and session ownership remain intact. +The original starting screens, generated CE XML and MCC production modules +were not changed by this phase. No network protocol or simulation change +required a network-version increment. + +The regression suite passed **213 tests with one Windows socket-harness skip**. +Coverage includes native service contracts and callback ordering, browser/root +exclusions, pregame routing with gameplay/MCC rejection, scrolling without +changing service indices, preview geometry, and the earlier settings, glyph, +changelog, MCC menu/pause and web-build checks. The portable Windows release +build passed with the existing Expat linker warnings. All thirteen affected +C units also compiled independently for Android guest assembly and web objects. +Full builds were attempted: Android stopped at Unix executable/CMake staging +errors on Windows; web stopped at the missing `cp` command. These results do +not establish full Android/web links or runtime compatibility. + +Hidden Windows runs verified modern map selection, gametype selection, Server +Setup, the Bots editor, and the lobby. A 4:3 map list scrolled down and back up; +16:9 hosting/lobby and ultrawide Bots layouts were inspected. Native padded +map previews retain their picture placement. Two isolated LAN peers joined +through the unchanged LAN browser, displayed both players in the modern lobby, +and reached Battle Creek gameplay after the native countdown. The client +displayed the existing disconnect message when the timed host exited. This is +a local join/start smoke test, not sustained network synchronization coverage. + +The disabled-feature run retained the original multiplayer screen. CE Death +Island reached gameplay and its existing pause screen; the modern Settings +shortcut did not replace it. The prior phase's unchanged starting-screen and +Xbox/CE pause checks remain relevant. Full MCC gameplay, live internet joining, +physical controller hot-plugging, touch and end-to-end mouse-wheel interaction +were not tested in this phase. Details and retained captures are under +`build/frontend-phase6-*` and `build/frontend-smoke/phase6-*` in this worktree. + +All test processes exited. Original profile hashes remained unchanged. Temporary +map copies/caches, staged dependency sources, cross-compile objects and the +temporary test dependency install were removed. Inactive test saves were archived +with original paths and verified contents before removing loose copies. Selected +Phase 6 captures, logs and save archives occupy about 13.3 MiB. The required +Windows build occupies 213 MiB; generated Android/web inputs occupy about 80 MiB +and remain available for further platform work. + +### Phase 7 validation, 1 November 2026 + +Keyboard and mouse prompts now have a manual KEYBOARD style and an opt-in +automatic mode. The [keyboard prompt walkthrough](keyboard_prompts.md) records +the binding policy, semantic coverage, original artwork provenance, and the +necessary additive HUD and text-renderer hooks. Existing style indices remain +stable. This phase changes presentation only, with no network-version change. + +The combined review checked activation, input ownership, binding-cache reuse, +native icon fallback, drawing-state restoration and map-unload cleanup. The +initial coarse outlines were replaced with supersampled masks. Label placement +now measures actual visible font ink, supports fractional offsets, and accounts +for the HUD text cursor's three-unit retraction between text segments. Redundant +mouse-shape calculations were removed. Production harnesses cover allocation +failure, repeated cleanup and the disabled path as well as normal drawing. + +The final regression run passed **636 tests with one Windows socket-harness +skip**. It includes keyboard/controller prompts, binding and input policy, +frontend layout/navigation/multiplayer, high-resolution text/HUD, CE custom +icons, MCC HUD/menu/pause boundaries, changelogs and web-build checks. The +portable Windows release build passed with existing Expat linker warnings. +All nineteen affected C units compiled independently for both Android guest +assembly and web objects (38 successful compilations). Full Android/web builds +were attempted but stopped at the Windows-host NDK/CMake staging problem and +missing `cp`, respectively; independent compilation is not a successful link. + +Hidden, isolated Windows runs supplied inspected Settings keycaps and gameplay +captures. Xbox Blood Gulch displayed a manually selected F scoreboard binding +at 1920x1080 with High-Res HUD disabled. CE Death Island displayed the automatic +Tab prompt and retained its native pause screen. A default-disabled Blood Gulch +run retained the original plain BACK hint. A forced native A10 tutorial message +showed the mouse-right binding; this checks HUD rendering, not normal campaign +progression. The final F and Tab captures include the subsequent spacing fix. +Two earlier simultaneous local tests interfered because the local-test harness +uses a fixed host address; their captures were rejected and the checks rerun +sequentially. The successful runtime logs and captures are under +`build/frontend-smoke/keyboard-*`; regression/build logs are `build/keyboard-*`. + +Physical controller hot-plugging, real multi-player split-screen input, full +MCC gameplay, Linux runtime and Android/web runtime were not tested. Their +policy/boundary harnesses do not establish full runtime compatibility. Starting +menus and the native server browser retain their prior verified routes. + +All test processes exited. Original profile hashes were unchanged. Temporary +maps/caches, staged dependency sources, cross-compile objects and temporary test +dependencies were removed. Test saves were archived with original paths and +hash-verified before loose copies were removed. Selected keyboard captures, +logs and save archives occupy 9.46 MiB; the retained Windows build occupies +213.3 MiB and generated Android/web inputs occupy 79.6 MiB. + +### Phase 8 integration checks, 1-2 November 2026 + +Modern Interface now orders Menu Style, High-Res Text, High-Res HUD, then +Auto Detection. The two rendering options move out of Modern Advanced Graphics; +the legacy generated inventory is unchanged. `frontend_button_rows_show` in +[frontend_menu_runtime.inl](../../port/linux/game/frontend_menu_runtime.inl) +uses pending spinner values: High-Res HUD off hides detection and all glyph +controls, while on exposes the applicable family choice. Detection off shows +Manual Style; detection on shows the assigned device family (Manual Style for +an unknown device). The bumper option retains the native classic/gem restriction. +Hidden choices remain intact, and focus moves to a visible row when necessary. +The existing scroll layout compacts visible rows without gaps. Settings defaults +and the glyph rendering policies are unchanged. + +The final review covered the combined frontend lifecycle, pending edits, routes, +input ownership, rendering guards and map teardown. The family controls had +diverged from the native visibility policy; the correction above restores it. +No new shared-engine or MCC hooks were needed. The existing starting menu and +native server browser routes remain intact. A web build failure also exposed +Windows backslashes being consumed as escapes in Emscripten response files; +[web_build.py](../../tools/web_build.py) now quotes portable object paths, with +a regression check for paths containing spaces. + +The final regression run passed **644 tests with one existing socket-harness +skip**. It covers frontend navigation, pending edits, scrolling, detection and +HUD visibility, keyboard/controller prompts, CE custom HUD behavior, MCC +menu/pause/HUD boundaries and web build generation. Windows and web release +targets built successfully; Windows retains the existing Expat linker warnings. +The web build used the installed SDL cache and a staged SDL licence file, so this +does not verify a clean dependency bootstrap. All nineteen affected C units +also compiled independently to Android guest assembly. The full Android target +was attempted, but Windows-host shell chaining/redirection in dependency staging +failed before the platform link. The [Android build guide](../../port/android/README.md) +requires WSL2 on Windows; WSL is not installed on this machine. Independent +compilation does not establish a successful Android build. + +Hidden Windows captures confirm the new Interface order with High-Res HUD on +and that all dependent controls disappear with it off. A single-process fixture +run loaded Xbox Blood Gulch, MCC Mercury Falling with its package resources, +CE Death Island and the UI map in sequence. The MCC intro scene rendered and +simulation continued through the gameplay loads. Loading `ui` by console only +rendered its backdrop; this is not evidence of normal main-menu restoration. +Earlier Tiny Halo runs lacked matching resources and are excluded from successful +MCC evidence. + +Follow-up hidden Windows runs verified scrolling, Cancel restoring the original +Auto Detection value, Save applying it, and persistence in a fresh process using +the saved configuration. Normal menu navigation verified Modern-to-Xbox and +Xbox-to-Modern switching, with the existing starting menus retained. These runs +used isolated configuration and save folders; they did not change the user's +installed settings. + +Separate runtime runs entered Xbox Blood Gulch and CE Death Island, opened their +existing pause screens, and left gameplay through those screens. CE returned to +the existing PC main menu; the Xbox sequence returned to legacy menus and then +entered the campaign submenu through a subsequent scripted input. MCC Mercury +Falling, staged with its matching package resources, opened its MCC-owned +campaign pause screen and returned to the existing main menu through Save and +Quit. The MCC intro was ended through the test console before checking pause; +this is not full campaign-progression coverage. Gameplay tests required local +loopback sockets outside the sandbox, with internet discovery disabled. Earlier +sandboxed runs that could not create a local server are not successful gameplay +evidence. No additional production-code fixes were needed for these checks. + +The web release also ran in headless Microsoft Edge 156.0.4314.58, using an +isolated browser profile and a locally imported UI map. Captures verify the +Modern Interface rendering and keyboard input changing Auto Detection. This +checks the actual WebGL menu runtime, not browser gameplay or multiplayer. +Physical controller hot-plugging and split-screen input remain unverified; +the user explicitly asked to skip controller testing when the hardware was +unavailable. Linux runtime, full Android build/runtime and cross-machine play +also remain unverified in this environment. The passing checks are not a claim +of complete release compatibility. + +Evidence is retained in `build/frontend-phase8-*.log` and selected +`build/frontend-smoke/phase8-*` captures. Follow-up results include the +`phase8-roundtrip-*`, `phase8-switch-*-final`, `phase8-xbox-pause-network`, +`phase8-xbox-return`, `phase8-ce-leave-verified` and +`phase8-mcc-campaign-return` cases. Browser evidence is in +`build/phase8-web-runtime/`. Test saves are retained in verified +archives with original paths recorded. Disposable fixtures, duplicate captures, +temporary dependency staging and independent compile outputs are cleaned after +the runs; the required Windows/web builds remain available. + +### Online third-person merge, 2 November 2026 + +The menu checkpoint `e4bef11d9` integrates `online-third-person` at `f7fa7dcf7`, +including its upstream OpenCE prerequisites. The resulting code contains no +stencil-shadow feature, setting or hooks. Ordinary inherited stencil APIs are +unchanged. The incoming protocols remain OpenCE 41, MCC 63, third-person 32712 +and third-person MCC 32713. This menu integration does not change wire formats +or authoritative simulation, so it introduces no further protocol revision. + +[frontend_menu.py](../../tools/frontend_menu.py) adds the native Shoulder Camera +inventory below Modern Video > Third Person. Shoulder rows are visible only +when the pending Third Person choice is enabled. It uses the same pending settings, +Save and Cancel flow as other Modern settings pages. The third-person preference +remains off by default. [frontend_multiplayer.py](../../tools/frontend_multiplayer.py) +adds a Modern Session Options presentation reached from Server Setup, retaining +the native compatibility and host camera-policy callbacks and value indices. +Crossplay and Player Choice remain the defaults. Session Options labels its +compatibility choices **Crossplay / GulchCE** in every style. This names the +GulchCE-only session mode without tying its caption to one feature; protocol +values, version requirements and camera policy remain unchanged. Shorter captions and +wider value columns keep the choices legible at 4:3 without changing row fonts. + +The combined review covered menu callback/data registrations, generated routes, +input ownership, defaults, source hooks and map-family guards. Upstream server +screens introduced another gradient and a generic header widget; replacing both +variants in the Modern generator prevents a legacy border and title appearing +under the Modern header. Raw device observation still precedes input filtering, +but Modern key handling now follows upstream held-key suppression. Camera wheel +capture retains its upstream position before normal weapon-wheel handling. +Feature logic remains in its existing modules. No additional shared-engine or +MCC hooks were required. Starting menus, the native server browser, gameplay +pause menus and the main-menu-only style-switch boundary remain intact. + +The merge regression run passed **253 tests with one existing socket-harness +skip**, covering frontend layout/navigation, glyphs/remapping, camera policy and +wire behavior, checkpoints, MCC menu/camera boundaries and web generation. +After the header fix, all **25 affected frontend tests** passed again. All +**36 web JavaScript tests** passed. Final Windows and web release builds passed; +Windows retains existing Expat linker warnings. The web build used the installed +SDL cache and a temporary local Ninja wrapper for Windows-host dependency/copy +commands; this does not establish a clean dependency bootstrap. The Android +target was attempted but blocked by missing staged SDL sources. WSL2 and an +Android device are unavailable; no successful full Android or Linux build/runtime +is claimed for this combined merge. + +Hidden Windows runs rendered the shoulder settings at 16:9 and Session Options +at 4:3. Normal host-menu navigation selected Third Person compatibility and +Forced On, with both values verified in the isolated saved configuration. +The corrected Session Options capture has one title, clear section spacing and +unclipped policy choices. Headless Edge 156.0.4314.58 also rendered the actual +web shoulder settings and changed a pending height value through keyboard input. + +Five isolated two-instance Windows cases passed host/client policy checks and +five two-player samples per peer: Forced On, Forced Off, Player Choice with +different preferences, late joining, and the opening co-op sequence. The co-op +intro retained its cinematic camera; this is policy/join evidence, not rendered +shoulder-camera or full campaign coverage. These were local loopback tests with +internet discovery disabled. No new combined-build CE/MCC gameplay, WAN, +native/browser WebRTC, physical-controller or split-screen runtime coverage is +claimed. Earlier phase checks and the separate +[third-person qualification](third_person_qualification.md) are distinct evidence, +not substitutes for those remaining combined-build checks. + +Logs are retained in `build/third-person-merge-*.log`, with per-peer results in +`build/merge-camera-runtime/`, selected Windows captures in +`build/frontend-smoke/merge-third-person-*` and browser captures in +`build/merge-camera-web-runtime/`. Test-save archives retain original paths and +verified hashes; disposable cache maps, copied maps/binaries, duplicate captures +and temporary test dependencies are removed. Original profile hashes were checked +unchanged. The required Windows/web builds remain available for further testing. + + +## Menu follow-up layout and navigation + +The Modern Video tab separates First Person and Third Person. Advanced +Graphics links to Extra Effects for overshield, HDR and tone mapping controls. +Session Options, Bots, Map Sharing, Co-op Options, and Voice and Voting share +the same generated rows, scrolling and right-hand help layout. Their original +callbacks, host restrictions and network values remain responsible for behavior. +The server browser remains native. + +`append_legacy` in [frontend_navigation.py](../../tools/frontend_navigation.py) +defines separate Xbox links. `frontend_menu_attach` inserts Audio, Video and +Network Setup between Advanced Setup and Change Color, and binding/remapping/ +glyph editors in Advanced Controls. Original widget definitions are preserved; +only these optional instances receive links and vertical offsets. The native +profile help indexes strings and pictures by row number, so the guarded +`frontend_menu_legacy_description_index` hook excludes inserted links from that +index and supplies their help in an added description child. This shared hook +is necessary because the native callback otherwise indexes past its original +five descriptions. Children are owned and freed by their existing widget parent. +Advanced Controls also assumes each native row contains a spinner. The guarded +`frontend_menu_legacy_controls_help` hook skips that lookup for added editor +actions, and `frontend_menu_shortcut` opens those actions before the native +Accept handler saves and closes the screen. Existing native settings are saved +through their original handler; editor return restores the existing history. +The added Advanced Controls rows reference the native `option_bkds` bitmap, +matching its opacity. [frontend_legacy.py](../../tools/frontend_legacy.py) +generates separate footer definitions with unchanged action callbacks and +references to the original Xbox A/B/X menu bitmaps. Only live Xbox frontend +instances use these definitions, including Settings reached from gameplay; +Stock, PC and Modern retain their glyph preferences. Gameplay caches missing +the native menu bitmaps use the existing Xbox redraws from `port/assets/buttons`, +copied by the generator without alteration. A accepts ordinary settings +values and X resets defaults. Binding rows retain their bind/clear actions. + +[frontend_multiplayer.py](../../tools/frontend_multiplayer.py) creates the +campaign chooser and shared difficulty screen. The difficulty screen uses an +outer presentation container so the native first two children remain the list +and saved-progress warning. Plasma panels render before the native details; +selected difficulty rows retain their own plasma background. Completion icons +form a centered group beneath the campaign description. + +The multiplayer map chooser selects campaign difficulty inside its existing +map list, rather than opening the Campaign difficulty screen. +`frontend_multiplayer_difficulty` adds the same icon and wrapped description to +that step, hides the mission details, and uses centered label definitions for +those live rows. Returning to map selection restores the original labels and +details. Native and MCC host services keep their existing selection state. + +## Settings during gameplay + +`frontend_menu_style` separates the saved preference from the active style. +Leaving `ui.map` latches the current choice; gameplay map loads, including CE +and MCC, retain it. Saving a different style in Settings does not replace tags +or rebuild menus. Returning to `ui.map` adopts the saved choice. Stock remains +available explicitly; new configurations default to Modern. Auto Detection remains enabled by default and includes keyboard/mouse keycaps +in modern menu footers and supported gameplay prompts. The former separate +Keyboard Glyphs toggle has been removed; manual Keyboard remains available. + +Only the known generated profile Settings root is redirected. Modern paused +page roots share the settings inventory but omit `main menu intialize` and use +the existing pause history on OK/Cancel. The existing loader removes pause-time +flags for network sessions. MCC still decides its own Settings pause behavior +and owns its controller-specific profile session. Xbox gameplay uses a separate +Settings entry because gameplay caches need not contain the Xbox main-menu +profile editor. No map-authored pause roots are replaced. Profile replacement +and connection controls retain the established in-game restrictions. + +The combined review removed obsolete style-row visibility wiring and kept the +main-menu navigation guard separate from paused Settings access. Tests exercise +deferred saves across all three map-family identities, Apply/Cancel returning +to pause history, in-game Online restrictions, and embedded difficulty details. +Windows hidden runs verified Modern Settings on Xbox Blood Gulch, CE Death +Island and MCC Digsite `1`, Xbox Audio Setup, and Modern-to-PC deferral through +return to the main menu. These sampled maps do not establish compatibility with +every custom map. Full Android runtime and physical controller checks remain +unverified; the user asked to skip the unavailable controller test. + +Final checks for this follow-up: 105 Python tests passed; one POSIX socket +harness skipped on Windows and two unrelated artwork tests were deselected +because SciPy is unavailable. Windows and web builds passed, and all 11 changed +Android guest compilation units passed. The complete Android target remains +blocked by the missing staged SDL `CMakeLists.txt`. The multiplayer difficulty +panel was also checked at 640×480 and 854×480, and disabled/Stock Audio Setup +retained its normal buttons. Generated map fixtures and caches were removed; +test saves, logs and screenshots were retained separately from user data. + +`frontend_menu_reflow_text` in +[frontend_layout.c](../../port/linux/game/frontend_layout.c) normalizes native +manual line breaks in Modern instance text, including CRLF and `|n`, before +width-based wrapping. It rejoins manually hyphenated words such as +`wea-` followed by a newline and `pon`. The text is measured left-aligned, +then drawn using its authored centered alignment. Difficulty icon crop bounds +exclude the original bitmap padding; other native preview placement is retained. +These changes apply only to recognized Modern widgets, not stock text or map UI. + +Menu navigation uses `controller_glyph_draw_menu`, with bounded icon cells and +label spacing independent of gameplay's HUD scale. Manual controller styles +remain visible when auto detection is off; automatic mode still follows the +active input source. Gameplay uses its existing drawing entry point. + +Focused regression coverage is in `test_frontend_menu.py`, +`test_frontend_multiplayer.py`, `test_frontend_presentation.py` and +`test_controller_buttons.py`. Runtime captures use isolated hidden Windows runs; +small-resolution captures are desktop rendering checks, not Android hardware +validation. Build and runtime outcomes are reported separately from full +map-family or multiplayer compatibility. diff --git a/docs/reading/networking.md b/docs/reading/networking.md new file mode 100644 index 0000000000..e50f098816 --- /dev/null +++ b/docs/reading/networking.md @@ -0,0 +1,380 @@ +# Following a player action across the network + +The example is a client player moving forward while the host and another +player observe them. Read [input](settings_input_and_menus.md) and +[objects](objects_and_gameplay.md) first. The detailed reference is +[NETCODE.md](../../port/linux/NETCODE.md); this chapter supplies a route +through its implementation rather than reproducing its protocol catalogue. + +## Reading route + +| Order | Source and names to find | What to establish | +| --- | --- | --- | +| 1 | [network_game_manager.c](../../source/networking/network_game_manager.c), [network_server_manager.c](../../source/networking/network_server_manager.c) | Session/player admission and teardown. | +| 2 | [network_distributed.h](../../port/linux/game/network_distributed.h) | Message kinds and shared contracts between the distributed modules. | +| 3 | [network_distributed.c](../../port/linux/game/network_distributed.c): `network_distributed_tick`, `distributed_client_send_inputs`, `distributed_client_send_predictions` | What the client sends after advancing its player. | +| 4 | The same file: `distributed_take_prediction`, `distributed_correct_own_unit`, `network_distributed_handle_message` | Validation, host acceptance and local correction. | +| 5 | [network_objects.c](../../port/linux/game/network_objects.c), [network_damage.c](../../port/linux/game/network_damage.c) | Object lifetime, inventories, damage and hit reports. | +| 6 | [third_person_protocol.c](../../port/linux/game/third_person_protocol.c), [third_person_protocol.h](../../port/linux/game/third_person_protocol.h) | GulchCE-only camera admission; Xbox, CE and MCC share OpenCE admission in Crossplay mode. | + +## Joining creates a session, not just a socket + +A listing or advertisement tells a client about a game. Admission still +checks compatibility, available slots and session state. The networking +managers handle players joining and leaving; a player must acquire a +consistent identity before other packets can safely refer to them. + +Joining a running game adds further work: load the map, establish the +host's time, receive existing objects and game state, and become ready. +The [joining reference](../../port/linux/NETCODE.md#joining-a-game-in-progress) +explains the sequence and timeout rules. A connected peer that has not +loaded is not yet able to consume all ordinary gameplay messages. + +When diagnosing a join failure, separate discovery, admission, content +matching, loading and synchronization. Reaching one of these stages does +not establish that the next succeeded. + +## Input and predicted position are different messages + +The client's [input path](settings_input_and_menus.md) produces its player's +action. It advances its own player promptly instead of waiting for a round +trip. After the host's initial snapshot finishes, `network_distributed_tick` +records its own positions, sends inputs and sends predictions, then performs +other client network work. The checkpoint boundary below explains the brief +send pause while a snapshot is arriving. + +The input says what the player attempted. The prediction says where the +client's simulation put them. The host does not grant authority simply +because it receives a plausible-looking position: `distributed_take_prediction` +checks movement against its own state and permitted tolerances. The host +applies accepted predictions at its tick boundary. It also relays the +players' actions and sends authoritative unit state to clients. + +```mermaid +sequenceDiagram + participant C as Client player + participant H as Host + participant R as Other client + C->>C: Apply local action and remember predicted state + C->>H: Input and prediction + H->>H: Validate and advance authoritative state + H->>C: Unit state with prediction timing + H->>R: Relayed action and unit state + C->>C: Compare matching history and correct if needed + R->>R: Advance remote copy and reconcile +``` + +This diagram describes dependencies, not a promise that every message +arrives or is sent to every peer at the same rate. Distance, visibility, +batching and message type affect transmission frequency. + +When scripts disable player input, relayed actions no longer describe the +player unit's pose. A late join can attach the unit before the input-disabled +presentation arrives, leaving a locally changed aim that inhibition then keeps. +Read `distributed_scripted_pose_from_unit`, `distributed_unit_state_write`, +`distributed_unit_state_read` +and `distributed_scripted_pose_apply` in `network_distributed.c`: the host sends +desired facing/aim/look and current aim/look as separate directions while input +is inhibited or the unit is suspended. A body's forward axis is not a substitute +for any of those directions. Complete bounded decoding and direction validation +precede application to the matching live unit. The host rejects client +predictions carrying scripted pose or suspension fields; sharing a decoder +does not grant clients authority over those fields. + +For example, during a cinematic the host can retain its current aim while a +script has already requested a different direction. Both values must survive a +late join. The suspension flag also follows the host. Scripted correction does +not reuse ordinary input-prediction history, and it can reconcile orientation +even when positions agree. The existing co-op BSP guard still protects a local +player whose host has changed BSP. Normal controllable input omits the extra +vectors and retains its prediction path. This shared engine contract applies +independently of map family; it is not an MCC data conversion. + +[Scripted-pose tests](../../tools/test_scripted_player_pose.py) exercise the +actual codec, malformed/truncated input, unchanged ordinary wire data and a +stationary turn. The [milestone evidence](../mcc_refactor_validation.md#milestone-15-mcc-hud-corrections-and-shared-cinematic-aim) +distinguishes the controlled tests from native/browser runtime observations. + +A client with a custom firing position, such as a VR hand, can send OpenCE's +optional fire-origin message. In `network_damage_handle_fire_origins`, the host +accepts positions only for players owned by that client and within a bounded +reach. The hit-report path checks freshness, hand position and line of sight; +`network.fire_origins` controls whether this can admit a hit the eye cannot see. +MCC's separate message numbers and admission revision are recorded in +[NETCODE.md](../../port/linux/NETCODE.md), preserving OpenCE's message 93. + +Co-op presentation has its own authority path. In +[network_coop.c](../../port/linux/game/network_coop.c), +`client_presentation_apply` gives the host's scripted cutscene camera +precedence over dead-player spectating, including vehicle insertion scenes. +`camera_object_offset` follows the client's local copy of the filmed object. +When scripts release the camera, the normal spectating path applies again; +`coop_spectate_nothing_to_watch` retains the host view when nobody is alive +to watch. This is source behavior, not evidence of every campaign cutscene +having been played through. + +## Compare states from the same time + +Suppose the host replies about tick T, but the client has already moved on. +Comparing the host's old position directly with the client's current +position would mistake legitimate later movement for an error. + +`distributed_correct_own_unit` looks up the recorded local position for +the prediction time, checks both time and unit identity, and measures the +host's difference from that historical position. When correction is needed, +it applies the difference to the current position and adjusts the stored +history accordingly. This path preserves movement performed since T; it +is not a general rewind-and-replay implementation of every game object. + +The code contains special cases that carry meaning. A co-op player should +not be moved into a BSP the client has not loaded. A player still supported +by the same elevator can have a small vertical phase difference without +having made an invalid jump. Read those guards before simplifying the +position comparison. + +A client can also lose simulation time during a loading stall. Follow +`network_game_client_handle_message_server_game_update` in +[network_client_message_handler.c](../../source/networking/network_client_message_handler.c), +then `network_game_client_handle_game_update` in +[network_client_manager.c](../../source/networking/network_client_manager.c), +and `game_time_synchronize_distributed` / `game_time_update` in +[game_time.c](../../source/game/game_time.c). Only a decoded reliable update +from the selected host while in game supplies this target; distributed +datagram timestamps do not set it. + +For example, a client eight ticks behind remembers the host's timestamp and +can run two ticks on a frame that normally runs one. Every added tick executes +the normal simulation, interpolation snapshot and network publication. Extra +work is capped at the frame's ordinary tick count and 30 total ticks, never +past the observed target solely for catch-up. The fractional frame remainder +is unchanged. A repeated or older target adds no new time; this is not an +extrapolated moving clock. Local and host clocks, menus, startup holds, pauses +and MCC zero speed do not gain extra ticks. MCC's approved nonzero speed +determines the ordinary budget before catch-up. + +The target is transient, outside saved game state, and clears on initialization, +map disposal, game end and explicit clock replacement. Co-op checkpoint recovery +keeps the host clock monotonic; the target carries no object epoch or saved +world data. Initial synchronization and the existing jump for delays over one +second remain separate. The [frame-clock regression](../../tools/harness/tests/test_game_time_sync.py) +exercises the actual handler and tick loop, including stale targets, work bounds, +pause/speed transitions and lifecycle resets. Runtime results remain separate +evidence; passing this harness does not establish all network compatibility. + +## Authority also governs hits and object lifetime + +Movement prediction does not give the client authority over kills or +pickups. `network_damage.c` reports a local player's hits and checks them +on the host against ownership, weapon/rate rules, target history and other +constraints. The host deals damage. Clients replay the corresponding +presentation, with special handling for deaths and authoritative state. + +A projectile may remain after its firing object is deleted. The player lookup +`get_player_index_from_object_or_parents` in +[damage.c](../../source/objects/damage.c) therefore uses a checked object lookup +before following a non-unit's parent. An expired datum (including a slot reused +by a different object) yields no player for the gametype multiplier lookup. +It does not erase the damage payload's separate player/team attribution or +change host admission. The [owner lookup tests](../../tools/harness/tests/test_damage_owner_lookup.py) +cover live units, AI, parent chains, deletion and slot reuse. + +OpenCE's host also checks a reported point hit against level geometry in +`distributed_report_line_of_sight`. For example, a shot reported through +a solid wall is refused if no eligible recent shooter position has a clear +route to the target. The check uses bounded history and trace counts; +vehicle muzzles require a clear segment from the recorded eye position. +`distributed_stuck_detonation` allows a matching host-recorded attached +projectile to detonate after its victim moves behind cover, consuming that +attachment once. Melee, collision and area damage retain their existing +admission checks. The history and attachment ledger reset for each new game. +The [sight tests](../../tools/harness/tests/test_reported_hit_sight.py) +exercise extracted admission functions with controlled collision results, +including deliberate broken variants; they do not simulate every map's +geometry or replace real combat checks. + +`network_objects.c` creates, deletes and reconciles replicated objects. +The host tick sends object changes before messages that depend on those +objects. Kill statistics and damage/state ordering matter too: receiving +a reference before the referred-to object or announcing a kill before its +statistics can produce an inconsistent client even if each packet is valid. + +An inventory can arrive in an unreliable datagram before its unit or weapons +arrive on the reliable stream, despite the host's send order. OpenCE's +`distributed_client_retry_inventory` retains the latest inventory for each +unit in a bounded queue. `distributed_client_apply_retried_inventories` +checks it each client tick, applies entries once their objects +exist, and expires entries after `EMPTY_INVENTORY_TICKS`. A checkpoint clears +the queue in `network_objects_reverted`; `network_objects_new_game` uses that +same reset. For example, a newly spawned player +can receive their weapon inventory before the weapon object; retaining it +lets the client equip that weapon when it arrives without granting the +client authority over inventory. The +[retry tests](../../tools/harness/tests/test_retried_inventories.py) exercise +late units and weapons, replacement, capacity, forgetting and expiry using +extracted engine functions and deliberate broken variants. + +A checkpoint can restore an earlier living object with the same full handle +that identifies its corpse on a client. Follow `network_coop_reverted` in +[network_coop.c](../../port/linux/game/network_coop.c), then +`network_distributed_reverted` in `network_distributed.c` and +`network_objects_host_reverted` in `network_objects.c`. This is shared network +co-op behavior, independent of camera policy or map family. + +Every distributed header includes a world epoch: a host-owned counter outside +checkpointed game state. `network_distributed_reverted` advances it and +`distributed_restore_checkpoint` clears old prediction, recovery, damage and +actor state. `distributed_message_epoch_valid` accepts a new epoch only from +an exact, standalone reliable host boundary. Gameplay messages with another +epoch are rejected before simulation clocks, stale tracking or handlers run. +Thus an old reliable kill cannot kill a restored object merely because its +handle matches. +Late-join readiness can request the current boundary within the existing +resend limit; it cannot adopt an epoch or authorize gameplay itself. + +Read `network_objects_client_asked` next. Its reliable snapshot sends the +boundary, object descriptions, ordinary inventories, then an exact +`objects_synchronized` end marker. `distributed_host_send_inventories_to_machine` +includes empty inventories of living units. For example, a healthy retained +unit may still carry a weapon picked up after the saved checkpoint; explicit +empty slots remove it even after the periodic sender's empty-inventory window +has elapsed. MCC's additional grenade slots and campaign state retain their +separate periodic synchronization in `mcc_network.c`. + +Before the end marker, the client accepts ordered object descriptions and +ordinary inventories, while refusing other gameplay and suppressing outgoing +gameplay in `distributed_fill_header`. `network_objects_client_tick` continues +readiness, inventory retries and cleanup bookkeeping, but uses +`distributed_checkpoint_ready` to postpone local inventory and vehicle +prediction notes. Old replicas therefore cannot supply new-world input or +make the restored inventory look like an acknowledgement of a local shot. +The marker confirms ordered delivery; failed object creation still uses the +existing retry path rather than being declared successful. + +Client simulation continues during the transfer, so it can create projectiles, +delayed effects and hit reports from replicas that are only partly restored. +On the first validated ordered host end marker for the current epoch, +`distributed_message_epoch_valid` retires those projectiles and effects with +`network_objects_discard_client_effects`, clears hit queues through +`network_damage_new_game`, and clears provisional input, prediction and send +histories through `distributed_reset_checkpoint_state(FALSE)` before ordinary +gameplay messages resume. This preserves the object descriptions and inventories +already applied from the snapshot. It also retains sender and per-message receive times, so +older datagrams in the same epoch remain stale. A duplicate end marker does +not repeat this cleanup or erase current gameplay. + +In `distributed_client_create`, only the first validated description for an +object slot in the new epoch may replace a same-handle dead co-op unit with +the host's live copy. `distributed_client_reuses_object` applies that rule; +`distributed_handle_unit_state` subsequently binds the player. A later live +description in the same epoch cannot undo a newer death. Another checkpoint +explicitly renews eligibility. Existing healthy replicas retain their normal +reuse path. + +The initial boundary reset also calls `network_objects_discard_client_effects`: +old client projectiles and effects with delayed object or damage parts are deleted +through their existing lifecycle. Host checkpoint projectiles remain intact. +This boundary does not comprehensively reset or reconstruct authored HUD, +navigation-point and attachment caches. Those pre-existing presentation paths +need separate evidence before claiming complete authored checkpoint rollback. + +The [checkpoint regression](../../tools/test_coop_checkpoint_recovery.py) and +[epoch dispatch tests](../../tools/test_checkpoint_epoch.py) exercise actual +engine functions. The [original investigation](../mcc_refactor_validation.md#stage-10-shared-checkpoint-recovery-investigation) +retains the old default-profile failure and the earlier camera-only limits; +the [shared recovery validation record](../mcc_refactor_validation.md#stage-10-shared-checkpoint-recovery-fix) +reports checks completed for the new contract, separately from source intent. + +## Transport has its own contracts + +Inputs are sent unreliably, with recent button history repeated to tolerate +loss without waiting for retransmission. Important lifecycle events use +reliable connections. Unreliable updates carry time information so stale +data can be rejected. Reliability does not replace size, sender, direction, +rate or index validation. + +Internet play uses the P2P transport around this gameplay model. Native +[p2p_webrtc.c](../../port/linux/src/p2p_webrtc.c) and browser +[web_p2p.c](../../port/web/src/web_p2p.c) connect through WebRTC data channels; +the browser's socket constraints change transport implementation, not who +decides damage. See [Transport](../../port/linux/NETCODE.md#transport) before +following packet details into those files. + +The transport also owns its worker lifetimes. In +[p2p.c](../../port/linux/src/p2p.c), `p2p_initialize` registers `p2p_shutdown` +before creating the worker. Shutdown requests a stop under `p2p_lock`, waits +outside that lock for both the tunnel and UPnP workers, then withdraws the +public listing and any idle router mapping. Upstream bounds each exit wait +to three seconds; a worker that exceeds it may still be running as the C runtime +closes its streams. This applies to every map family without changing packets +or simulation. Completed UPnP workers are also reaped before +renewal. [Lifecycle regressions](../../tools/test_p2p_shutdown.py) execute the +actual functions with controlled OS threads and failure injection. + +`posix_upnp_cancel` in [posix_upnp.c](../../port/linux/src/posix_upnp.c) is a +process-exit latch, checked between discovery, mapping scans and port retries. +It cannot interrupt an active miniupnpc request. Discovery asks for two +seconds, connection waits use three seconds and HTTP reads use five seconds +per read; repeated reads and multiple devices mean these are not a total +request deadline. The bounded exit wait does not guarantee an active request +has finished. Browser UPnP remains disabled, with a no-op cancellation stub. + +## GulchCE compatibility and teardown + +Crossplay uses upstream OpenCE protocol 43 for Xbox, Custom Edition and MCC +maps. Map-vote messages remain IDs 94-95; checkpoint recovery is 96; MCC owns +its upstream gameplay, sharing, admission and loading message IDs. MCC content +identity and loading checks remain active, but there is no GulchCE-specific MCC +capability, network version or join envelope. + +After decoding an ordinary join, the host checks its appended shared version +before token, ban and player-slot admission. The +[join codec test](../../tools/test_join_protocol.py) checks that old and truncated +requests cannot omit this field. `test_mcc_protocol.py` pins the complete +upstream protocol 43 manifest and exercises host admission. MCC-only gameplay +messages must still not execute on Xbox or CE maps; map-family isolation is +independent of protocol compatibility. + +For dedicated hosting, start at [dedicated_server.md](../dedicated_server.md), +then read `server_director.c` for rotation and session ownership and +`server_commands.c` for administration. These upstream paths retain the same +ordinary host authority and admission checks. + +The Session Options selector chooses Crossplay (`opence_crossplay`) or GulchCE +Only (`gulchce_third_person`). Crossplay disables multiplayer shoulder-camera +behavior. GulchCE Only uses camera protocol 32744, an additional shoulder relay +byte and a mandatory kind 102 join envelope around the ordinary join. It is the +same contract for all map families. Forced Off remains a camera session and +does not relax admission. + +Read [third_person_protocol.c](../../port/linux/game/third_person_protocol.c): +`third_person_protocol_join` and `third_person_protocol_unwrap` bound and +validate camera admission. The shared join send/dispatch hooks are necessary +because the engine owns those boundaries. Host create/open/dispose hooks own +the session lifetime; client join/disconnect hooks clear prior permissions. +A camera server requires the envelope before the ordinary token, bans, slots +and map-content checks. A Crossplay server uses the ordinary shared-version admission path. +The selected mode cannot change after the lobby opens. See the +[camera walkthrough](third_person.md#session-compatibility) for behavior, +state ownership and tests. Public listings retain the common discovery +format; the subsequent advertisement and handshake determine compatibility. + +## Evidence and useful checks + +The original Xbox lockstep model is replaced by the port's distributed +netcode. The core host/client behaviour above comes from that port; the MCC +admission boundary is GulchCE-specific. +[test_elevator_prediction.py](../../tools/harness/tests/test_elevator_prediction.py) +and [test_elevator_correction.py](../../tools/harness/tests/test_elevator_correction.py) +exercise production movement paths in controlled conditions. +[test_server_teardown.py](../../tools/harness/tests/test_server_teardown.py) +checks session cleanup. These were inspected, not run for this chapter. + +[net_compare.py](../../tools/net_compare.py) runs builds together and judges +their logs; [test_net_compare.py](../../tools/test_net_compare.py) tests the +judge itself with constructed logs. Passing the latter does not establish +that two game builds interoperate. Real changes need appropriate host/client, +late-join, loss, teardown and native/browser transport checks. The +[testing chapter](platforms_and_testing.md) explains how to report their limits. + +Continue with [maps and resources](maps_and_resources.md), or return to the +[guide](README.md). diff --git a/docs/reading/objects_and_gameplay.md b/docs/reading/objects_and_gameplay.md new file mode 100644 index 0000000000..93b5510b8a --- /dev/null +++ b/docs/reading/objects_and_gameplay.md @@ -0,0 +1,167 @@ +# Players, objects and gameplay state + +The example here is a player receiving a new body, controlling it and +eventually losing it. It connects the [input path](settings_input_and_menus.md) +to the [simulation tick](startup_and_loop.md). A player, a unit, a weapon +and a tag definition are related records with different lifetimes. + +## Reading route + +| Order | Source and names to find | Question it answers | +| --- | --- | --- | +| 1 | [players.h](../../source/game/players.h), [units.h](../../source/units/units.h), [objects.h](../../source/objects/objects.h) | What state belongs to a player, unit or general object? | +| 2 | [players.c](../../source/game/players.c): `player_spawn`, `players_set_local_player_unit`, `players_update_before_game`, `players_update_after_game` | How does a player acquire and control a body? | +| 3 | [objects.c](../../source/objects/objects.c): `object_new`, `objects_update`, `object_delete`, `object_delete_immediately` | How are instances created, advanced and retired? | +| 4 | [data.c](../../source/memory/data.c): `datum_try_and_get`; [object_types.h](../../source/objects/object_types.h) | How do handles and type-specific operations work? | +| 5 | [units.c](../../source/units/units.c): `unit_control`; [weapons.c](../../source/items/weapons.c) | Where do controls and weapon behaviour become gameplay? | +| 6 | [game.c](../../source/game/game.c): `game_tick`; [network_objects.c](../../port/linux/game/network_objects.c) | Who updates objects, and who may create or delete them online? | + +## Definitions describe; instances change + +A unit definition supplies authored properties, including its camera FOV. +A live unit holds changing state such as health-related flags, position, +inventory and its association with a player. Several instances can use the +same definition without sharing their changing position or damage state. + +`player->unit_index` refers to the player's current body. Weapons are +objects too, with their own handles and inventory relationships. The local +player's first-person weapon presentation is another layer: changing its +drawing is not the same operation as changing the weapon's ammunition or +the target's health. The [FOV chapter](field_of_view.md) demonstrates that +separation in a small module. + +The engine's object types dispatch different operations for bipeds, +vehicles, weapons and other kinds. When an object-specific function appears +to be missing from `objects_update`, look at the type dispatch it calls +rather than assuming every type is updated inline in that one function. + +## Follow a new spawn + +`player_spawn` includes a campaign path that can reactivate a retained body. +For this example, follow the path that creates a new unit instead. It finds +a starting location, chooses a unit definition from the appropriate game +globals and constructs `object_placement_data` before calling `object_new`. +The following inventory and player-linking code completes the spawn. + +`object_new` does more than allocate a structure. It can apply gametype +definition remapping, validates the tag's object type against the type it +will instantiate, allocates an object header and a type-sized datum, and +initializes position, orientation, ownership, animation and child links. +It starts with a result of `NONE`; callers must account for failure. + +This explains two otherwise surprising details. First, a definition index +is not an object index: the new object points back to its definition. +Second, the object header and the object's payload are distinct; the header +tracks identity, type and lifecycle flags used by the object manager. + +In a running tick, `players_update_before_game` translates the player's +action into unit controls. `objects_update` visits active objects and calls +their update path, with creation flags and other conditions controlling +eligibility. `players_update_after_game` runs later in `game_tick`. +The order lets the tick coordinate player decisions and object results. + +## A handle is not a pointer or a permanent identity + +`datum_try_and_get` separates the encoded slot and identifier, checks the +slot against the pool's capacity and checks the entry's identifier. That +extra identifier helps distinguish a later use of a recycled slot from +the object an old handle originally named. There are special cases in the +lookup implementation, so use the engine's accessors rather than inventing +a universal bit manipulation rule at a call site. + +An object index cannot be substituted for a player index just because both +are stored in a `long`. Likewise, an array of local-player values cannot +be indexed by either handle. The compiler sees similar integer types; the +program's contracts give them different meanings. + +An object can also have no player owner. For example, multiplayer overshield +decay in `object_damage_update` in [damage.c](../../source/objects/damage.c) +can reach `hud_tick_shield` with `NONE`. The HUD function in +[hud_unit.c](../../source/interface/hud_unit.c) skips that notification before +looking up a player; decay still runs normally on the object. Monaco's +multiplayer startup exposed the inherited invalid lookup. Local players +still receive the HUD adjustment, while remote players have no local HUD +to update. [test_hud_shield_tick.py](../../tools/test_hud_shield_tick.py) +checks these three ownership cases against the real function. + +Pointers returned by lookups refer to engine-owned storage. They are not +permission to free that storage, and retaining one across deletion or map +unload can outlive its referent. When following a long-lived field, look +for its clearing or invalidation path as carefully as its assignment. + +## Deletion is a lifecycle, not just a free + +`object_delete` first checks `network_objects_may_delete`. Its initial +recursive deletion path marks the object and children as being deleted, +hides them and removes names. That is different from concluding that all +storage was freed immediately. The final removal path has attachments, +relationships and type-specific cleanup to handle. + +```mermaid +flowchart LR + A[Definition and placement] --> B[Create header and datum] + B --> C[Link player and inventory] + C --> D[Controls and object ticks] + D --> E[Mark for deletion] + E --> F[Detach and retire storage] +``` + +This is why an old projectile's damage-owner record matters even after its +player has left. A reused player slot must not accidentally inherit credit +or authority for that projectile. The production paths exercised by +[test_stale_player_damage.py](../../tools/harness/tests/test_stale_player_damage.py) +retire player references and validate late damage ownership. Its `reused`, +`deleted`, `unspawned` and `authority` cases are useful examples of testing +lifetime rather than only a successful hit. + +## Gameplay authority and feature boundaries + +A vehicle controller also produces temporary state. Read `vehicle_update` +and `update_human_boat_physics` in +[vehicles.c](../../source/units/vehicles.c), then `physics_update`, +`physics_compute_new` and `physics_update_old` in +[physics.c](../../source/physics/physics.c). The powered-point controls are +local to one tick; authored physics flags determine which controls become +forces. They are different from persistent object state and from the mass-point +output array that physics clears. Initializing one does not initialize the other. + +The [boat investigation](../mcc_maps.md#shared-engine-investigation-7-november-2026) +shows why that distinction matters: the shared three-point boat controller +initializes all three temporary records before assigning its active controls. +Equivalent accepted Xbox, Custom Edition and MCC inputs receive the same +correction. This replaces the former MCC initializer without changing authored +tags or other vehicle controllers. The regression tests exercise both physics +paths' forces and resulting motion. Matching network agreements exclude older +legacy peers whose driven-boat prediction still used uninitialized controls. + +The host decides network spawns, pickups, damage and deletion. A client +may predict its own movement while still needing the host's object changes. +Do not infer ownership from a local object being present. Read the checks +in `network_objects.c` and the [network walkthrough](networking.md). + +The engine supplies the core object, unit and weapon systems. Port gametypes +and networking add guarded integration. OpenCE's optional CTF kill scoring +starts at `ctf_kills_score` and `ctf_capture_points` in +[game_engine_ctf.c](../../source/game/game_engine_ctf.c). Multi-Hill keeps +each active hill in `king_hills`; read `king_pick_extra_hills`, +`king_hills_to_globals` and the network-state readers and writers in +[game_engine_king.c](../../source/game/game_engine_king.c). Its first hill +still supplies the legacy `king_globals` view. Force Team Spawns is checked +by `game_engine_force_team_spawns` in +[game_engine.c](../../source/game/game_engine.c), with a fallback when a map +lacks either team's CTF spawn locations. These options default to stock +behavior and the host controls their scoring and spawn decisions. + +GulchCE's MCC inventory, movement, +damage and object-name adaptations live in the MCC modules listed in +[CODINGSTANDARDS.md](../../CODINGSTANDARDS.md). Similar-looking structures +do not make those compatibility paths interchangeable with Xbox or CE paths. + +This chapter traces source; it does not establish gameplay correctness for +every weapon or spawn mode. The stale-damage harness and +[Stagekit walk scenario](../../tools/stagekit/tests/test_walk.py) illustrate +different levels of evidence and were not run for this documentation pass. +A lifecycle change needs failed creation, death, respawn, departure, reused +slots and map teardown checked alongside an ordinary living player. + +Continue with [rendering](rendering.md), or return to the [guide](README.md). diff --git a/docs/reading/platforms_and_testing.md b/docs/reading/platforms_and_testing.md new file mode 100644 index 0000000000..44ca3b8b4a --- /dev/null +++ b/docs/reading/platforms_and_testing.md @@ -0,0 +1,219 @@ +# Shared code, platform boundaries and evidence + +This chapter follows the same game entry point into different environments, +then shows how to investigate a behaviour without confusing a small test +with a complete game run. Read [startup](startup_and_loop.md) first. Build +commands and mandatory checks remain in [AGENTS.md](../../AGENTS.md) and +the platform READMEs; this is a reading guide to their reasons. + +## Reading route + +| Order | Source | What to establish | +| --- | --- | --- | +| 1 | [configure.py](../../configure.py), [linux_build.py](../../tools/linux_build.py), [windows_build.py](../../tools/windows_build.py) | Which files and compiler conventions make a native build. | +| 2 | [halo_linux_prefix.h](../../port/linux/include/halo_linux_prefix.h), [halo_math.h](../../port/include/halo_math.h) | Compatibility definitions and shared maths behind familiar source syntax. | +| 3 | [host_main.c](../../port/android/host/host_main.c), [guest_host.h](../../port/android/guest/runtime/guest_host.h), [host_imports.list](../../port/android/host_imports.list) | Android startup and the permitted guest/host interface. | +| 4 | [guest_sdl.c](../../port/android/guest/runtime/guest_sdl.c) | SDL operations actually bridged for the Android guest. | +| 5 | [web_main.c](../../port/web/src/web_main.c), [web_build.py](../../tools/web_build.py) | Browser storage, the worker entry and WebAssembly build differences. | +| 6 | [Harness README](../../tools/harness/README.md), [Stagekit README](../../tools/stagekit/README.md), [net_compare.py](../../tools/net_compare.py) | What each verification layer really runs. | + +## The binary contract matters as much as the C declaration + +The native Linux and Windows builds use 32-bit x86 and the game's MSVC-style +ABI conventions. Structure layout, pointer size, alignment, return values +and inline-function handling matter because the game and its data expect +them. Prefix and compatibility headers adapt the compilation environment. +The [Linux](../../port/linux/README.md#how-the-port-operates) and +[Windows](../../port/windows/README.md#how-the-port-operates) references +explain the platform implementations in detail. + +The XDK declarations in `port/include/xdk` are the project's independent +stand-ins. Their [README](../../port/include/xdk/README.md) describes their +provenance and how to extend them. The prohibited original SDK headers and +`xbox/include` are not reading prerequisites. + +Maths is another interface. Native game calls use the shared implementation +described in `halo_math.h`, and builds disable fused multiply-add. Tiny +floating-point differences can affect machines simulating the same game. +An apparently harmless replacement with a platform library call can therefore +be a networking change, even if the code contains no packet operations. + +## Android: a 32-bit game model in a 64-bit application + +Android's host is a 64-bit app. The game guest uses ILP32 AArch64: integers, +longs and pointers in the guest are 32 bits despite its AArch64 instructions. +That distinction preserves the game's layout assumptions without making the +Android host itself a 32-bit process. + +In `host_main.c`, the SDL entry loads the guest image from the APK, prepares +its environment and launches its main routine with a stack in guest memory. +Host imports and the SDL bridge define what the guest can call. A library +available to the host is not automatically callable by game code: signatures, +pointer representations and bridge support must agree. + +For a concrete investigation, suppose a shared feature needs a new SDL +operation. Trace its existing calls through `guest_sdl.c`, then check +`guest_host.h` and `host_imports.list`. A successful Windows compile cannot +establish that the Android bridge exists or passes the value correctly. +See [Android internals](../../port/android/README.md#how-the-port-operates) +before adding cross-boundary calls. + +For GPU buffer lifetime, follow `host_gl_fence_frame` and `host_gl_wait_frame` +in [`host_gl.c`](../../port/android/host/host_gl.c), then the ring rotation in +`D3DDevice_Present` in [`d3d8_gl.c`](../../port/linux/src/d3d8_gl.c). +A timed-out fence still owns its slot: the host finishes queued work before +allowing another upload. The [Android OpenGL ES notes](../../port/android/README.md#opengl-es) +describe the fallback, regression coverage and remaining device-validation limit. + +## Web: the same game with browser scheduling and storage + +`web_main.c` runs on the Emscripten worker, mounts the browser's Origin +Private File System at `/data`, sets data/save defaults and calls +`halo_game_main`. `web_build.py` renames the original `shell_xbox.c` main +function to that name. The main loop then uses its web callback path. + +The page and the game worker have distinct responsibilities. Importing game +data and managing the page do not mean the game's C code can use arbitrary +desktop files or native sockets. [web_p2p.c](../../port/web/src/web_p2p.c) +bridges browser transport, and the [web reference](../../port/web/README.md) +describes storage, workers, graphics and current limits. WebAssembly calls +must match their callee's type exactly; code that happens to survive an ABI +mismatch on one native build can fail here. + +`HALO_GLES` is shared by Android and web, while `HALO_ANDROID` and `HALO_WEB` +identify different environments. An Android-only guard is not a substitute +for an OpenGL ES capability condition. The Vulkan work discussed in +[rendering](rendering.md) has its own supported scope and does not establish +an Android or web Vulkan implementation. + +## A sound stopped between mixer callbacks + +The shared [DirectSound mixer](../../port/linux/src/dsound_sdl.c) implements +the sound streams used by Xbox, Custom Edition and converted MCC audio. +The map readers and MCC conversion ownership remain separate. This OpenCE +fix changes how an already-playing stream stops, without changing game +simulation or network messages. + +For example, firing a weapon again can reuse the previous shot's channel. +Read `stream_flush`, `voice_cut`, `mix_voice` and `mix_cut`: the mixer +captures the next 240 output frames (5 ms at 48 kHz) before returning packet +memory, fades them to silence, and mixes them beside the next shot. A second +cut preserves the unplayed part of the first fade, including its reverb send. + +GulchCE's flush guard addresses a callback boundary: `stream_complete_head` +unlocks the mixer for the game's completion callback. The stream's +`flushing` flag prevents the audio thread from mixing remaining live packets +over the captured fade during that interval. Cancellation remains synchronous, +the fade owns its samples, and the guard clears before a later sound starts. +Paused or never-played voices do not acquire a new fade. Releasing a stream +removes it and its remaining fade from the mixer. + +The [mixer harness](../../tools/harness/tests/test_mixer.py) uses the real +mixer and stream functions. Its flush case schedules a real worker during +completion callbacks; its overlap case checks output samples and reverb sends +for both resamplers, mono/stereo sources and stereo/5.1 output. Negative +controls remove the flush guard or discard a previous fade and must fail. +Run `python -m pytest -q tools/harness/tests/test_mixer.py` on Linux or Windows +with clang and the platform's 32-bit compiler prerequisites. These asset-free +checks do not replace listening tests, platform builds or map transitions. + +## Choose evidence that reaches the suspected behaviour + +| Layer | What actually runs | What it cannot establish alone | +| --- | --- | --- | +| Source inspection | The reader follows production callers, contracts and conditions. | Runtime success, appearance or performance. | +| Harness | Extracted production functions compiled against a small fake world. | Every dependency, real assets or a real GPU/device. | +| Format/tool tests | Real parsers or utilities with generated fixtures and sometimes optional assets. | A whole scenario playing correctly after conversion. | +| Stagekit | The real engine on deliberately generated scenarios, without retail assets. | Retail-map fidelity or every script and resource combination. | +| Runtime/visual/network checks | A configured build with actual platform, content and peers. | Untested maps, hardware, transitions or long sessions. | + +The harness extracts functions from source instead of maintaining a second +implementation. Its fake world supplies controlled state and dependencies. +Negative controls intentionally alter an extracted copy and require the +test to catch the fault. This demonstrates sensitivity to a particular +failure; it does not prove the absence of all defects. + +Stagekit goes further: its generator creates a stage, props and cues, then +the real engine runs them. For example, +[test_walk.py](../../tools/stagekit/tests/test_walk.py) checks that a player +stands on the floor, moves and jumps using positions sampled from the run. +Those samples are not every physics step. Stagekit is Linux-only and needs +the build/runtime prerequisites described in its README. + +## MCC refactor baseline + +For the MCC refactor's current milestones and concrete baseline, see +[MCC refactor milestones and validation](../mcc_refactor_validation.md). Its +overview separates completed work, deferred fixes and retained compatibility +limits, including the shared co-op recovery finding. The evidence sections +record the starting revision, the installed-Workshop smoke runner, the +distinction between pytest coverage and direct GPU execution, and actual +validation limits. Read `parse_args`, `case_environment`, `run_case` and `check_result` +in [mcc_native_smoke.py](../../tools/mcc_native_smoke.py) to follow a virtual +Workshop level name through an isolated hidden game run and its evidence. +The verdict checks debug, console, stdout and stderr diagnostics. Cache and +executable cleanup require observed child exit; uncertain shutdown retains +the outputs and stops subsequent cases so they can be investigated safely. + +[Milestone 10](../mcc_refactor_validation.md#milestone-10-shared-co-op-checkpoint-recovery) +tracks shared co-op recovery, and +[Milestone 11](../mcc_refactor_validation.md#milestone-11-shared-boat-control-initialization) +tracks shared boat initialization, recovery from small client clock delays +exposed by Mercury, and the separately authorized console lifetime repair. +Read `update_human_boat_physics` in +[vehicles.c](../../source/units/vehicles.c), `game_time_update` in +[game_time.c](../../source/game/game_time.c), and the console state helpers +included by [hs_runtime.c](../../source/hs/hs_runtime.c). These correct existing +engine contracts across map families; none selects a fix by map name. +The Stage 11 evidence separates the original failures, focused source tests, +native runtime checks and three actual-map Internet cases. Mercury driving +passes the unchanged comparison thresholds; the other affected Workshop B30 +check establishes static boat presence only. Network agreements are separated, +and old-layout console saves are refused. Consult the recorded limits before +inferring full campaign, every-map or old-peer compatibility. + +## Work through a suspected movement regression + +Suppose a player unexpectedly falls through an elevator. First record the +map family, host/client role, build revision, settings and the point in the +transition. Follow the responsible movement/correction source and inspect +the existing [elevator harness](../../tools/harness/tests/test_elevator_correction.py) +and [Stagekit elevator scenario](../../tools/stagekit/tests/test_elevator.py). + +The harness can isolate a correction rule. Stagekit can establish whether +the assembled engine keeps a rider supported in its generated scenario. +A retail-map run may still be needed for the original geometry, timing or +scripts. A network problem also needs both roles considered; a single local +run cannot establish cross-machine agreement. + +On a configured Linux environment, examples of focused existing checks are: + +```sh +python -m pytest -q tools/harness/tests/test_elevator_correction.py +python -m pytest -q tools/stagekit/tests/test_elevator.py +``` + +These are example commands, not tests run to write this guide. A successful +test of [net_compare.py's log judge](../../tools/test_net_compare.py) likewise +does not mean two builds were actually played together. Follow +[Comparing two builds](../../port/linux/NETCODE.md#comparing-two-builds) for +the latter, including both host/client directions where required. + +Automated game runs must use the repository's hidden-window or virtual-display +rules, isolated data/save folders and at most two game instances. Stop only +processes started for the test. Retain useful evidence, but clean up verified +temporary outputs without deleting original maps or saves. Read AGENTS.md +before running examples; a debug setting is not a blanket automation recipe. + +## Report the boundary of the result + +Record what was inspected, compiled and actually exercised separately. +Name skipped tests and missing prerequisites. For rendering, include the +backend and a real image check; for maps, distinguish loading from campaign +completion; for networking, name roles, transports and relevant transitions. + +The linked test, design and baseline documents record their own validation. +Example commands in this chapter are not claims that those checks ran. +The reader's guide explains how to interpret the evidence and its limits. + +Return to the [guide](README.md) for the full reading route. diff --git a/docs/reading/rendering.md b/docs/reading/rendering.md new file mode 100644 index 0000000000..be5ecf4128 --- /dev/null +++ b/docs/reading/rendering.md @@ -0,0 +1,578 @@ +# From game state to a picture + +This chapter follows a view of a room containing a moving player and a +weapon. The simulation has already established their state. Rendering +chooses a pose to show, decides what may be visible, submits drawing work +and presents an image. Read [startup and the loop](startup_and_loop.md) +and the [FOV walkthrough](field_of_view.md) for the timing and camera inputs. + +## Reading route + +| Order | Source and names to find | What it contributes | +| --- | --- | --- | +| 1 | [main.c](../../source/main/main.c): `main_game_render`, `set_window_camera_values` | The views and cameras for this frame. | +| 2 | [render_interpolation.c](../../port/linux/game/render_interpolation.c) | Poses between simulation snapshots and handling of discontinuities. | +| 3 | [render.c](../../source/render/render.c): `render_frame`, `render_player_frame`, `render_window` | Per-frame and per-view ordering. | +| 4 | [render_cameras.c](../../source/render/render_cameras.c): `render_camera_build_frustum`; [render_objects.c](../../source/render/render_objects.c) | Projection, viewing volume and visible objects. | +| 5 | [rasterizer_lights.c](../../source/rasterizer/rasterizer_lights.c), [rasterizer_transparent_geometry.c](../../source/rasterizer/rasterizer_transparent_geometry.c) | Lighting and transparency passes. | +| 6 | [d3d8_gl.c](../../port/linux/src/d3d8_gl.c): `draw_flush`, `D3DDevice_DrawIndexedVertices`, `D3DDevice_Present` | Translating the game's graphics calls to OpenGL and presenting them. | +| 7 | [nv2a_vsh.c](../../port/linux/src/nv2a_vsh.c), [nv2a_psh.c](../../port/linux/src/nv2a_psh.c) | Translation of Xbox shader operations into GLSL. | + +## Prepare a view before drawing objects + +The [depth and decal walkthrough](reversed_depth.md) follows the desktop's +default reversed depth through projection, depth tests and decal offsets, +including the conventional-depth fallback and interaction with dynamic lighting. + +OpenCE's `convex_polygon2d_clip_to_plane` in +[geometry.c](../../source/math/geometry.c) keeps a corner on the clip line +when a rounding error would otherwise produce a NaN crossing. This prevents +that invalid coordinate from hiding later portals for a frame. The fog-screen +pass keeps each split-screen view's previous camera in its own slot through +`previous_camera_matrix_for_window` in +[rasterizer_xbox_environment_fog.c](../../source/rasterizer/xbox/rasterizer_xbox_environment_fog.c). +Both corrections apply through the existing renderer for every map family. +The [issue 83 investigation](../geometry_flicker_83.md) connects the portal +correction to disappearing terrain, its regression tests and the remaining +limits of that evidence. + +`screen_mode_choose` in [d3d8_gl.c](../../port/linux/src/d3d8_gl.c) selects +the render-target scale separately from the game's logical 480-line view. +Resolution scaling can use native pixels, 75%, 50%, 25%, or the original +resolution. Android defaults to original and bounds larger targets by the +GPU limit; the desktop default remains native. Settings apply between frames. + +The engine can render several local players. `render_frame` manages the +frame and windows; `render_player_frame` prepares a player's frustums and +handles additional views such as mirrors. `render_window` performs drawing +within a prepared view. A "window" here can mean one rendered view inside +the application's window, not necessarily a separate operating-system window. + +The render camera describes position, orientation, clipping distances and +FOV. Building its frustum produces the planes and transforms used to relate +world positions to the screen. Visibility also uses the map's spatial +structure and potentially visible sets. A later GPU occlusion query is a +different mechanism; the words "visibility" and "culling" can refer to +several stages, so find which stage owns a result before changing it. + +In the example, the moving player's rendered pose can lie between its two +simulation snapshots. A teleport or respawn should not interpolate through +all intervening space. `render_interpolation.c` contains the checks and +fallbacks for those discontinuities. Rendered poses and simulation positions +are related values with different purposes. + +First-person hands and weapons use `render_interpolation_first_person` in +[render_interpolation.c](../../port/linux/game/render_interpolation.c). It keeps +camera-relative poses per local player. The caller, +`first_person_weapon_build_node_matrices` in +[first_person_weapons.c](../../source/interface/first_person_weapons.c), supplies +the weapon's full object handle and animation graph tag index. Those identities, +the node count and consecutive ticks determine whether two poses can blend. +The identities must come from the caller: matrices alone cannot distinguish a +weapon replacement from a fast animation with the same number of nodes. + +This replaces a 0.25-world-unit displacement cutoff that held the entire pose +at its latest tick during fast rocket-launcher melee and reload motion. Rendering +still refuses non-finite displacements. A replacement within a tick, missing +poses, disabled Smooth Motion or `render_interpolation_reset` at map startup +discards the old history. Xbox, Custom Edition and MCC retain their own loading +paths and supply their existing poses to this shared render service; simulation +state and animation timing are unchanged. + +A separate discontinuity occurs when the stock rocket's tube node resets by +180 degrees after chambering. Its rotation advances normally before that reset; +blending the reset invents an extra half-turn between the equivalent tube poses. +Near-half-turn rotations snap that node only. Smaller turns and the other nodes +continue blending, including the hands. This is a render-side discontinuity +guard, not a change to the authored animation or ammunition state. + +[test_first_person_interpolation.py](../../tools/harness/tests/test_first_person_interpolation.py) +compiles the production snapshot, matrix and rotation code. It checks fractional +frames, weapon/graph replacement, split-screen slots, camera transforms, capacity, +invalid data, chamber resets and history resets. Negative controls restore the old +distance cutoff or blend through the half-turn and must fail their corresponding +cases. These asset-free tests do not establish +visual compatibility for every authored animation. + +OpenCE also advances visual function values into the picture's time. Read +`object_function_values_for_render` in [objects.c](../../source/objects/objects.c): +for example, a charging plasma weapon's displayed intensity changes between +ticks without overwriting the simulation's values. `render_object_list` and +`first_person_weapon_draw` retain these values in frame memory because queued +transparent draws can read them later. GulchCE's +[viewmodel shield module](../../port/linux/game/viewmodel_shield.c) copies the +interpolated unit values into its existing per-player arms storage; the shield +and overshield modules still own their feature state and activation checks. + +The render functions use the incoming values saved by +`object_compute_function_values`, rather than reading the object's current +inputs. An invisible vehicle weapon can overwrite its parent's inputs after +the parent ticks; rereading those inputs made Warthog headlights follow the +gun's illumination with Smooth Motion enabled. The saved inputs live outside +game state and are checked against the full object handle. Map starts and +saved-game loads call `object_function_inputs_forget` in the lifecycle of +[game_state.c](../../source/saved%20games/game_state.c). Until fresh inputs +exist, or with Smooth Motion disabled, rendering uses the stored tick outputs. +This shared rendering correction preserves the simulation and the separate +Xbox, Custom Edition and MCC loading paths. The asset-free +[picture-function tests](../../tools/harness/tests/test_picture_function_inputs.py) +cover overwritten inputs, additive functions, reused handles and invalidation; +they do not establish GPU visibility or lens-flare occlusion correctness. + +## Lightning changes shape once per tick + +OpenCE's lightning correction keeps the random offsets of a bolt stable +between simulation ticks. For example, Assault on the Control Room's light +bridges should not flicker nearly five times faster at 144 FPS than at 30 FPS. +Read `lightning_submit` in [lightning.c](../../source/objects/widgets/lightning.c): +the first submission in a tick saves the local random seed for that lightning +slot and split-screen window. Later submissions replay it, then restore the +seed they found. Marker positions and the camera-facing geometry are still +evaluated for each rendered frame; the cache stores no vertices or map pointers. + +`lightning_new` clears a reused slot. `lightnings_reset_render_state` clears +all seeds on map initialization, map unload and through the post-load callback +list in [game_state.c](../../source/saved%20games/game_state.c). GulchCE adds +the unload and post-load resets because restoring a checkpoint can replace +the lightning pool without calling `lightning_new`, including at the same tick. +The callback only clears rendering state; saved data and network messages +are unchanged. Xbox, Custom Edition and MCC retain their existing loading +and conversion paths and use this shared renderer through its existing interface. + +The [lightning harness](../../tools/harness/tests/test_lightning_tick_shape.py) +executes the real submission code and post-load callback list with fake +renderer services. It covers tick zero, moving markers, independent bolts, +all four views, pool reuse, map and checkpoint resets, and failed draw recovery. +It does not establish visual parity or platform compatibility; those require +real-game captures and builds as well. The +[integration validation record](../lightning_tick_shape_validation.md) +separates the completed checks from remaining platform and visual limits. + +## Draw passes have an order and temporary state + +Read `render_window` for the actual order of world/object drawing, lighting, +decals, transparent geometry and other effects. Transparent work is not +simply appended to one universal opaque draw: the engine has multiple +passes and queues. Near the end of the primary view, tone mapping and +anti-aliasing happen before interface and menu drawing. This placement +explains why changing a world postprocess need not alter text in the same way. + +The first-person weapon can temporarily use a separate projection. Its +begin/end scope must restore the world camera, as the FOV chapter explains. +The same reading habit applies to a texture unit, render target or stencil +state: identify who sets it, which draws use it and who restores it. + +Object shadows have the same begin/end contract. In +[rasterizer_xbox_shadows.c](../../source/rasterizer/xbox/rasterizer_xbox_shadows.c), +`_rasterizer_environment_shadow_begin` initializes the shadow volume only +for the primary render target with environment shadows enabled. It returns +false for a skipped pass, so `render_object` in +[render_objects.c](../../source/render/render_objects.c) does not draw or end +an uninitialized volume. This fixes inherited behavior that returned true +even for a skipped pass. Monaco exposed it in a secondary reflection view, +with `structure_clusters_in_sphere` rejecting the uninitialized radius. +The correction applies to all map families and does not alter MCC conversion +or enable shadows in reflections. [test_shadow_setup.py](../../tools/test_shadow_setup.py) +exercises the real setup function for primary and secondary targets, disabled +shadows and transitions back to an enabled primary pass. + +```mermaid +flowchart LR + A[Simulation snapshots] --> B[Rendered poses and cameras] + B --> C[Visibility and draw passes] + C --> D[Xbox-shaped graphics calls] + D --> E[Backend state and shaders] + E --> F[GPU work] + F --> G[Present image] +``` + +## Player shield appearances + +GulchCE's non-default SHIELD LOOK presets are restricted to player bipeds. +Read `shield_look_player`, `shield_look_for_unit` and `shield_look_skip_shell` +in [shield_look.c](../../port/linux/game/shield_look.c). The unit's current +player index establishes eligibility, including remote players; an asset +name or shared model does not. For example, an AI Elite sharing a player's +biped definition keeps its authored shield even after the player's preset +has populated the shader cache. + +The shared [model submission](../../source/models/models.c) passes object +identity and the first-person flag to shell suppression. First-person hands +use the weapon as their draw identity, so the feature checks its parent +unit without changing the renderer's identity. The same ownership guard +protects depleted arcs and recharge; Arm Shields still controls the added +first-person pass. These are drawing decisions and do not change shield +strength or network state. See [Shield Look](../shield_look.md) for detailed +behaviour and [its regression tests](../../tools/test_shield_look.py) for +shared-model and ownership-transition coverage. + +## The platform layer translates graphics state + +In the shared OpenGL path, the game still makes Xbox Direct3D 8 calls. +`d3d8_gl.c` reads the device state and translates it into OpenGL operations. +The shader translators convert vertex-program instructions and pixel +combiner state to GLSL. This is why an unfamiliar Xbox-era shader constant +may be consumed several files away from the draw call that sets it. + +Coordinate conventions matter: depth range, viewport origin, texture rows +and the final presentation flip must agree. The opening comment in +`d3d8_gl.c` explains the desktop convention; `HALO_GLES` selects the +OpenGL ES/WebGL adaptations. Do not assume a desktop GL facility is available +on Android or the web because the C file is shared. + +`prepare_draw` binds sampled textures before render targets because resolving +a sampled multisample image can change framebuffer bindings. When +`render_target_get` allocates a new target, it temporarily binds that texture +on the active texture unit. It must restore that unit's previous 2D binding +before returning, including a previous binding of zero. Invalidating the +renderer’s state cache alone does not restore the actual GL binding. + +This shared contract was verified by tracing CE DeathIsland's first water-ripple +draws in a browser process that had not loaded MCC. Each newly allocated output +texture replaced sampler 3's input; the sampled texture ID then equalled the +framebuffer's color attachment ID. WebGL rejects this feedback with +`INVALID_OPERATION`, as specified in its +[texture/framebuffer feedback rules](https://registry.khronos.org/webgl/specs/latest/1.0/#6.26). +The fix preserves the allocation's prior binding without changing map-family +loading paths or the existing intentional-feedback copy. The +[allocation regression](../../tools/test_render_target_binding.py) executes the +real target lookup and storage functions with recorded GL bindings, covering +color/depth allocation, distinct inputs, unbound inputs, active-unit preservation, +cached lookups without new queries, and callers that explicitly select a texture. +It is a state-contract test; current visual/platform evidence belongs in the +[validation ledger](../mcc_refactor_validation.md). + +`fragment_shader_get` first caches the complete pixel-shader state key, so a +repeat draw does not translate GLSL again. GulchCE's `fragment_source_get` +then reuses a compiled fragment shader only when the generated source matches +byte for byte. A hash narrows the search; `strcmp` decides equality. For +example, two different state keys that emit identical GLSL keep separate key +entries but reference one compiled shader. `program_get` can consequently reuse +the same link when the vertex shader also matches. Uniform updates still run +through the existing per-program serial/state checks. + +The source cache owns one generated string and shader result per distinct +source, including a failed compile result. Full-key entries borrow the shader +ID. If a source-entry allocation fails, the full-key cache retains its compiled +result without sharing. These entries have the existing device/context lifetime +and retain no map pointers; they are not freed during map transitions. This +does not add context recreation to the backend. See the +[cache tests](../../tools/harness/tests/test_fragment_source_cache.py) and +[fix report](../damage_and_shader_cache_fixes.md) for validation and limits. +Shader generation, AMD's direct visibility readback and the asynchronous +buffered readback used by NVIDIA remain unchanged. + +When a new shared fragment is compiled, `fragment_source_get` also calls +`shader_hash_set` before taking ownership of its source. This registers it with +OpenCE's separate on-disk program cache. Reused fragments keep the same shader +ID and source hash, so source deduplication does not disable binary-program reuse. + +Before its presentation blit, `D3DDevice_Present` selects the window's draw +framebuffer after looking up the source framebuffer. `framebuffer_find` +binds both read and draw targets when it creates an entry. Without restoring +the draw target, a first presentation can blit the back buffer onto itself. +A fresh Xbox map's loading-screen draws can create that entry earlier, +masking the defect when saved map caches are absent. The +[presentation regression](../../tools/harness/tests/test_present_framebuffer.py) +checks new, reused and changed source framebuffers, plus HDR presentation +and its blit fallback. This binding defect was reproduced during issue #80's +investigation; it does not establish the cause of the reported persistent +Android geometry loss. + +At presentation, `D3DDevice_Present` unbinds the OpenGL read framebuffer +before `platform_video_swap`. The read framebuffer selects the image used +by pixel-read and copy operations; binding zero selects the default window +framebuffer. This OpenCE change restores the binding expected by OBS game +capture. It applies to the shared GL presentation path; an ordinary render +smoke test alone does not verify OBS capture itself. + +Submitting a draw does not mean the GPU has completed it. In particular, +visibility-query results and reusable upload storage have completion rules. +[Visibility query readback](../visibility_queries.md) and +[test_visibility_readback.py](../../tools/harness/tests/test_visibility_readback.py) +show why a delayed GPU result must not be treated as a zero or why asking +for a result too soon can stall the frame. The test uses fake driver +behaviour; it does not measure real GPU performance. + +## Camera and cloth timing + +`player_effect_get_camera_effect_matrix` in +[player_effects.c](../../source/effects/player_effects.c) caches each local +player's first camera-effect matrix for the tick. Repeated render frames keep +the weapon impulse or shake at that tick's strength instead of consuming its +decay early. Windows have separate caches; rendering restores the local random +seed afterward. `player_effect_reset_render_state` clears only these matrices. + +`flags_update` in [flags.c](../../source/objects/widgets/flags.c) accumulates +render time but advances cloth only on a new game tick. Cloth constraints used +to run once per render frame, making flags stiffer at high refresh rates. +`flags_reset_render_state` discards both the previous tick and partial frame time. + +Both resets run at map initialization/disposal and through the existing +`after_load_procs` table in [game_state.c](../../source/saved%20games/game_state.c). +For example, restoring a checkpoint at tick 100 must draw its camera impulse, +not a cached matrix from the previous state at tick 100. These caches belong +to their effect modules, outside saved game state; the dispatcher is the +necessary shared lifecycle connection. Xbox, CE and MCC retain their loaders. +The [lifecycle harness](../../tools/harness/tests/test_render_effect_lifecycle.py) +executes actual update functions and the callback table; removing either +checkpoint hook makes its regression fail. It stubs rendering and cloth physics. + +## Contrail timing + +Projectile trails are chains of points. Read `contrails_update` and +`contrail_update_points` in [contrails.c](../../source/effects/contrails.c), +then `render_contrail` in [render_contrails.c](../../source/render/render_contrails.c). +Emission and point-state aging use elapsed game ticks at 1/30 second per tick +(half that in double-speed mode), independent of uneven render-frame spacing. +Point motion and texture animation still use each rendered frame's time. +This preserves short bright states at high refresh rates; aging every frame +previously shortened trails whose state transitions discard excess time. +The clock resets on map initialization, disposal and checkpoint restoration, +including a restore at the same tick. Multiple elapsed ticks advance existing +point states separately; this does not reconstruct earlier attachment poses. +New points still initialize on frames without a tick so the renderer has a valid state. +See the [contrail fix record](../contrail_timing.md) for evidence and limits. + +## Dynamic lighting 1.0 + +Android builds exclude the optional lighting modules and their model-shader +additions. Read the [Android lighting boundary](../../port/android/README.md#lighting-availability) +and [stock hook implementations](../../port/android/guest/dynamic_lighting_disabled.c) +for that fallback. Desktop and web keep the implementation described below; +all optional lighting settings still default off. + +On desktop and web, `prepare_draw` obtains `plasma_model_lighting_mask` only +for instruction-recognized point-light model programs. `draw_program_get` +selects the stock vertex and fragment variants when this mask is zero. A +selected optional light chooses lazy enhanced variants instead; the per-pixel +fragment key includes this distinction. This also honors host-controlled +Shield Glow, because the mask uses the existing effective feature policy. +An enabled setting without a selected light still uses stock model shaders. + +The stock variants contain no optional model-light uniforms, samplers or +falloff helpers. They skip optional uniform lookup, sampler initialization +and per-draw bindings. Enhanced compile/link failures have separate fallback +state and cannot disable stock per-pixel lighting. Both variants use the +existing source-deduplication and driver-specific binary caches. Previously +used variants remain cached, so toggling back does not recompile them; the +first use can still incur a compile/link hitch. This separation changes no +AMD/NVIDIA translation workarounds or map-family loading paths. +The [shader isolation harness](../../tools/harness/tests/test_dynamic_shader_isolation.py) +checks lazy caching, repeated switches, independent failure recovery and zero +optional GPU calls for stock draws. The +[translator harness](../../tools/harness/tests/test_plasma_model_shader.py) +checks the real vertex programs and point-light formulas on desktop, web and +Android. These CPU tests do not establish driver performance or visual parity. + +These optional features are available on `main` and `testing`. The +[plasma lighting source](../../port/linux/game/plasma_lighting.c) +is a useful second example after FOV. `plasma_lighting_prepare` selects +eligible authored projectile and energy-emitter attachments and records temporary state; +`plasma_lighting_frame_end` restores it. Window and reset functions delimit +view-specific selection and longer-lived feature state. + +The [emitter expansion walkthrough](emitter_expansion.md) covers sword/charge/heat +attachments, vehicle and world emitters, flame aggregation and consolidated controls. + +For world reflections, read `plasma_specular_begin` and +`plasma_specular_color` in [plasma_falloff.c](../../port/linux/game/plasma_falloff.c). +The inherited specular pass uses a light's scalar brightness and the +surface's reflection colours, discarding the light's hue. A green bolt can +therefore produce a pale, view-dependent highlight beside its green spill. +The enhanced path tints both material reflection colours with the selected +light's normalized hue, preserving the existing brightness and falloff. +The small hooks in `_rasterizer_environment_specular_light_begin` and +`_rasterizer_environment_specular_light_draw` are necessary because those +functions own the material shader constants. Policy and temporary tint state +remain in the feature module. Every begin resets the tint, and +`plasma_falloff_end` clears it even when no attenuation texture was bound. +Unselected lights return the original packed material colour unchanged. +Authored no-specular flags, impacts and explosions remain authoritative. +This is a reflection colour correction, not an additional light or a change +to projectile simulation. A highlight can still move relative to diffuse +spill as the viewing angle changes. + +The projectile's simulation and tag data are not the place to manufacture +the rendering effect. This path uses the rendered attachment pose and +temporarily changes eligible light behaviour. Separate modules own added +rocket lights, muzzle lighting and Covenant emitters. Their activation, +budgets and cleanup must be read in their own modules, not inferred from +the existence of the common plasma setting. + +For the Grunt/Hunter fuel-rod flight light, `lights_preprocess_scene` passes a copy of the +evaluated colour through `covenant_lighting_color` in +[covenant_lighting.c](../../port/linux/game/covenant_lighting.c). With Projectile +Lights enabled, the exact projectile/exhaust pair gets less red and blue while +green modulation stays authored. Only the rasterizer submission is adjusted; +the source light still supplies stock flare and simulation colours. See the +[Covenant projectile reference](../covenant_lighting.md) for tag evidence and +map-lifecycle handling. + +The [plasma reference](../plasma_lighting.md) +explains falloff and approximate collision-based occlusion; its +[emitter reference](../covenant_emitter_lighting.md) +explains exact tag/marker eligibility and bounded additional lights. +Approximate occlusion is not a complete shadow system. The +[1.0 baseline guide](../dynamic_lighting_release.md) describes current +controls and known limits; the plasma document retains historical milestone +evidence, with its original prototype restrictions explicitly labelled. + +The [plasma tests](../../tools/harness/tests/test_plasma_lighting.py) +and related falloff, occlusion and emitter harnesses are evidence about +specific contracts. They do not establish visual quality across all maps. + +For the held Needler, read `needler_falloff_factor` and +`ammo_counter_falloff_texture` in +[ammo_counter_falloff.c](../../port/linux/game/ammo_counter_falloff.c), then +`field_texture` in [plasma_occlusion.c](../../port/linux/game/plasma_occlusion.c). +The mask is radial around the needles; only its downward reach is restricted. +The analytical fade and its filtered texture differ near the lower boundary: +linear filtering mixes adjacent samples, and specular lighting uses a larger +volume. The [visibility harness](../../tools/harness/tests/plasma_occlusion.c) +therefore checks interpolated texture values at crouched-player and short-NPC +foot heights as well as the scalar function. The +[visual acceptance record](../dynamic_lighting_acceptance.md) separates the +real captures from those synthetic checks. Muzzle collision blocking is +automatic with muzzle lighting; the separate Light Occlusion toggle controls +projectile and emitter blocking. + +The AR display uses `ammo_counter_lighting_screen` and the paired +`ammo_counter_lighting_draw_begin` / `ammo_counter_lighting_draw_end` helpers in +[ammo_counter_lighting.c](../../port/linux/game/ammo_counter_lighting.c). +`_rasterizer_model_draw` calls them around the display draw: first- and third-person +RGB is doubled before fog and the exact output state is then restored. Both +models share the same emissive floor; their separate spill strengths are unchanged. +This narrow shared hook is +needed because a feature-owned point light cannot brighten the screen's own +material or bracket its draw. The setting and exact material identity guard +the change; the [emitter guide](../covenant_emitter_lighting.md) describes the +separate per-view spill gain and map cleanup. + +Visibility history is translated and uniformly scaled between fields. +`field_for` prepares sixteen interpolation coordinates per axis, then shares +them across the 4096 cells; the sample weights, accumulation order and fallback +outside the previous field stay unchanged. This reduces repeated arithmetic +without changing ray count, field resolution, refresh policy or fading. +`field_texture` also shares the diffuse/specular upload when their radii are +exactly equal: the attenuation, visibility and directional texels are identical. +Different specular extents continue to use independent textures. + +The 1536 rays in each refresh share one synchronous batch in +[plasma_collision.c](../../port/linux/game/plasma_collision.c). +`plasma_collision_begin` accepts only the field's exact scenery/machine flags, +optionally including vehicles. `plasma_collision_depth` uses the existing +structure BSP and collision-model intersection routines, caching cluster +membership, object eligibility/bounds and model instances within that batch. +For example, a Warthog flash still tests the chassis on every ray; it avoids +fetching the same chassis metadata repeatedly. Parent sphere/eligibility tests +still gate children, and siblings remain independent. These are depth-only +queries, so unused material, plane and location results are not constructed. + +The cache is bounded at 512 object records and 4096 cluster references. A full +cache, unsupported flags or a malformed leaf uses `collision_test_vector`; +borrowed model pointers are cleared by `plasma_collision_end`. Nothing is reused +across rendered poses, simulation ticks or maps. Disabled lighting never starts +a batch. This changes no shared collision implementation or map-loading path. +The [batch harness](../../tools/harness/tests/test_plasma_collision.py) covers +ownership, traversal and fallback. Test builders' `--verify-traces` mode compares +every depth with the original engine query and times complete batches against +the same pose; its doubled workload is excluded from FPS acceptance. +The [collision and memory follow-up](../dynamic_lighting_tracing.md) records +the measurements, real-engine comparisons and remaining acceptance limits. + +For enhanced model draws only, `plasma_occlusion_model_initialize` in +[plasma_occlusion_gl.c](../../port/linux/src/plasma_occlusion_gl.c) resolves +uniform locations while the linked program is current. Its small record belongs +to `program_entry` in the GL backend, so recycled GL names cannot reuse stale +locations. `plasma_occlusion_bind_model` uses those locations and an immutable +linear/clamped sampler on reserved units 6/7. The sampler and white fallback +texture have GL-context lifetime, like the existing shader-program cache; +per-light field textures are still released by `plasma_occlusion_reset`. +These context resources are created only after an enhanced draw needs them; +disabled draws neither create nor bind them. The backend owns variant selection, +shader linking and this feature-owned binding record, which the game module +cannot manage through its light-selection hooks alone. +Xbox, CE and MCC use the same existing feature hooks, with no loader changes. +See the [performance follow-up](../dynamic_lighting_optimisation.md) for +measurements and the limits of GPU timing versus sustained frame pacing. + +For focused Windows stall investigation, +[lighting_performance_build.py](../../tools/lighting_performance_build.py) +adds test-only `--stalls` thread CPU and compile/link clocks; `--resources` +counts retained renderer entries. The runner's `--no-captures` removes image +allocation/readback and keeps every measured frame in pacing results. +[The stability report](../dynamic_lighting_stability.md#focused-stall-and-memory-investigation) +separates observed shader warm-up hitches from unresolved memory ownership +and the unreproduced long stalls. These tools restore production sources; +their diagnostic timings are not clean performance acceptance measurements. +The [Windows hitch investigation](../windows_stutter_investigation.md) records +the correction for direct desktop program links and the limits of the CE +and Digsite MCC runtime measurements; shader-link stalls alone do not establish +the reported GulchCE/OpenCE difference. +The [renderer preparation walkthrough](../render_preparation.md) follows the +optional shader recipes and material selection, separate bounded Xbox/CE and +MCC texture preparation, dead alpha-combiner normalization and the draw-local +honeycomb variant. It distinguishes repeat-visit coverage from first-use work +that remains during gameplay, and identifies the GLES no-op boundaries. + +The [shield-lighting walkthrough](shield_lighting.md) describes Shield Glow's +integration with the same falloff, specular and visibility services. Its +surface animation remains in `overshield_effect.c`; the host policy still +owns activation, and the light module never changes shield vitality. + +## Vulkan branch notes + +The optional renderer on `vulkan-renderer` has dedicated state in +[vulkan_game.c](https://github.com/chestahh/GulchCE/blob/vulkan-renderer/port/linux/src/vulkan/vulkan_game.c), +scene resources and submission in +[vulkan_scene.c](https://github.com/chestahh/GulchCE/blob/vulkan-renderer/port/linux/src/vulkan/vulkan_scene.c), +and separate window/presentation ownership. Guarded D3D8 dispatch hooks +route the enabled feature to that implementation. It reuses pure shader +translation interfaces, adapts GLSL bindings and compiles SPIR-V; it does +not need an OpenGL context to render the native scene. + +Its completion fences govern reuse of upload, descriptor and query slots. +A busy slot can defer a frame rather than overwrite data the GPU still +uses. Teardown must retire references before map storage is reused. These +are ownership rules, not merely performance choices. + +The branch's [renderer reference](https://github.com/chestahh/GulchCE/blob/vulkan-renderer/docs/vulkan_renderer.md) +describes an experimental native scene milestone. OpenGL remains the +default. Full settings and rendering parity are not established; MCC +resources are outside the milestone's supported boundary, and CE requires +separate Vulkan validation. The +[scene tests](https://github.com/chestahh/GulchCE/blob/vulkan-renderer/tools/test_vulkan_scene.py) +cover specific resource and draw contracts. They are not a blanket +compatibility claim for the renderer or every GPU. + +## Evidence and next steps + +The engine supplies cameras, visibility, draw ordering and Xbox-style +rasterizer calls. OpenCE supplies the shared GL translation and port +features; the two experimental branches add dedicated GulchCE rendering +work. The branch links above intentionally point outside the current +checkout when those files are absent here. + +This chapter records source and reference inspection, not new captures, +benchmarks or GPU test runs. To investigate a rendering change, distinguish +wrong simulation state, wrong rendered pose, culling, shader translation +and stale GPU resources. Check a real image as well as relevant tests, and +record the backend, platform, map, settings and view layout. + +## MCC weapon particle streams + +Ruby Rebalanced's flamethrower authors different particle systems for its +first-person and world-model barrels. Start at `particle_system_new_particles` +and `particle_system_render` in +[particle_systems.c](../../source/effects/particle_systems.c), then read +`mcc_particle_system_markers` and `mcc_particle_system_visible` in +[mcc_particles.c](../../port/linux/game/mcc_particles.c). The first chooses the +local viewmodel marker for first-person-only streams; the second checks the +authored view exclusions for each rendered player. The native Xbox and CE +paths pass through unchanged when MCC is inactive. The adapter owns no +persistent state, and the engine retains particle lifetime and map cleanup. +See the [MCC evidence and regression checks](../mcc_maps.md#flamethrower-particle-system-views-issue-33) +for the inspected flags, reproduction and validation limits. + +Continue with [networking](networking.md), or return to the [guide](README.md). diff --git a/docs/reading/reversed_depth.md b/docs/reading/reversed_depth.md new file mode 100644 index 0000000000..21e021a483 --- /dev/null +++ b/docs/reading/reversed_depth.md @@ -0,0 +1,89 @@ +# Depth precision and decals + +OpenCE's reversed-depth implementation (#495) improves the separation of +nearby surfaces at a distance. GulchCE keeps `display.reversed_depth = true` +on desktop. Set it to `false` and restart to use the Xbox-style 24-bit depth +path. Android and web keep their existing conventional depth path. + +A depth buffer stores the depth of the visible surface at each pixel. +Conventional depth grows toward the far plane; reversed depth grows toward +the camera. Floating-point storage has finer steps near zero, so reversing +depth improves distant precision. This does not remove all floating-point +error or guarantee separation at every distance. + +## Reading route + +1. [port_config.c](../../port/linux/src/port_config.c) declares the default, + desktop scope and `HALO_REVERSED_DEPTH` override. In + [d3d8_gl.c](../../port/linux/src/d3d8_gl.c), context creation reads it once; + the startup log records the selected depth format. +2. `render_target_get` chooses `GL_DEPTH32F_STENCIL8` for reversed depth and + `GL_DEPTH24_STENCIL8` otherwise. The renderer reverses depth comparison, + clears and viewport ranges together. Read `apply_raster_state` and + `D3DDevice_Clear` alongside this allocation. +3. [nv2a_vsh.c](../../port/linux/src/nv2a_vsh.c), + `reversed_depth_instruction` and `nv2a_vertex_shader_to_glsl`, recognizes + compatible projection rows. It subtracts the rows before transforming + the position, avoiding loss of distant precision from subtracting two + already rounded clip coordinates. Unrecognized programs fall back to + subtracting clip z from w. `nv2a_fixed_function_glsl` handles positions + already transformed by the CPU, including the loading screen. +4. In `d3d8_gl.c`, `prepare_draw` carries + the enabled state and polygon offset into the cached `depth_bias` + uniform. Both translated and fixed-function vertex shaders apply it. + The disabled state supplies zero, including after a biased draw. + +## Why decals need a separate bias + +A decal sits on another surface. A small bias moves its depth toward the +camera so it remains visible. OpenCE #540 retains the Xbox's constant bias +units when using floating-point depth: a hardware floating-point polygon +offset would otherwise become much smaller at a distance. The vertex +shader adds the constant term, and hardware polygon offset retains the +slope term (the contribution from the surface's angle). + +For example, a bias of eight 24-bit units moves window depth by +`8 / 16777215` toward the camera. The uniform divides by the viewport's +depth scale; the later viewport transformation cancels that scale. +A zero-width viewport range produces zero bias instead of division by zero. +The slope term scales with the render target relative to the game's +480-line view, on both depth paths, including supersampling. + +The vertex correction precedes clipping. Geometry within the bias distance +of a clip plane can therefore behave differently from a hardware-only +offset. Fragment programs that write their own depth, such as `DOT_ZW` +effects in [nv2a_psh.c](../../port/linux/src/nv2a_psh.c), override interpolated +vertex depth and retain their existing conversion. These are limits to +test when investigating a particular effect, not promises that every +shader has identical precision. + +## Ownership and checks + +These changes belong to the existing shared OpenGL backend: target format, +shader emission and render-state translation cannot be implemented in an +independent game feature module. They do not change map loading or route +Xbox and CE data through MCC adapters. No simulation or network packet +changes are involved. The existing MCC environment emitter, optional model +lighting and shield-honeycomb uniforms retain their ownership and guards. +In particular, the draw cache includes both honeycomb and depth-bias inputs. + +The setting is fixed for a graphics context's lifetime; changing the config +requires a restart. Render targets and shader programs use that context's +mode. Ordinary map transitions continue through the existing resource +cleanup, without a new per-map depth setting or feature state. + +[test_reversed_depth.py](../../tools/test_reversed_depth.py) exercises the +production bias calculations, viewport ranges, render scales and fixed-function +shader generation. With `HALO_TEST_GPU=1`, GLFW and PyOpenGL installed, it +uses a hidden OpenGL 4.5 context to compile the 67 stock vertex programs +with depth and lighting variations, and checks depth readback, bias removal +and 4x MSAA resolves in both formats. Transform feedback (reading the vertex +shader's output directly) checks closely spaced surfaces through 1,000 world +units using the production projection program. +[test_plasma_model_shader.py](../../tools/harness/tests/test_plasma_model_shader.py) +checks the production translations for desktop, Android and web with +dynamic lighting enabled and disabled. These tests supplement game captures; +they do not establish visual compatibility across every map, GPU or effect. + +The [integration validation record](../reversed_depth_validation.md) separates +the November 2026 build, GPU and game results from checks that remain unavailable. diff --git a/docs/reading/settings_input_and_menus.md b/docs/reading/settings_input_and_menus.md new file mode 100644 index 0000000000..5c390230de --- /dev/null +++ b/docs/reading/settings_input_and_menus.md @@ -0,0 +1,235 @@ +# From a setting or input to an action + +This chapter follows two related paths: saving a menu setting, and pushing +a controller stick forward in a local game. The setting path changes a +stored preference; the input path produces an action for the current player. +Read [startup and the loop](startup_and_loop.md) first to place both in time. + +## Reading route + +| Order | Source and names to find | What to follow | +| --- | --- | --- | +| 1 | [port_config.c](../../port/linux/src/port_config.c): `config_settings`, `config_load`, `config_value`, `config_write`, `config_changes` | Definition, loading, reading and changing a port setting. | +| 2 | [port_settings.py](../../tools/port_settings.py): `SCREENS`; [menu_functions.c](../../port/linux/game/menu_functions.c): `pc_menu_event_function_invoke`, `setting_changed_save`, `setting_write` | Generated choices and their runtime callbacks. | +| 3 | [xinput_sdl.c](../../port/linux/src/xinput_sdl.c): `XInputGetState`, `halo_linux_mouse_look` | Device input presented to the game. | +| 4 | [input_xbox.c](../../source/input/input_xbox.c): `input_update`, `input_frame_begin`; [input_abstraction.c](../../source/input/input_abstraction.c): `input_abstraction_update` | Raw controller state becoming game controls. | +| 5 | [player_control.c](../../source/game/player_control.c): `get_local_player_input_blob`, `player_control_update` | Movement, facing and buttons for a local player. | +| 6 | [players.c](../../source/game/players.c): `players_update_before_game`; [units.c](../../source/units/units.c): `unit_control` | Applying an action to the player's unit. | + +## Settings have a definition and consumers + +Each port setting has a name, type, default, environment-variable mapping, +platform applicability and explanatory text in `config_settings`. Loading +starts with defaults, reads configuration-file values and applies supported +environment overrides. `config_value` triggers the initial load under a +lock and checks that the requested name and type match a defined setting. + +Reading a setting is not the same as applying its effects. For example, +FOV code reads a real value, converts it and retains the converted result +until `config_changes()` advances. Another consumer may need a restart or +an explicit resource reload. Inspect the consumer before assuming a newly +saved value takes effect in the same way everywhere. + +The [FOV walkthrough](field_of_view.md) traces a complete example. Its +setting changes memory through `config_write`, attempts persistence in +`config.toml` and advances the change count. A failed file write is not +proof that the in-memory value stayed unchanged. Likewise, editing the +file externally is not evidence that every consumer watches it live. + +## Menu data selects a runtime operation + +The opt-in [modern Settings frontend](menu_redesign.md) uses a separate +frontend parse and root selector. It leaves gameplay's `display.menus` +policy and MCC pause ownership intact; switching occurs only at the main menu. + +The menu XML describes widgets and event names. It is produced by +[ce_menus.py](../../tools/ce_menus.py) and `port_settings.py`; use the +[menu asset reference](../../port/assets/menus/README.md) for regeneration. +[menu_tags.c](../../port/linux/game/menu_tags.c) connects the port's menu +assets to runtime tags, while `menu_functions.c` implements named callbacks. + +For a settings spinner, `setting_changed_save` ignores invalid or unchanged +selections, then passes the chosen text value to `setting_write`. Names +starting with `profile.` take the player-profile path. Other names, such +as `display.fov`, go to `config_write`. This distinction is why controller +preferences and global display settings need not be stored in the same file. + +When a button appears to do nothing, trace its event name into +`pc_menu_event_function_invoke` before changing its appearance. The existing +[unwired-function list](../../port/assets/menus/UNWIRED.md) records known +gaps. A visible widget alone does not establish that its action is implemented. + +Stock/OpenCE-style settings expose **Network Setup > Map Sharing** on desktop, +Android and web. Classic PC and Xbox-style settings reuse those services; +Modern exposes the same controls under **Online > Map Sharing**. Its +**Controls > Stick Dead Zones** and **Online > Discord Account** actions open +the existing Stock editors through `frontend_editor`; those editors save with +their own OK buttons, while pending Modern settings remain pending. Account +changes stay unavailable during gameplay, matching Stock's restrictions. +`test_modern_settings_match_stock_functionality` compares reachable setting +bindings on desktop, Android and web; callback tests also cover pending edits +and the in-game restriction. These optional frontend routes are Gulch-specific. +The sharing page +includes client downloads, host MCC sharing, package settings and downloaded-copy +management. Steam discovery alone is desktop-only. The Stock route is generated +by `port_settings.settings_files` and loaded by `halo_menus_load` without the +optional frontend asset set; `frontend_menu.document` supplies the separate +Modern route. `test_stock_network_menu_reaches_sharing` and +`test_modern_network_menu_reaches_sharing` traverse platform-visible widgets, +including their links, rather than checking that a hidden definition exists. + +MCC's manual-download prompt uses the normal `main_goto_main_menu` route when +dismissed. It does not choose a PC, Xbox or Modern root itself. Live consent +still returns to its current lobby; see [MCC sharing](maps_and_resources.md#mcc-package-sharing-between-machines). + +[MCC level previews](mcc_level_previews.md) follows package metadata into a +bounded image reader, the menu texture cache and style-specific thumbnail +rectangles. It also explains wrapping of MCC titles and descriptions without +changing the Xbox or Custom Edition text paths. + +## Follow the forward stick + +[Controller button remapping](controller_remapping.md) adds a Gamepad Setup +submenu with independent P1-P4 layouts. It transforms physical button input +before keyboard/touch merging, while leaving menu navigation and stick axes intact. + +On the normal controller path, the SDL-backed `XInputGetState` supplies the +Xbox-shaped state consumed by `input_xbox.c`. `input_abstraction_update` +uses the local player's control preferences to translate stick positions +and buttons into `game_input_state`: forward movement, strafe, yaw, pitch +and named controls. + +`get_local_player_input_blob` starts with a cleared action and resolves the +local player and device. Among its operations, it copies +`input_state->forward_movement` and `input_state->strafe` into the action's +throttle. It handles look rates and control conditions as well. The +player-control and update-queue machinery then supplies actions to the +simulation; `players_update_before_game` prepares `unit_control_data` and +calls `unit_control` for the player's unit when control is allowed. + +```mermaid +flowchart LR + A[Controller state] --> B[Input abstraction and preferences] + B --> C[Local player action] + C --> D[Simulation action queues] + D --> E[Player-to-unit control] + E --> F[Object simulation] +``` + +The stick does not directly assign a world position. Unit and object logic +interpret the control using movement rules, collision and current state. +A player with no unit, a paused menu, an inhibited control state or a network +role can change which parts of this route are active. + +## Keyboard, mouse and text have distinct routes + +Android gyro settings live in [touch_gyro.c](../../port/linux/src/touch_gyro.c). +`touch_gyro_mode` preserves the saved Android layout in the default `legacy` +mode; explicit on/zoom modes use independent sensitivity and inversion. +`TouchControls.nativeGyroMode` reads that selection through +[host_touch.c](../../port/android/host/host_touch.c). `halo_linux_touch_look` +consumes swipe and gyro separately, then `touch_gyro_apply` scales only gyro. +`get_local_player_input_blob` supplies the player's zoom state to +`halo_linux_gyro_filter`: a turn made while unzoomed in zoom-only mode is +discarded before conversion to a player action. This small engine hook is +needed because the platform input layer does not own player zoom state. +No action format or simulation rule changes, and the functions leave desktop +and web input untouched. The Android view resets sensor timing across mode, +visibility and app lifecycle transitions. The [gyro harness](../../tools/harness/tests/test_touch_gyro.py) +checks default behavior, independent axes, invalid sensitivity and zoom +transitions; physical-device aiming and lifecycle checks remain necessary. + +The opening comment in `xinput_sdl.c` is particularly useful. During +gameplay, keyboard bindings produce named actions rather than pretending +to press all the controller buttons. During menus, navigation keys do map +to controller-like navigation. Mouse aim supplies accumulated motion through +`halo_linux_mouse_look` instead of becoming a right-stick turning rate. + +That mouse function consumes pending motion and clears it under a lock. +This is a small ownership example: reading a delta may consume it, whereas +reading a held button is a state query. Calling the former twice can have +different results even within one frame. + +Console input, chat text, menu text boxes and gameplay bindings also have +different capture rules. Investigating "Escape did the wrong thing" starts +with the active input context. It does not start with globally changing the +key's meaning. Split-screen controller indices and local-player indices +must remain associated with the intended player. + +## MCC pause menus + +MCC uses its own pause widgets so an authored map cannot replace the native +pause actions. Read [mcc_pause.c](../../port/linux/game/mcc_pause.c), starting +with `mcc_pause_screen`, `mcc_pause_dialog` and `mcc_pause_key`. Their Xbox +reference layouts include OpenCE's Settings and co-op Friendly Fire entries. +For example, Revert opens ATTENTION with B=CANCEL and A=OK; confirmation +reaches `mcc_ui_event_function` in [mcc_ui.c](../../port/linux/game/mcc_ui.c), +which checks host authority and checkpoint validity before reverting. + +[mcc_pause_runtime.c](../../port/linux/game/mcc_pause_runtime.c) appends an +owned tag table only after construction succeeds. `mcc_pause_borrow_art` +selects the port's existing panel and alert redraws without modifying their +original groups or textures. The glyphs use embedded small menu-button +redraws, not the MCC map's gameplay icons. Teardown releases MCC allocations +first and leaves borrowed textures for their native owner. Xbox and Custom +Edition retain their existing pause builders and action routes. + +The focused checks are [test_mcc_pause.py](../../tools/test_mcc_pause.py), +[test_mcc_pause_runtime.py](../../tools/test_mcc_pause_runtime.py) and +[test_mcc_ui.py](../../tools/test_mcc_ui.py). They cover layout and actions, +failed construction, resource ownership, controller cleanup and client +refusal. Real screenshots and host/client menu interaction are still needed +to verify presentation and navigation. See [MCC pause behavior](../mcc_maps.md#in-game-pause-menus) +for context-specific choices and split-screen limitations. + +## Evidence and useful checks + +On `dynamic-lighting-test`, Video Setup's Dynamic Lighting screen exposes +eight independent, default-off settings. Its rows come from +`SCREENS["video_settings/dynamic_lighting"]` in +[port_settings.py](../../tools/port_settings.py). `setting_load` reads the +saved values; `setting_changed_save` writes only changed values on OK. +Defaults changes the pending spinner selections, so Cancel still discards +those changes. Restarting reads the saved configuration again. Portable +builds keep `config.toml` beside the executable, independently of the map +data root; acceptance runners must isolate both locations. + +`settings_help` also reconnects a generated setting row to its spinner when +its descendant focus was cleared by a pointer focus change. Without this, +returning to the row with the d-pad could show the correct help but ignore +left/right input. The repair uses existing setting metadata and preserves +an already-focused child and ordinary button navigation. It stays in the +port's settings handler; Xbox widget focus semantics are unchanged. +[test_settings_focus.py](../../tools/harness/tests/test_settings_focus.py) +exercises that route and a negative control with the repair removed. + +The inherited game provides control abstraction, profiles, widgets and unit +control. The port provides SDL input, keyboard actions, configuration and +generated menu integration. GulchCE features add their own settings and +callbacks within those boundaries. + +[test_button_presets.py](../../tools/harness/tests/test_button_presets.py) +extracts the actual profile-to-control mapping and checks layouts, unknown +preset fallback and deliberately faulty variants. +[test_profile_keyboard.py](../../tools/harness/tests/test_profile_keyboard.py) +checks virtual-keyboard input and cleanup when creating a profile. These +tests do not prove that a real device, focus transition or menu layout works +on every platform. +They were inspected, not run, for this chapter. + +For an input change, check holding and releasing the control across gameplay, +menus and text entry, then check a second local player. For a setting change, +check default loading, save failure, reload and the actual consumer. Keep +generated XML changes tied to the intended generator change. + +Shield Glow and Glow Intensity now live in Dynamic Lighting; their saved keys +and host policy are unchanged. Animated Overshield remains in Extra Effects. +The [shield-lighting guide](shield_lighting.md) explains the distinction between +saved local preferences and effective host-selected state. Defaults restores +OFF for light toggles and DEFAULT for intensity; it does not override a host. + +Continue with [objects and gameplay](objects_and_gameplay.md), or return to +the [guide](README.md). + +For the optional AUTO BUTTON DETECTION setting and independent manual/family +preferences, see [controller detection and button styles](controller_buttons.md). diff --git a/docs/reading/shield_lighting.md b/docs/reading/shield_lighting.md new file mode 100644 index 0000000000..8229b19c44 --- /dev/null +++ b/docs/reading/shield_lighting.md @@ -0,0 +1,98 @@ +# Shield Glow and animated Overshield + +Shield Glow adds soft radial illumination to a unit's visible shield. It uses +its selected Shield Look, authored colour channels and animated overshield +layer. Animated Overshield still owns the rising surface and first-person arm +animation; it does not require Shield Glow. Neither feature changes vitality, +damage, tags, projectile responses or map-family loading. + +Both switches default off. Shield Glow and Glow Intensity are in Video Setup > +Dynamic Lighting; Animated Overshield remains in Extra Effects. Existing saved +keys are retained. The inherited `network.shield_effects` policy is authoritative +online: stock suppresses both, the glow/overshield combinations select them, and +players delegates to local preferences. No packet or protocol version changes. +Light Occlusion remains a local rendering preference, as for the other emitters. + +Android excludes Shield Glow with the rest of the optional lighting renderer, +even if a host requests glow. The host's transmitted policy is unchanged and +still controls Animated Overshield surfaces. The +[Android replacement](../../port/android/guest/dynamic_lighting_disabled.c) +retains `shield_glow_reset`'s call to `overshield_effect_reset`, so surface state +does not survive map/light-array replacement. See the +[Android lighting boundary](../../port/android/README.md#lighting-availability). + +## Reading route + +1. [network_shield_effects.c](../../port/linux/game/network_shield_effects.c), + `network_shield_effects`, resolves the existing host policy. +2. [overshield_effect.c](../../port/linux/game/overshield_effect.c), + `overshield_effect_get`, owns the time-based charge state. The body, arms and + `overshield_effect_light_sample` use `overshield_effect_layer_color`: green + above 200% total shield, pink at or below it. `overshield_effect_reset` clears + model-height caches, units and arm pointers on map/light-array boundaries; + effective disable also clears this state. `overshield_effect_find_values` + matches queued body/arm draws for both colour and height fading. Colour + lookup does not compute unused fade parameters or scan the effect list twice. +3. [shield_glow.c](../../port/linux/game/shield_glow.c), `shield_glow_sample`, + resolves the same selected shader and colour rules as the surface. Normal + flares use its evaluated intensity source/exponent and the selected recharge + envelope. Overshields use visible charge coverage and the shared layer hue. + A dark authored colour stays dark; only overbright colours are normalized. +4. `shield_glow_update` selects at most eight candidates by strength, radius and + distance from the nearest local camera. Existing lights receive a 20% score + bonus to resist churn. New lights preserve short hits; existing lights use + 15 ms attack and 80 ms release time constants. Admission and release use + separate small thresholds. Selection fades over the last three units of the + 25-unit range. This is a bounded approximation, not a global light allocator. +5. [plasma_lighting.c](../../port/linux/game/plasma_lighting.c) registers shield + light identities for the existing world/model attenuation and coloured + specular paths. [plasma_occlusion.c](../../port/linux/game/plasma_occlusion.c) + admits them to the existing eight-field collision budget when enabled. + +For example, an animated green overshield with Shield Glow enabled produces a +green radial light. As its charge rises, the light centre rises from the lower +body towards its middle and its contribution grows. Dropping to the inner layer +turns both the surface and emitted light pink. Disabling only Shield Glow removes +that added illumination while leaving the animated surface active. + +## Ownership and limits + +Rendered skeleton heights place the radial source and scale its reach. Crouching +lowers its centre and reduces its radius. This approximates a luminous body with +one point source: it is not mesh-based area lighting, an AR-style cone, or precise +self-shadowing. Some illumination of nearby ground is physically appropriate. + +The light module owns light handles; it disconnects and blacks them after each +render frame, deletes them on disable or loss of eligibility, and forgets handles +when light storage is reset. Repeated split-screen views at one game time do not +advance the smoothing. Clock rollback releases lights before reselection. + +The only additional engine wiring is in +[object_lights.c](../../source/objects/object_lights.c): shield-owned radius bounds +must participate in visibility partitioning, and shutdown must forget shield +state. These private light-storage operations cannot live solely in a feature +module. Existing map-reset hooks also reset overshield state. Xbox, Custom Edition +and MCC continue using their existing loaders and rendering services. + +Light Show retains its saved meaning: three times the radius and full intensity +from a third of the flare. The ordinary setting does not multiply radius by hit +strength, avoiding a rapidly expanding luminous edge. Stock light-template flags, +including no-specular, remain authoritative. Occlusion is the same filtered +collision approximation as other dynamic lights, with bounded capacity and +possible leakage; it is not CStencil or Modern. + +## Checks + +[test_shield_lighting.py](../../tools/harness/tests/test_shield_lighting.py) compiles the actual +module against a synthetic world: host override, selected colours, camouflage, +body placement, 30/60/120 Hz release equivalence, selection and cleanup. The +overshield rendering test checks shared layer hues and model-cache reset. +The plasma lighting/occlusion harnesses cover shield-only activation and cleanup. +Menu checks verify generated ownership, saved keys and the ten-row layout. + +Runtime evidence and its limits are recorded in the +[Milestone 2 acceptance record](../dynamic_lighting_acceptance.md). Synthetic +checks do not establish appearance on every map, GPU or platform. +The [Milestone 4 compatibility record](../dynamic_lighting_compatibility.md) +adds mixed-setting multiplayer checks for Xbox, CE and MCC, including received +host policy, respawns, weapon changes and late joining. diff --git a/docs/reading/startup_and_loop.md b/docs/reading/startup_and_loop.md new file mode 100644 index 0000000000..006c520638 --- /dev/null +++ b/docs/reading/startup_and_loop.md @@ -0,0 +1,137 @@ +# From launch to a running game + +Start here for the order in which the major systems run. The example is +launching a desktop build, reaching the menu and starting a local map. +Networking and platform-specific startup add steps, covered in the +[networking](networking.md) and [platforms and testing](platforms_and_testing.md) +chapters. See the [glossary](glossary.md) for tick, frame and lifecycle. + +## Reading route + +| Order | Source and names to find | Question it answers | +| --- | --- | --- | +| 1 | [shell_xbox.c](../../source/shell/shell_xbox.c): `main` | Where does the shared game begin? | +| 2 | [shell.c](../../source/shell/shell.c): `shell_initialize`, `shell_dispose` | Which services must exist before the loop? | +| 3 | [main.c](../../source/main/main.c): `main_loop`, `main_change_map_name`, `main_new_map` | How do menu requests become map transitions? | +| 4 | [game.c](../../source/game/game.c): `game_load`, `game_initialize_for_new_map`, `game_tick`, `game_dispose_from_old_map` | What belongs to a game or to one loaded map? | +| 5 | [game_time.c](../../source/game/game_time.c): `game_time_update` | How many simulation steps are due? | +| 6 | [render_interpolation.c](../../port/linux/game/render_interpolation.c): `render_interpolation_tick`, `render_interpolation_frame_begin`, `render_interpolation_frame_end` | How can drawing happen between those steps? | + +## Startup establishes the services + +The name `shell_xbox.c` reflects the engine's origin. The native port still +uses its game entry point, while the platform layer implements the Xbox +calls it makes. Begin at `main`; some historical helper names near it are +colourful but are not feature names you need to learn first. + +The entry point prepares memory, then calls `shell_initialize`. That function +initializes the basic runtime and platform, opens tag-file services, prepares +maths and game-state storage, and initializes the rasterizer. Input and sound +initialization follow a successful rasterizer initialization. The return +value determines whether the entry point proceeds to `main_loop`. + +This is a useful ownership distinction: allocating the game's memory and +opening its services does not mean a playable level is loaded. There are +process-lifetime services, per-map state, and per-frame temporary state. +Reading only the startup function would miss the latter two. + +## A menu request is handled by the loop + +`main_loop` initializes console, debug-key and game systems, sets up the +connection and clock, and requests the main menu. At the top of its loop, +it handles pending operations such as map changes, saves, reverts, respawns +and returns to the menu. These flags let an action request a transition +without doing all its work on the caller's stack. + +For the local example, `main_change_map_name` handles the menu fade and +constructs `game_options` with a map name and difficulty. Its local path +disposes the old map's game systems, precaches the requested map, unloads +the old scenario and calls `main_new_map`. That function flushes input, +calls `game_load`, initializes the new map on success, creates local +players and starts game time when errors permit. It also resets pending +transition flags. Follow [maps and resources](maps_and_resources.md) for +what `game_load` does with the map name. + +The main menu itself is a scenario with a rendered scene. Consequently, +"a scenario is loaded" and "the player is in a playable match" are different +conditions. Guards such as `game_in_progress`, `game_engine_running` and +`main_menu_is_loaded` should be read at the call site rather than treated +as synonyms. Here, `game_engine_running` refers to the gametype machinery, +not simply to the application running. + +## A frame can contain zero, one or several ticks + +The following is a simplified dependency order for an active iteration; +pause state, connection type and pending transitions select different paths. + +```mermaid +flowchart TD + A[Handle pending transitions] --> B[Sample input and process events] + B --> C[Network frame work and elapsed time] + C --> D[Menus and local player controls] + D --> E[game_time_update] + E --> F[Run due game_tick calls and save render snapshots] + F --> G[Update camera systems] + G --> H[Draw an interpolated frame when allowed] + H --> I[Present and finish the iteration] + I --> A +``` + +`game_time_update` adds elapsed seconds to leftover time, converts that +total into whole ticks at the current game speed, and retains the fraction. +It also bounds catch-up work and accounts for connection state. When a tick +is permitted, it calls `game_tick` and then `render_interpolation_tick`. + +For intuition, a display at 120 frames per second has roughly four frame +intervals per normal 30 Hz tick. That is not a promise that every fourth +iteration ticks: timing, loading, pauses and speed changes affect scheduling. +The important consequence is that a frame with no tick must report no new +simulation time. `last_local_time_elapsed` is cleared before the calculation +so HUD timers and similar frame-side consumers do not reuse the last tick's +elapsed count repeatedly. + +## What a tick advances + +Read `game_tick` as an ordered list of responsibilities. It updates units, +AI or host-driven actors, players before gameplay, effects, first-person +weapons, the gametype, scripts where allowed, objects, players after +gameplay, and HUD/player effects. The exact ordering is executable code; +the list here is a route through it, not permission to reorder systems. + +Only the host runs AI for a distributed game. In network co-op, clients +also skip the host's script execution. Those conditions explain why a +function that exists in every build is not necessarily executed by every +machine. The [gameplay](objects_and_gameplay.md) chapter follows a player's +unit through this machinery. + +Drawing is separately bracketed by `render_interpolation_frame_begin` and +`render_interpolation_frame_end`. The interpolation module keeps tick +snapshots and blends poses for drawing, with discontinuity handling for +teleports, respawns and camera cuts. Its opening comment explains the +normal one-tick presentation delay. Camera responsiveness features should +be read separately from the simulation clock. + +## Lifetime and evidence + +The inherited engine supplies the shell, scenario lifecycle, game loop and +tick structure. The port adds interpolation, platform scheduling, network +work and guarded feature integration. GulchCE's MCC speed handling appears +in `game_time_update`; it is an explicit boundary, not a reason to treat all +maps as MCC maps. + +On the web, `main_loop_web_frame` calls `main_loop_iteration` through +Emscripten. On native builds, preprocessor branches retain the loop inside +`main_loop`. A search result for `main_loop_iteration` alone therefore does +not describe every build's call stack. + +This chapter is based on source inspection. The +[Stagekit walk tests](../../tools/stagekit/tests/test_walk.py) demonstrate +how the real engine's movement can be checked on generated data, while the +[Stagekit reference](../../tools/stagekit/README.md) explains deterministic +replays and their limits. They are not tests of every startup failure or +menu transition, and were not run for this documentation change. For a loop +change, investigate pauses, no-tick frames, catch-up, map transitions and +web callbacks as well as ordinary gameplay. + +Continue with [settings, input and menus](settings_input_and_menus.md), or +return to the [guide](README.md). diff --git a/docs/reading/third_person.md b/docs/reading/third_person.md new file mode 100644 index 0000000000..d2ef541ffd --- /dev/null +++ b/docs/reading/third_person.md @@ -0,0 +1,224 @@ +# Shoulder camera on online-third-person + +This optional GulchCE camera is off by default. A host can instead select +Player Choice (the default), Forced On or Forced Off for the match. The +policy does not overwrite saved player preferences. Stock Xbox, Custom +Edition and MCC loading paths remain separate; MCC weapon-authored following +cameras, vehicle cameras, scripts and cinematics retain their priority. + +Default keyboard controls are **N** for perspective, **B** for shoulder, +and **Left Alt** held for free look. Hold a modifier and scroll to adjust the +camera: **Alt** for distance, **either Shift** for height, or **Caps Lock** for +lateral offset. Wheel up moves closer, higher or right respectively; wheel +down reverses it. Caps Lock must be physically held, regardless of its typing +toggle. These bindings are configurable under Controls Setup > Camera. If +modifiers overlap, distance takes priority, then height, then lateral offset. + +[third_person_input.c](../../port/linux/game/third_person_input.c)'s +`third_person_camera_scroll` uses the menu's existing bounds and saved settings. +Lateral scrolling can cross the centre by changing the existing shoulder +selection while keeping the offset a magnitude; B still mirrors that offset. +At the centre the shoulder selection is retained. Ordinary scrolling switches +weapons. First person (including scope and collision fallback), menus, console, +text chat and released mouse capture do not consume the wheel for adjustments. +Host policy and session compatibility still gate camera availability. +Saved custom bindings are retained. Gamepad Setup > Button Remapping > +Camera Perspective offers Third Person On / Off and Swap Shoulder, both +unbound by default. The Modern frontend exposes the same editor through +Settings > Controls > Controller Remapping. Both actions share the keyboard +camera preferences and obey the existing host/session policy. +No stencil shadows or cosmetic head tracking are part of this consolidation. + +With the optional Modern frontend, Settings > Video > First Person exposes +the perspective setting and a Shoulder Camera page for its adjustments. +Modern Server Setup > Session Options retains the native compatibility and +host-policy callbacks. Both routes are main-menu-only; the existing starting +menus, server browser and gameplay pause menus retain their own presentation. +See the [menu walkthrough](menu_redesign.md) for integration checks and limits. + +## Reading order + +1. [third_person_policy.c](../../port/linux/game/third_person_policy.c): + `third_person_policy` reads the authoritative game record; + `third_person_enabled` combines it with the saved preference. Only a host + creates or edits the match policy. Forced Off clears replicated shoulder + input; scope, seats and death still use their established cameras. +2. [director.c](../../source/camera/director.c): + `director_choose_game_perspective` selects the shoulder callback only for + eligible on-foot play. Passenger display overrides and authored following + cameras are considered first. `director_camera_is` exposes identity + without exposing mutable director state. These small shared hooks are + necessary because the director owns the selected callback privately. +3. [third_person_director.c](../../port/linux/game/third_person_director.c): + `third_person_camera_update` calls the stock first-person eye calculation + with the director's exact callback signature, including on WebAssembly. +4. [third_person.c](../../port/linux/game/third_person.c): + `third_person_camera` resolves the shoulder offset after interpolation, + collision and free-look orbit. `director_get_perspective` reports that + resolved view to body/particle rendering. Hidden viewmodel poses, markers + and sounds continue updating in `first_person_weapons.c` so collision + fallback does not need to reconstruct them. +5. [third_person_weapon.c](../../port/linux/game/third_person_weapon.c): + `third_person_muzzle_shot` and `third_person_muzzle_target` share the + cover-aware muzzle solver. The marker follows authored alternating barrels + and charged secondary triggers. Explicit custom firing rules retain their + existing behavior. Spread, projectile gravity and aim assistance remain + the weapon's own. + +The firing and preview eligibility checks also ask +`director_desired_perspective` before using a shoulder muzzle. A weapon's +authored following camera therefore wins immediately after a switch, even +if the prior rendered frame or a received input still says shoulder view. +The host applies this check independently of the client's input bit. + +## A shot beside cover + +The camera can see around a corner while the weapon remains blocked. The +solver checks the eye-to-barrel segment and the muzzle's firing line, then +projects the reachable target into the displaced camera's reticle. A barrel +inside a wall cannot spawn a projectile beyond it. Free look holds gameplay +aim fixed and hides the reticle until the camera returns. + +For MCC camera-relative triggers, `third_person_muzzle_target` obtains the +nominal ray from [mcc_projectiles.c](../../port/linux/game/mcc_projectiles.c), +as actual firing and `weapon_get_projectile_ray` do, before applying the +shoulder muzzle and cover correction. See the +[projectile investigation and fix](../digsite_projectile_offsets.md). + +On the host, `third_person_muzzle_history` supplies a muzzle computed from +the host's weapon pose to `distributed_note_targets` in +[network_damage.c](../../port/linux/game/network_damage.c). This small hook +is necessary because that module owns hit visibility history. The feature +does not submit client muzzle coordinates or bypass damage validation. The +existing visibility check requires clear eye-to-muzzle and muzzle-to-target +segments. Ownership, rate limits, target history and damage rules still run. +The upstream optional client-hand origins remain separately controlled. + +## Session compatibility + +The [earlier crossplay qualification](third_person_crossplay_qualification.md) +records its tested revisions and menu checks; it does not qualify the current +shared checkpoint agreement. See the +[shared recovery validation record](../mcc_refactor_validation.md#stage-10-shared-checkpoint-recovery-fix) +for the updated contract's checks and limits. + +Host setup keeps its existing layout; **Session Options** opens the +compatibility and camera-policy controls plus the invite link. Moving that +link leaves room for two lines of host-menu help without shrinking the rows. +Both camera rows use the standard menu +font and full-size selection background. The compatibility selector defaults +to Crossplay. + +**Crossplay** (`opence_crossplay`) uses upstream protocol 43 for Xbox, Custom +Edition and MCC maps. The optional shoulder camera, its input bit and muzzle +solver are disabled, regardless of the saved preference. Shared checkpoint +and bounded clock recovery use the upstream agreement in both session modes. +Normal vehicles, scripted cameras and MCC weapon-authored cameras are unchanged. +No additional MCC capability guard or join envelope is needed. + +**GulchCE Only** (`gulchce_third_person`) enables Player Choice / Forced On / +Forced Off and requires camera protocol 32744 for all map families. It uses +bounded join kind 102 around the ordinary join, including account-link +credentials. Nested envelopes are rejected. Camera policy uses bits 4-5, +leaving upstream co-op and vehicle-riding flags in bits 0-3. Forced Off remains +a camera session and requires the same admission proof and relay format. + +Read [third_person_protocol.c](../../port/linux/game/third_person_protocol.c) +next to the policy module. `third_person_session_host_begin` initializes host +state; `third_person_session_set` permits changes during host setup. Opening +the network socket happens before setup and must not lock the selector. +`third_person_session_lock` fixes the mode when the lobby opens, a remote +machine is admitted, or the match starts, and keeps it fixed through subsequent +rounds. The server's create/admission/start/dispose hooks are necessary because +the engine owns admission and server lifetime. Client join +and teardown hooks bind permission to the selected host and clear it at the +connection boundary. Settings validate policy bits against that permission; +settings and personal preferences cannot enable a camera extension themselves. + +For example, a player with third person saved as on joins a Crossplay host: +the ordinary join and relay are used, N cannot enable the shoulder camera, +and the saved preference remains on. Disconnecting clears the session state; +offline play can use that preference again. A matching GulchCE camera host +instead supplies the authoritative camera policy. A stale or unsupported +camera revision is rejected. An OpenCE 41 advertisement is incompatible. + +Internet discovery advertises the shared GulchCE revision. The subsequent +game advertisement and admission establish the map and camera agreements; +a listing is never permission to enable the camera. There is no change to +WebRTC framing or signalling. Separate-computer/WAN checks remain a release +validation requirement, not something established by local two-peer tests. + +## State and checks + +Each local viewport owns its collision, orbit and target state. Map loads and +checkpoint restores call `third_person_reset`; changed units, death, seats, +scope and scripted cameras clear orbit state. A held orbit key must be +released before reacquiring after these transitions. Settings and keyboard +ownership remain shared as documented; two separate processes do not prove +same-process split-screen input independence. + +`network_coop_restore_players` in +[network_coop.c](../../port/linux/game/network_coop.c) preserves the current +host roster when a checkpoint predates a join or departure. The small +[game_state.c](../../source/saved%20games/game_state.c) after-load hook must +run before observer, director and input restoration: those caches need the +live players, rather than the saved membership. This co-op +lifecycle fix runs in all network co-op sessions, independently of camera +preferences or policy. It is not an MCC adapter. +It uses the established player, unit and session interfaces; Xbox, Custom +Edition and MCC discovery/loading remain separate. Clients do not choose +membership or restore a checkpoint themselves. `tools/test_coop_checkpoint.py` +checks departed players, added/reused slots, local viewports, stale machine +handles, invalid roster entries, repeat restores and the non-host guard. +After the restore, `network_distributed_reverted` advances the host's world +epoch, clears pending recovery state and sends a reliable boundary before +`network_objects_host_reverted` immediately sends loaded peers fresh object +descriptions, complete ordinary inventories including empty ones, and an +ordered end marker. This covers objects restored under an old handle without +making clients wait for the normal resynchronization backoff. +Only the host's checkpoint path bypasses the resend interval; client requests +retain their limits. While that snapshot arrives, the client admits its +ordered descriptions and ordinary inventories, suppresses other incoming and +outgoing gameplay, and postpones local inventory and vehicle prediction notes. +Readiness and inventory retries continue. Receipt of the end marker does not +claim that a failed object creation has succeeded. +The first validated marker also retires projectiles, delayed gameplay effects, +queued hits and prediction histories produced during the partial snapshot. +Already applied objects, inventories and receive-time history remain; duplicate +markers do not repeat this cleanup. These lifecycle rules are camera-independent. + +`network_objects_expect_live_unit` in +[network_objects.c](../../port/linux/game/network_objects.c) requests bounded +resynchronization when the host says a co-op unit is alive but the local copy +is dead. `distributed_client_reuses_object` permits reconstruction only for +the first validated description of that slot in the checkpoint epoch. A later +live description cannot resurrect a unit killed in the same epoch; a new +checkpoint renews eligibility. Old-epoch messages cannot mutate the restored +world even when they name the same object handle. These rules apply with +either camera perspective. The +[networking guide](networking.md#authority-also-governs-hits-and-object-lifetime) +explains the ordering, client effect cleanup and the remaining limits of +authored HUD, navigation-point and attachment rollback. The checkpoint tests cover recovery and retry +limits; the [shared recovery validation record](../mcc_refactor_validation.md#stage-10-shared-checkpoint-recovery-fix) +records the checks actually completed for the updated contracts. + +`tools/test_third_person.py` exercises the production camera and muzzle +solver with controlled collision worlds, including near cover, FOV, scope, +free-look release and lifecycle exits. `tools/test_third_person_director.py` +executes director transitions and wheel routing. Camera policy, wire and +admission tests cover host ownership and malformed inputs. The reported-hit +sight and fire-origin harnesses cover visibility and untrusted-origin rules. +`tools/camera_policy_sessions.py` supplies real two-process loopback checks. + +These checks have distinct limits: fake-world tests establish algorithmic +behavior; loopback sessions exercise real simulation and replication but do +not establish public internet connectivity or full campaign compatibility. +Rendered map-family transitions, weapon effects and physical controller or +split-screen interaction need their own runtime evidence. + +The [28 October qualification record](third_person_qualification.md) records +the completed Windows/browser, checkpoint and rendered split-screen checks, +the fixes they exposed, and their remaining coverage limits. + +MCC camera-relative projectile rays use upstream agreement 43 (camera mode 32744). +Xbox/CE agreement versions are unchanged. Firing and preview share `mcc_projectiles.c`. diff --git a/docs/reading/third_person_crossplay_qualification.md b/docs/reading/third_person_crossplay_qualification.md new file mode 100644 index 0000000000..910220cbf4 --- /dev/null +++ b/docs/reading/third_person_crossplay_qualification.md @@ -0,0 +1,85 @@ +# Session compatibility qualification, 1 November 2026 + +This records the `testing` merge and selectable-session work on +`online-third-person`. The merged testing revision is `b8d365fc3`; the final +implementation is `d0d96b2176d84894153b6f6b8d8a88f5be1bef29`. +Read the [camera walkthrough](third_person.md#session-compatibility) for +ownership, admission and the two session modes. + +## Review and menu findings + +The combined review covered the upstream merge, optional relay byte, +advertisements, bounded camera admission, host policy, client teardown, +checkpoint guards, settings and generated menus. The ordinary OpenCE 41 +contract and independent MCC 63 capability remain separate. No stencil +shadows, cosmetic head tracking or camera gamepad bindings were added. + +The real host flow exposed a premature lock: the engine opens its socket +before showing setup. Compatibility now locks at lobby entry, remote +admission or match start. The host's initial loopback admission remains +editable; clients cannot change the mode. Production-function regressions +exercise this distinction and retain the normal admission checks. + +Host setup retains its existing controls. Invite Link moved into Session +Options, leaving room for two help lines above the main footer. Compatibility +and policy use standard row dimensions and fonts. Spinner bounds align the +text with its label and include both clickable arrows. The invite row copies +the complete address while displaying a short action prompt. + +Rendered browser captures at 1280x960 and 1280x720 were inspected. Mouse +clicks changed compatibility in both directions and changed the camera +policy; keyboard navigation also worked. The final widescreen host capture +shows both help lines aligned with the labels and clear of the footer. + +## Runtime evidence + +The final gameplay engine was tested at `8744b631f`; the following +`d0d96b217` change only adjusts generated selector bounds and their test. +Windows used a portable release build; browsers used the matching CI debug +build in headless Edge. Signalling was private and local. + +| Check | Observed result | +| --- | --- | +| Official OpenCE crossplay | Unmodified OpenCE build-337 (`899219cc0a14b03bc12f0517a1e9ee4c37158af8`) hosted GulchCE and joined GulchCE on Xbox Blood Gulch. Both directions passed default simulation tolerances with 45 two-player samples. GulchCE kept its saved camera preference on while enforcing first person. | +| Camera authority and admission | GulchCE Forced On and Forced Off passed with 44-45 samples. An official OpenCE client was refused entry to a camera session even with Forced Off. | +| Windows/browser gameplay | Four Blood Gulch sessions: both host directions in Crossplay and GulchCE Third Person. Each peer logged 45 two-player samples. All four passed the unmodified comparator tolerances and established WebRTC connections. Forced On overrode disabled personal preferences; Crossplay disabled the camera and its muzzle override. | +| Offline split screen | One rendered engine with two local players. Only player 2 scoped; only player 1 used free look and returned on release. Logged aim stayed fixed during free look/release. Turning player 2 afterward changed only that player's aim. Captures were inspected. | + +Earlier focused runs in this assignment additionally covered official +OpenCE crossplay in both directions on CE Death Island, GulchCE Player +Choice, CE camera sessions, and MCC Mercury sessions with different package +folder names. MCC baseline and camera sessions continued after checkpoint +restore. Two Windows a30 camera sessions, Forced On and Forced Off, exercised +three reconnects and repeated checkpoint restores with 80 ms receive +latency and 2% simulated loss. These are opening-session checks, not full +campaign completions. Their evidence remains applicable to the unchanged +gameplay paths; the later setup-lock correction was retested on Xbox and +with the MCC lifecycle/admission fixtures. + +The combat runners combine bot firing with synthetic reported-hit probes, +pickups, deaths and vehicle events. Accepted-hit counts are therefore not +exclusively physical gunfire. Passing the comparator means staying within +its existing tolerances, not zero transient position drift. + +## Automated checks and limits + +The final local regression run passed 131 checks with six platform-dependent +skips. Menu regeneration left the checked-in generated output unchanged. +The [build workflow](https://github.com/chestahh/GulchCE/actions/runs/41359912174) +passed for Linux, Windows, Android and web; the +[MCC workflow](https://github.com/chestahh/GulchCE/actions/runs/41359186563) +passed for the final engine revision. Chromium and Firefox native WebRTC +transport checks passed, including simulated datagram loss. The final CI +Linux harness passed 2,147 tests, with 27 skips and seven subtests. + +Local two-peer tests do not establish public WAN reachability, compatibility +with future OpenCE protocol revisions, full campaign correctness or runtime +behavior on Android hardware. No such claims are made here. + +Disposable maps, binaries, browser profiles and duplicate captures were +removed after retaining useful logs and screenshots. Test saves were +archived with original relative paths and every exported file's SHA-256 +verified before loose copies were removed. Original game data and user saves +were not modified. Local evidence lives under the worktree's +`build/session-compatibility`; the delivered bundle includes its concise +validation record. diff --git a/docs/reading/third_person_qualification.md b/docs/reading/third_person_qualification.md new file mode 100644 index 0000000000..c0f7b78cb0 --- /dev/null +++ b/docs/reading/third_person_qualification.md @@ -0,0 +1,115 @@ +# Online third-person qualification, 28 October 2026 + +This records the qualification of `online-third-person` through engine +revision `8294d69476996136cfb325557dc50420dd741c25`. Read the +[camera walkthrough](third_person.md) for behavior and ownership. This is +release-candidate evidence, not a declaration of complete campaign or WAN +compatibility. WAN means peers on separate external networks. + +Third person remains optional and off by default. Player Choice remains the +default host policy. Xbox, Custom Edition and MCC discovery/loading paths +and defaults remain separate. No stencil-shadow feature, cosmetic head +tracking or new controller binding was added in this qualification. + +## Findings and fixes + +Two connected controllers exposed a startup assertion before the game clock +existed. `remap_game_active` in +[controller_remap_game.c](../../port/linux/game/controller_remap_game.c) +now guards active-player queries. The real browser startup test includes two +neutral standard gamepads; the production-function regression failed before +the fix. Existing button layouts remain authoritative. + +Repeated co-op reconnects followed by an old checkpoint restore exposed a +session-lifetime bug, also reproduced with third person forced off. Saved +player datums could replace the live roster while machine ownership tables +still described the current session. `network_coop_restore_players` in +[network_coop.c](../../port/linux/game/network_coop.c) reconciles those +datums with the host's current membership before view and input caches +rebuild. The three-line registration in +[game_state.c](../../source/saved%20games/game_state.c) is necessary because +that file owns callback ordering. The reconciliation stays in the co-op +module; it does not adapt Xbox/CE loading to MCC. + +A restored unit can also reuse a handle whose client copy died. In +[network_objects.c](../../port/linux/game/network_objects.c), +`network_objects_host_reverted` immediately refreshes loaded clients through +the existing reliable object-description path. `distributed_client_reuses_object` +recreates a dead co-op copy when the validated host description says alive. +Ordinary client requests retain their rate limit and retry backoff; only +the host's checkpoint operation initiates the immediate refresh. No client +can choose membership, revive itself or dictate a checkpoint. + +Experimental protocols are now **32708 for Xbox/CE and 32709 for MCC**. +The admission envelope remains mandatory, including camera-off games. +OpenCE/main and earlier camera builds cannot join these sessions. No packet +IDs or layouts were repurposed. The generated protocol manifest was updated +and checked after CI caught its stale revision. + +## Completed validation + +All engine sessions used isolated data/save folders and at most two game +instances. Native test windows were hidden; browser runs used headless Edge. + +| Check | Observed result | +| --- | --- | +| Windows portable release | Built successfully; final focused regression run: 56 passed, including the recorded-format check. | +| Windows/browser host-policy matrix | Six real Blood Gulch sessions: each platform hosted Player Choice, Forced On and Forced Off. Each peer logged at least 45 two-player samples. Conflicting local preferences obeyed the host policy. | +| Cross-platform simulation | All six pairs passed the unmodified `tools/net_compare.py` default tolerances, with 25–43 aligned seconds per pair after startup. Large transient drift occurred around scripted relocations/respawns; these results do not mean zero divergence. | +| Windows co-op stress | Two 140-second a30 runs, Forced On and Forced Off, each with three client reconnects and two explicit checkpoint restores, plus opening-cutscene restoration. Receive latency was 80 ms with 2% simulated packet loss. No stale-roster errors or engine exceptions remained. | +| Restore timing | Comparing host/client alive state after each explicit restore found at most one one-second mismatched sample. The first matching alive sample appeared within 35 simulation ticks of each scheduled restore. Reconnecting was not needed to recover. | +| Windows/browser co-op | Real a30 session over WebRTC, save/revert at approximately ticks 240/600, continued to tick 1350. Both players were alive and third-person policy remained enforced. Default log comparison passed. | +| Native round lifecycle | Native internet UDP tunnel with private local signalling, isolated from LAN discovery: three played rounds and their postgame/lobby transitions, followed by the fourth round beginning to load. | +| CE and MCC | Two-peer CE Death Island session passed. Two-peer MCC Mercury session used different host/client package-folder names and continued after a save/revert; both players remained alive. These are focused opening-session checks. | +| True split screen | One rendered browser engine, two local players, two synthetic standard gamepads. Player 2 alone scoped; player 1 alone orbited with the reticle hidden and returned on release. Both returned to third person. Gameplay aim stayed fixed during orbit/release; turning controller 2 subsequently changed only player 2's aim. Captures were inspected. | + +The combat runners combine real bot firing with synthetic reported-hit +probes (`HALO_NETWORK_TEST_SHOOT`), forced deaths, pickups and vehicle events. +Their accepted-hit counts are not exclusively physical gunfire. An earlier +gunfire-only run is retained separately in the local evidence. + +[Final platform CI](https://github.com/chestahh/GulchCE/actions/runs/40619370361) +passed Windows, Linux, Android and web. The Linux primary suite reported +1,793 passed and 27 skipped; additional suites also passed. Skipped retail +tests are not runtime evidence. Web transport checks passed Chromium and +Firefox normally and with 10% datagram loss, alongside browser startup and +page/socket tests. +[MCC validation](https://github.com/chestahh/GulchCE/actions/runs/40618494706) +passed on the same engine code before the manifest-only follow-up. + +The local browser gameplay and final split-screen runs used the CI debug +artifact from `80d2f0bb`; the Windows build used the same engine code. +`8294d694` changes only the recorded network-format manifest. Artifact +SHA-256: `9d69398c18634180f7c9de53c3622a28da59e6037985388b1c0c4d344317d6b4`. + +## Limits, review and retained evidence + +An earlier native pair reached public signalling brokers and established +the native internet tunnel, but both endpoints were on this computer/LAN. +The Windows/browser matrix used a private local signalling broker and real +WebRTC. Neither establishes independent-WAN NAT traversal or long-distance +play quality. Physical-controller testing, long campaign playthroughs and +exhaustive weapon rendering on every map family remain playtest coverage. +Shared preferences and keyboard ownership are unchanged; viewport-state +isolation does not imply independent keyboard settings for each player. + +The combined implementation, source hook, guards, declarations, state +ownership, tests and documentation were reviewed before final regression +checks. No unrelated refactoring or MCC boundary changes were needed. +Negative controls rejected missing roster reconciliation and dead-unit +reuse. The browser linker caught a missing `void` declaration during +development; it was corrected before the final passing builds. + +Local evidence lives under the worktree's `build/qualification/`: final +policy cases are `final-native-*` and `final-browser-*`; checkpoint stress +is `windows-coop-immediate-{on,off}`; family checks are `final-families`; +rendered isolation is `split-browser-final`. These folders contain logs, +JSON reports, inspected captures and the local runners. Earlier failing +reproducers and fixture failures remain labelled separately; their initial +summary flags are not substitutes for the final recovery-timing checks. + +Disposable map copies, browser profiles, caches, test binaries and temporary +broker dependencies were removed. Inactive test saves were archived +losslessly, with original paths and SHA-256 manifests verified before loose +files were removed. Original maps and user saves were preserved. The +Windows delivery and active build/toolchain remain available. diff --git a/docs/render_preparation.md b/docs/render_preparation.md new file mode 100644 index 0000000000..f8108defb9 --- /dev/null +++ b/docs/render_preparation.md @@ -0,0 +1,264 @@ +# Renderer preparation and irregular hitches + +The [Windows investigation](windows_stutter_investigation.md) measured shader +linking and MCC texture handling on gameplay frames. The preparation controls +move some of this work into loading without changing simulation, network +messages, texture quality or map-family selection. All controls default off. + +```toml +[display] +shader_prepare = true +texture_prepare_mb = 128 +mcc_texture_prepare_mb = 128 +``` + +These controls are available on Windows and Linux OpenGL. They do not promise +stall-free gameplay: a shader pair outside the loading pass is still prepared on its first draw, +and textures outside the preparation budget retain their existing lazy path. +The tradeoffs are loading time, program memory and earlier texture residency. +The texture budget estimates image storage; it is not a driver memory limit. +Changes to these preparation controls take effect on the next map load. + +## Reading the shader path + +1. `game_load`, `game_initialize_for_new_map`, `game_unload` and `game_dispose` in + [game.c](../source/game/game.c) supply map boundaries. A failed load clears + the preceding map's preparation state too. These small shared hooks are + necessary because the GL backend does not own map lifecycle or identity. +2. `render_prepare_map` in [d3d8_gl.c](../port/linux/src/d3d8_gl.c) checks that + the GL device exists and passes its existing binary-cache services to + [shader_prepare.c](../port/linux/src/shader_prepare.c). GLES stays a no-op. +3. `shader_prepare_begin` validates a map's recipe file before issuing GPU + work. It loads matching driver binaries or compiles the saved GLSL pairs. + Missing pairs are submitted before completion checks; drivers supporting + parallel compilation expose completion status, with synchronous validation + retained elsewhere. The feature never draws an incomplete program. +4. `program_get` records actual shader pairs in memory and takes a prepared + program only when both source hashes match. It initializes the same uniforms + and uses the same failure/fallback path as before. Transferred programs + belong to the existing renderer cache; unconsumed ones belong to preparation. +5. Map unload saves the recipes and releases unused prepared programs. Process + exit also saves CPU recipe data, without calling GL from an exit handler. + +For example, the first visit to CE Death Island records a weapon/effect pair +when it is drawn. A later load prepares that pair before gameplay. The recipe +contains source rather than a driver binary, so it can also repopulate the +driver cache after a driver change. A new combination of render state is not +covered until observed unless selected by the material pass below. The recipe +part remains repeat-visit preparation, not exhaustive shader discovery. + +Each map identity includes its full family/package-qualified path. The recipe +format permits at most 512 pairs, 64 KiB per source and 16 MiB of source data +per map. Lengths, termination, source hashes, record count and trailing bytes +are checked before compiling. Incomplete or malformed files are ignored and +can be rebuilt by recording valid draws. Recipe recording performs no file I/O +on a draw; unseen pairs still use the renderer's existing binary-cache/link path. +Changing settings can encounter new source hashes; an obsolete source cannot +replace a different current shader. Cached recipes are local derived data, +not game assets intended for distribution. +Old recipes remain until the map's bounded recipe file is removed; source +changes can therefore leave unused entries consuming some of its capacity. + +## Preparing unseen materials + +[material_prepare.c](../port/linux/game/material_prepare.c) runs after map +initialization, before gameplay. It asks the existing model and transparent +renderers to select shaders for loaded environment, model, generic and Chicago +materials, using supported vertex formats and fog/lighting variants. It does +not simulate a scene or submit geometry. Limits are 512 materials, 8,192 draw +variants and 4,096 temporary bitmap descriptors. These are admission limits, +not a promise to cover every map or setting combination. + +The draw interception in `rasterizer_draw` and +`rasterizer_transparent_geometry_group_draw__internal` is necessary because +the existing material selectors combine state selection with geometry +submission. The feature-owned pass supplies dummy geometry metadata and the +hooks call the backend's ordinary shader selection without drawing it. Extra +transparent layers needing real geometry, such as water, glass and plasma, +are skipped during preparation and retain their normal gameplay paths. + +The small `texture_cache_prepare_descriptor` wrapper reuses native descriptor +validation and construction without fetching Xbox/CE pixels. Its call is +behind the loading-only feature guard; the existing MCC branch runs first. +MCC descriptors continue to come from `mcc_texture_cache_get`, and +`xgpu_mcc_texture_describe` reads only registered MCC metadata. This separate +lookup is necessary for MCC dimensions that cannot be encoded by a native +texture header. Neither path uploads pixels during material selection. + +The pass restores the window parameters and statistics, pairs renderer +begin/end calls, clears temporary texture bindings, frees descriptors and +turns its interception off before returning. Shader programs remain in the +existing source-keyed renderer cache, as programs encountered in gameplay do. +Material variants do not fill the observed-recipe file unless actually used +in gameplay. This trades additional loading time and program residency for +fewer first-use links; it does not change shader math or drop gameplay draws. + +## Xbox/CE texture preparation and Windows allocation costs + +[texture_prepare.c](../port/linux/game/texture_prepare.c) enumerates loaded +bitmap tags only when its own budget is enabled and MCC is inactive. It +prioritizes large non-paletted cached textures and calls the existing blocking, +validated texture-cache API. The 128 MiB maximum is half the native 256 MiB +texture arena. Each candidate is charged for the larger of its native pixel +size and estimated RGBA mip-chain storage, including row alignment, cube faces and cache page +rounding. Failed preparations remain charged, and normal lazy loading remains +available. The existing CPU and GPU caches retain ownership and invalidation; +this feature adds no separate residency pool. + +Two general Windows/desktop fixes also reduce first-use costs with preparation +off: [xgpu_texture_names.c](../port/linux/src/xgpu_texture_names.c) batches +unused GL texture names, and +[win32_memory_watch.c](../port/windows/src/win32_memory_watch.c) protects +contiguous unwatched page runs together. The latter falls back to individual +pages across separate Windows reservations and keeps per-page write-generation +tracking. Texture names allocate no image storage; ownership transfers to the +existing cache when consumed. Only unused names are deleted at map boundaries. +Shader preparation optionally reserves 1,024 names during loading. + +Android and web keep individual texture-name allocation. All preparation +modules are no-ops under `HALO_GLES`, and the Android CE cache, mirror uploads, +static geometry, texture invalidation and disabled dynamic-lighting modules +retain their established paths. The shared honeycomb shader specialization +below also applies to GLES; it changes source scope, not the enabled effect's +math. Compilation and host-side tests do not replace an Android device test. + +## Reading the MCC texture path + +`mcc_cache_tags_load` invokes `mcc_bitmaps_prepare_gpu` only after conversion +and validation succeed and MCC ownership is active. Both functions are in +MCC-owned modules: [mcc_cache.c](../port/linux/game/mcc_cache.c) and +[mcc_bitmaps.c](../port/linux/game/mcc_bitmaps.c). No Xbox or CE loading hook +is used by this MCC preparation pass. The separate Xbox/CE preparation +feature never routes their resources through the MCC adapter. + +The pass prioritizes large converted allocations. It registers them through +the existing [mcc_texture_cache.c](../port/linux/game/mcc_texture_cache.c) +adapter and asks `mcc_texture_bridge_prepare` in +[mcc_texture_bridge.c](../port/linux/src/mcc_texture_bridge.c) to prepare those +fitting the remaining budget. Small textures, palette-dependent P8 textures, +and active high-resolution HUD replacements retain their own paths. Failure +leaves the normal first-use path available. Existing MCC disposal releases +prepared textures along with other MCC textures; no separate ownership pool +or package-wide unbounded upload is introduced. + +## Avoiding redundant desktop shaders + +Desktop translation also canonicalizes dead alpha combiners in +`discard_dead_r0_alpha`. Model material selection can retain a preceding +material's unused alpha stage, creating different GLSL and extra links despite +identical output. The pass clears only alpha portions writing discard or +`r0.a` when no later input, mux selector or final combiner can read `r0.a`. +It retains other destinations and bypasses normalization for diagnostic +expressions that may inspect registers. GLES translation is unchanged by this +optimization. Tests exercise explicit reads, muxes, implicit final output and +debug expressions; no gameplay render state is modified. + +## Honeycomb shader scope and experiment + +`prepare_draw` sets `nv2a_pixel_shader_key.shield_honeycomb` from the existing +draw-local activation value. `nv2a_pixel_shader_to_glsl` emits the existing +surface code only for that variant. Shield draws keep the same surface math, +uniforms and settings. Ordinary draws omit a surface that previously returned +their original color immediately. Xbox, CE and MCC follow the same activation +contract; no map-family defaults change. + +The independent omission experiment is retained in +[render_stutter_build.py](../tools/render_stutter_build.py) as +`--omit-honeycomb`. It removes the surface entirely from a temporary diagnostic +build and must not be used as a production fix or visual-equivalence test. +The builder instruments scratch copies, preserving production sources and +objects. [render_stutter_run.py](../tools/render_stutter_run.py) runs hidden, +isolated matches, records frame timing, archives verified saves and +removes each run's temporary binaries and generated map caches. +The diagnostic `--record-prepared` option also saves speculative material +sources for coverage investigation; production records observed draws only. +Use the builder's `--deterministic` mode for a single-process controlled +comparison: split-screen matches use the network-server path, which otherwise +ignores the engine's ordinary fixed-step option. This mode patches scratch +copies to use a fixed clock and both engine and bot random seeds; never use it for multiplayer +compatibility checks or normal frame-rate acceptance measurements. +The runner's `--compare ` checks sampled player state, +excluding local machine-slot numbers that differ with a build's bot capacity. +Missing or different samples fail this comparison. Matching player samples +are useful evidence, not proof that every world object or GPU operation matched. + +Compare cold and warm application caches separately, verify matching simulation +traces, and report the uncontrolled driver cache. A change in average FPS alone +does not establish a hitch improvement. Required checks include optional +settings off/on, shader failure, malformed recipes, bounded uploads, palette +changes, map-family transitions, visual output and network compatibility. + +## Measured results and validation limits + +Windows release testing on an RTX 5070 Ti (driver 617.42) used CE Death Island +and `mcc_maps/DigsiteMP/10`. The diagnostic builds use fixed simulation ticks, +seven bots and a 120 FPS cap. The settled comparison window is ticks 600–1200, +601 frames; driver caches were not controlled. Timings include instrumentation +and are not a general FPS prediction. + +The CE warm-cache control's worst frame was 27.797 ms. The final prepared run +was 8.747 ms, with all 40 sampled player states matching the control after +normalizing machine-slot IDs. The measured respawn/new-view hitch at tick 1057 +fell within that final bound. Texture-name allocation, page protection and +first-use texture uploads were measured separately before selecting the fixes. + +On Digsite at 2560×1440, MSAA 8x, highest model detail, per-pixel lighting, +classic honeycomb and Shield Glow enabled, the final settled interval had a +9.568 ms worst frame and no shader links or frames above 16.7 ms. The preceding +material-pass run still linked five programs in that interval. Source inspection +found unused alpha-stage differences in the missing variants; the conservative +desktop normalization removes those differences. MCC bot traces did not match +across repeated controls, including before the material pass, so these runs do +not establish a controlled end-to-end speedup or the cause of the reported +OpenCE/GulchCE difference. + +The full early-gameplay log is retained too: the first rendered gameplay frame +(tick 3) reached 18.307 ms on CE and 74.788 ms on MCC; the latter included one +20.794 ms shader link. Unseen effects and resources outside the loading passes +remain first-use work. The result addresses the measured recurring hitch, not +every startup stall or every map. Removing honeycomb entirely in the separate +experiment did not eliminate the hitch, so the shipping change preserves it. + +The final self-review covered all modules, shared hooks, settings, diagnostics +and tests. It corrected partial shader-allocation cleanup, conservative native +row-pitch budget accounting and preservation of diagnostic register reads. +The final Windows release build passed, and the focused regression suite passed +310 tests, with seven platform-dependent skips and five passing subtests. +It includes real C tests for recipe validation/failure/ownership, texture +budgets and guards, Windows protection across reservations, MCC descriptors, +shader translation and the existing Android renderer fixes. + +Normal, uninstrumented Windows binaries also passed two-instance loopback +checks: new host/OpenCE client on CE Death Island, OpenCE host/new client on +Xbox Blood Gulch, and new host/testing-baseline client on MCC Digsite 10. +`net_compare.judge_run` reported no divergences or problems over respectively +52, 52 and 42 compared seconds, with damage, pickup and death cues enabled. +The references were OpenCE `f30c7a406` and testing `e83a45e49`. These are local +compatibility checks, not long-session or Internet latency coverage. + +Two clean-exit sequences, with preparation off and on, traversed Xbox b30, +MCC Digsite 10, CE Death Island and Xbox Blood Gulch. Every phase advanced +beyond 150 simulation ticks. Captures at 1280×720 were inspected for scene, +texture and HUD output with no obvious regression; they are not pixel-identical +comparisons or full campaign validation. Delayed console-print markers were +not observed because default chatter filtering suppresses them after the +command yields; tick logs and captures establish the narrower transition +result, not completion of those diagnostic scripts. The first two network +attempts lacked the stock lobby map and never entered gameplay; corrected +fixtures were rerun successfully and the original failed reports retained. + +All 30 affected Android/web translation-unit checks passed. Full Android and +web builds were attempted but blocked by the Windows host's command/toolchain +setup (Android compiler wrapper/SDL configuration and web shell commands). +No Android device, browser gameplay, Linux runtime or Internet/WebRTC run was +completed. Network messages and simulation rules are unchanged, so this work +does not change the network version. Device validation remains necessary; +cross-compilation and host tests do not establish Android visual equivalence. + +Local evidence is retained under `build/stutter`: frame CSVs and reports, +settings and executable/source hashes, source-difference records, platform +logs, compatibility captures and verified save archives. The normal Windows +release build is retained for delivery. Copied maps are hash-checked against +their originals before cleanup; diagnostic binaries, reference build copies, +generated caches and disposable cross-build outputs are removed. Original +maps, saves, installed toolchains and the primary checkout are preserved. diff --git a/docs/reversed_depth_validation.md b/docs/reversed_depth_validation.md new file mode 100644 index 0000000000..82382d3ac1 --- /dev/null +++ b/docs/reversed_depth_validation.md @@ -0,0 +1,94 @@ +# Reversed depth and decal integration validation + +Date: 5 November 2026. Base: `origin/testing` at +`ef03a840121f87b4a6e5de66afe8b5690c91c959`. + +The base already contains OpenCE #495 (`49c8260b98bda1fe02060628809d2ce42a09d22b`), +including the desktop default `display.reversed_depth = true`. OpenCE #540 +(`8468b4c347a5675946d4a53873398e47c6878ade`) was cherry-picked with its author +and provenance retained. Its draw-cache additions were combined with the +existing shield-honeycomb inputs and uniforms. The follow-up also applies +the constant bias to the fixed-function shader; otherwise #540 removes the +hardware constant term without supplying its replacement on that path. + +## Review + +The combined self-review covered depth allocation, clears, comparisons, +viewport ranges, projection recognition and fallback, constant and slope +bias, shader/program caching, fixed-function draws and lighting integration. +The existing model-lighting and MCC environment paths retain their guards. +No map-family loading, gameplay or network protocol changes were made. +No network version increase is required for these render-only changes. + +The implementation remains in the responsible OpenGL backend. No new shared +game-engine hook or MCC adapter is needed. Inspection found no justification +for restructuring the projection translator or adding a second feature +module. Precision claims in the settings help were narrowed: reversed depth +improves distant precision but does not guarantee separation at all distances. +The [walkthrough](reading/reversed_depth.md) records the near-plane clipping +and fragment-written depth limitations. + +## Build and automated checks + +Windows release, portable, PGO and LTO off: +`python configure.py --release --portable --pgo=off --lto=off`, then +`ninja windows`. The build passed. The linker emits Expat `LNK4217` import +warnings in `menu_files.o`; this is not a warning-free build. + +On an NVIDIA GeForce RTX 5070 Ti, OpenGL 4.5, driver 617.42: + +- Nine depth tests passed with `HALO_TEST_GPU=1`. They compile 536 combinations + of the 67 stock vertex programs, reversed/conventional depth, optional + model lighting and packed attributes. They also check production bias + calculations at different viewport ranges and render scales, fixed-function + bias removal, both depth formats, 4x MSAA resolves, and projection output + for surfaces 0.0016 world units apart through 1,000 world units. +- A temporary negative control removing the fixed-function correction + reproduced the missing shader expression detected by the new assertion. +- The desktop, Android and web shader-emitter tests cover lighting enabled + and disabled. The initial focused renderer/lighting suite passed 30 tests. +- After the combined review, the expanded focused suite passed 161 tests, + including the GPU checks, all selected lighting/shield/emitter/loading + harnesses and web build tests. One native socket test was explicitly skipped + on Windows because it requires POSIX pthreads. The duplicate CRT define + mentioned below was corrected in the local wrapper; its MCC mod-lifecycle + test passed in this final run. +- The broader harness plus touch-menu, depth, render-stutter, lighting and + web-build tests passed 1,643 tests and skipped eight with Windows CRT + compatibility defines. It also had 372 failures: this was **not** a green + full-suite run. Failures were in unchanged harnesses, including unavailable + POSIX headers/functions, missing `m.lib`, Windows type-declaration conflicts, + and one duplicate CRT define in the local compiler wrapper. None of the + lighting, shield, plasma, emitter, loading or new depth tests failed. +- `ninja android` and `ninja web` were attempted. Configuration generated + neither target because this machine lacks an Android NDK and Emscripten. + Source-level platform tests do not replace those builds. Linux runtime and + full Linux harness validation remain outstanding; WSL is unavailable here. + +## Rendered game checks + +All runs used hidden windows, isolated data and save directories, and at most +two game instances. Default-mode runs omitted both the config setting and +environment override; their startup logs reported `32-bit float, reversed`. +Explicit-false runs reported `24 bits, as the Xbox's`. + +| Scenario | Settings and observed outcome | +| --- | --- | +| Xbox Blood Gulch, two peers | Opposing local lighting settings, host shield policy, respawns and inventory changes; 81 paired snapshots, no reported divergence, clean exits. | +| CE Death Island, two peers | Same compatibility checks; 81 paired snapshots, no reported divergence, clean exits. | +| Xbox `a30` opening | 640x480 conventional depth with lights off; 1920x1080 reversed and conventional with lights on; 4x MSAA in both depth modes; 640x480 reversed with 2x SSAA. Captures and clean exits, no detected shader or GL errors. This is the drop-pod opening, not the Pelican scene. | +| Xbox `b30` Pelicans | 640x480 conventional depth and 1920x1080 default reversed depth, plus reversed 4x MSAA. Captures show the Pelican's side light as a continuous glow at 1080p. | +| Available MCC `mcc_maps/a10.map` | Successful MCC conversion and rendered gameplay with default reversed depth/lights on and conventional depth/lights off, 1280x720. The local file contains a multiplayer scene; this is not evidence of completing an MCC campaign. | +| Map-family transitions | Xbox Blood Gulch -> MCC `a10` -> CE Death Island -> Xbox Blood Gulch in one process, default reversed depth and dynamic lighting on. Console commands, loading logs and captures confirm the transitions; clean exit. | + +The native OpenGL debug log also contains driver shader-recompilation +performance messages. These captures are visual and lifecycle checks, not a +performance benchmark or proof of compatibility on every GPU. No new internet +transport code was introduced or transport-specific validation claimed. + +Local evidence is retained under `build/lighting-compatibility/`, +`build/depth-runtime/`, `build/depth-transitions/` and the build/test logs in +`build/`. The early `pelican-*` labels without `b30` are the `a30` opening +checks described above. Staged maps and generated map caches were removed; +test saves were archived losslessly with verified manifests. Original maps, +saves and the user's working checkout were not changed. diff --git a/docs/shield_look.md b/docs/shield_look.md new file mode 100644 index 0000000000..d19d0a2620 --- /dev/null +++ b/docs/shield_look.md @@ -0,0 +1,1022 @@ +# Shield Look + +Video Setup > FOV and Viewmodels > SHIELD LOOK offers these presets in order: + +| Menu label | Saved configuration value | Previous menu label | +| --- | --- | --- | +| DEFAULT (default) | `classic` | CLASSIC | +| CLASSIC WITH SPRINKLES | `classic_with_sprinkles` | CLASSIC WITH SPRINKLES | +| MARK VI | `enhanced` | ENHANCED | +| INFINITE HONEYCOMB | `classic_honeycomb2` | CLASSIC HONEYCOMB | + +SHIELD LOOK overrides apply only to bipeds with a current player index, +including remote/co-op players. AI bipeds retain their authored shield +materials and do not receive the preset's depleted arcs or recharge envelope. +Eligibility is checked per instance before the definition cache is consulted, +so a player and an enemy may safely share a model or biped definition. +The shell-suppression hook receives the draw's object identity and first-person +flag. Hands retain the engine's weapon identity; the feature resolves the +weapon's parent unit only for its player-ownership check. Arm Shields remains +authoritative, including suppression of authored player hand shells when OFF. +Losing player ownership restores the authored look on subsequent draws. + +The player-only correction was reproduced by failing regressions for all +three non-default presets. After the fix, 164 shield/enclosure checks and +Windows, Android and web release builds passed. Hidden Windows b30 campaign +runs loaded and rendered with DEFAULT and INFINITE HONEYCOMB. These were +startup smoke checks, not controlled Elite flare comparisons. Shared-model, +remote-player ownership, loss of ownership, first-person weapon identity, +Arm Shields OFF, arcs and recharge are covered by the harness. No live CE/MCC +combat, multiplayer or physical Android/web GPU comparison was performed. +The final self-review retained the feature-owned guard and minimal model-hook +arguments; no shader formulas or simulation state were changed. + +The retained presets keep their saved values and exact visual formulas. +HONEYCOMB CLEAR and HONEYCOMB LAYERED have been removed, including their +exclusive shader paths. Saved `honeycomb` and `classic_honeycomb` selections +return to DEFAULT. Offsets, map-colour inheritance, Arm Shields authority, +arcs, recharge and overshield precedence are unchanged. Historical design +and validation notes below retain the names used when those checks were run. +The four-preset cleanup passed 118 focused shield tests and Windows, Android +and web release builds. Hidden Windows UI runs verified all four labels and +both retired-value fallbacks. The retained GLSL grid, body and arm formulas +were compared against the previous revision and are unchanged. Map-colour, +Arm Shields and lifecycle harness checks pass; gameplay captures, multiplayer +and physical Android/web rendering were not repeated for this removal. + +The former ENHANCED 2 profile is the current MARK VI look. + +`display.shield_look = "enhanced"`, or `HALO_SHIELD_LOOK=enhanced`, selects +CMT Snow Grove's plasma pattern and first-person parameters with the approved +small outward body flare, overriding map-authored shield modifiers except custom colour. This is a local rendering feature in `port/linux/game/shield_look.c`. +It does not use the mod loader or change simulation, shield strength, damage, +network messages, map tags, models or cache files. No network-version change +is required. + +CLASSIC leaves the established drawing paths intact. Arm Shields is +now authoritative for the added first-person pass in every SHIELD LOOK +mode: OFF adds no arm shield; ON supplies the stock displacement and its +distance/FOV-based cap. ENHANCED restyles that pass with the CMT pattern and +custom map colour (where present) while preserving its animation values and overshield handling. +CLASSIC preserves authored map shields. ENHANCED replaces authored shield +modifiers and omits their duplicate plasma model shells. Overshield Effect remains an +independent, opt-in visual modifier. + +## Reference and provenance + +The reference is the user-supplied `cmt_Snow_Grove.map`, 131301829 bytes, +SHA-256 `d65da3089cfaf8243f4288bc079326c1ab89a46f8e2f2bed974eb548e5fd8fed`. +It is a stock CE-format cache (609), not an OpenSauce implementation. +The user authorized using its assets. No CMT art, geometry or executable code +is redistributed by this feature: the inspected shaders use the stock +`characters\elite\bitmaps\plasma shield noise` texture. Its entire six-level +32x32x32 mip chain (37449 texels) is identical to the Xbox texture after +addressing and A8Y8-to-ARGB conversion. The existing map therefore supplies +the exact noise data through its existing texture loader. + +The multiplayer unit is tag 1880, its body modifier tag 1935; the globals' +first-person hands are model 2157 with plasma material 2163. Both shader +noise references point to bitmap 1126, external CE resource 863. The original +CMT shaders use the following inspected values. The regression test compares +all rendering fields, allowing only the approved body displacement below: + +| Parameter | Body | First-person hands | +| --- | --- | --- | +| Intensity source / exponent | B / 1 | B / 1 | +| Offset source / exponent | C / 2 | C / 2 | +| Offset amount | 0.035 | 0.009 | +| Perpendicular alpha / RGB | 1 / (0.909804, 0.772549, 0) | same | +| Parallel alpha / RGB | 1 / (0.937255, 0.694118, 0.0627451) | same | +| Color source | none | none | +| Primary period / direction | 2.1 / (2, 0, -0.5) | same | +| Primary scale | 18 | 45 | +| Secondary period / direction | 3.2 / (0, 2, 0.5) | same | +| Secondary scale | 14 | 62 | + +The original CMT profile uses source C rather than B: CMT has two object +functions, and its unused C output is zero. ENHANCED uses the approved body +displacement below; first-person displacement follows the stock modifier +and Arm Shields cap. ENHANCED retains Arm Shields' animation-values pointer, +so its displacement cap and overshield handling apply to the enhanced +profile. CMT supplies duplicate arm parts for the plasma layer: all +68-byte vertices in its four shell parts (660, 574, 222 and 39 vertices) +are byte-identical to their underlying arm parts. The feature uses the +engine's modifier pass on the current map's hands. +This preserves that map's geometry and animation. Controlled render +comparisons on identical geometry are recorded below; the feature does not +replace another map's models to make their silhouettes match CMT's. + +## Approved ENHANCED profile + +ENHANCED now uses the approved former ENHANCED 2 appearance exactly. The +body displacement is outgoing hit intensity B, exponent 0.5 and amount +0.0125 world units (about 3.8 cm at full intensity). The CMT pattern, animation and brightness remain unchanged; custom authored hue can replace the preset gold. +The first-person offset now follows Arm Shields, as described below. +The former skin-tight body option and separate SHIELD LOOK submenu are gone. + +Existing `"enhanced2"` config/environment values normalize to `"enhanced"` +at load, so playtest selections retain their appearance and show ENHANCED in +the menu. Both spellings also select the same stable shader in the feature. +There is only one enhanced body copy. CLASSIC still preserves stock behavior. +No shared-engine hook, map-family adapter, geometry mutation or simulation +change is needed; the existing renderer displaces vertices along normals. + +## Map authority and isolation + +CLASSIC returns the map's original shaders and submits its authored model +materials unchanged. ENHANCED (including migrated `enhanced2`) takes precedence +over authored shield modifier parameters and plasma shell materials on Xbox, +CE and MCC. Shader/function fingerprints and unrelated transparent model +materials no longer veto the selected appearance. Hit timing and the map's +intensity channel remain unchanged; appearance is applied at draw time. + +The selected profile keeps the approved body parameters and the established +Arm Shields stand-off (0.03, exponent 2), with its existing distance/FOV cap. +Arm Shields OFF also suppresses authored plasma hand shells under ENHANCED; +CLASSIC keeps the original map behavior. Visors, generator lights, decals and +other non-plasma materials are retained, since transparency alone does not +identify a shield. No map tags or geometry are rewritten. + +The exact stock/CMT noise is found among the loaded map's bitmap tags using +bounded reads and full-mip fingerprints: Xbox A8Y8 `f2f70788`, CE linear ARGB +`e7f72da4`, MCC packed ARGB `18ac1e94`. This prevents custom modifier noise +from changing the selected pattern. Each family retains its existing resource +loader; no foreign map or mod is loaded. Missing/malformed plasma data, no +matching noise resource, or exhausted profile capacity retains the original +shader safely. Other valid modifier types receive the same private plasma profile; the +animated overshield resolves its intensity channel from that selected profile. + +Resource discovery and private shader copies reset before map load/unload. +CLASSIC bypasses discovery and overrides; selecting ENHANCED again reuses +stable per-map copies. Original map resources remain owned by their loaders. + +## Authored colour inheritance + +The feature-owned draw copies retain every approved profile field. A guarded +`shield_look_colors` call changes only the draw-local perpendicular and parallel +RGB constants immediately before the existing Overshield colour operation. +It identifies an eligible body/arms copy by pointer; CLASSIC, unrelated plasma, +non-plasma source modifiers and unregistered draws do not inherit colour. + +Static authored RGB is supported, as are plasma colour sources 1 through 4 +resolved from the current draw's object colours. The source RGB is multiplied +by that channel, then each nonblack endpoint is normalized to the corresponding +preset maximum RGB component. This preserves preset peak brightness rather +than importing authored opacity or intensity. A black endpoint uses the other +endpoint's hue; two black/unusable endpoints retain the preset. Missing or +invalid colour channels retain the preset. No texture pixels are sampled to +invent a colour for non-plasma or texture-baked effects. + +Known stock cyborg and elite RGB pairs and the approved CMT pair (with no +colour channel) preserve preset gold. Comparison uses numeric colour data, +with a 0.00001 tolerance, not tag names or a map-name exception. Consequently, +a map that reuses the stock colour pair retains gold even if it customizes +other shader fields. The shader's other authoring does not imply a custom hue. +Future profiles registered in this feature can use the same colour resolver. + +This draw-time hook is necessary for per-object colour channels: cached copies +are shared by instances of a biped definition, and mutating their RGB per unit +would leak colour between deferred or split-screen draws. The shared addition +contains no colour logic and uses existing validated runtime tags and draw +colours. Xbox/CE/MCC loaders, resource ownership and cleanup are unchanged. +The existing Overshield operation runs last and remains authoritative; Arm +Shields still controls visibility and displacement. No simulation or network +contract changes, so no network-version bump is needed. + +## Necessary shared hooks + +The existing renderer has no registration point for a private modifier +profile. Minimal `port:` additions supply the required integration: + +- `render_objects.c`: substitute a private body shader at draw submission, + after the existing modifier-type check. Animation values remain the unit's. +- `first_person_weapons.c`: supply the hands modifier between the weapon and + hands draws; CLASSIC and ineligible maps follow the existing Arm Shields + call. The weapon never receives the enhanced modifier. +- `models.c`: omit authored plasma shell parts belonging to a selected body + or hands profile before their normal transparent submission. A modifier-only + replacement cannot suppress these separately submitted model materials. + CLASSIC and unrelated models/materials retain their existing paths. +- `cache_files.c`: clear eligibility and private shader/value copies before + load and before unload. Failed loads and Xbox/CE/MCC transitions cannot + reuse an earlier map's handles. + +All eligibility, storage and parameter logic stays in the feature module. +Copies are never recycled within a map because deferred transparent draw +packets can retain their addresses. Arm animation values are separate for +each local player. Disabling takes effect on subsequent draw submissions; +the stable copies remain available for already queued packets until teardown. + +## Verification history + +The earlier authority-refusal results below describe the previous policy. +The current precedence policy supersedes those eligibility expectations. + +`python -m pytest -q tools/test_shield_look.py` compiles the actual feature +module as 32-bit C89 with fake engine services. It covers CLASSIC/invalid +settings, exact profile fields, authored shaders/textures/functions/body and +hands shells/decals, toggling, split screen, reloads, capacity and failed reads. +It also checks generated menus and placement of the draw/lifecycle hooks. +Set `SHIELD_LOOK_REFERENCE_MAP` and `SHIELD_LOOK_STOCK_MAP` to the local CMT +and stock Xbox caches to additionally check exact CMT parameters, all noise +texels, and the actual feature reader's Xbox/CE/MCC-layout fingerprints. +`SHIELD_LOOK_CC` optionally selects a 32-bit compiler wrapper. + +Validation on Windows (20 October 2026): 25 Shield Look tests and all 21 +existing Arm Shields tests passed, including negative controls. The added +stock-light tests exercise the real generator-light definitions and pixels, +and reject altered materials, stages and textures. The harness used LLVM's +32-bit MSVC target; its existing Unix `-lm` argument was omitted by a local +Windows wrapper because the Microsoft runtime already supplies those calls. + +Release, portable Windows, Android guest/host, and web targets built with +LLVM 23.1.4, Visual Studio Build Tools 2022 and Windows SDK, Android NDK r30, +and Emscripten 6.0.10. Windows used the normal project build. The Android and +web builds used local equivalents for generated Unix shell bootstrap/copy +commands and normalized response-file paths; no build-generator changes are +part of this feature. Cross-platform compilation is not device/browser +runtime validation. + +Hidden Windows OpenGL runs used isolated data/save folders, at most two +instances, real scripted damage, and bounded copies of the supplied maps. +Original maps were never edited. Script-reference and spawn controls in the +copies made the hits and cameras reproducible; MCC fixtures preserved script +indices while making startup scripts dormant. A temporary diagnostic build +controlled randomness and recorded render-path selection. Its instrumentation +and random-seed change were removed before the final production builds. + +The live tests found that the original eligibility filter rejected stock +Spartan generator lights. The exact material/stage/texture checks above fix +that without admitting arbitrary Chicago shield shells. + +Visual equivalence was checked separately from eligibility: + +- CMT's arm shell has identical vertices **and triangle strips** to the + underlying hands. On controlled copies with identical geometry, lighting, + hit timing and interpolation disabled, the original authored first-person + shell and ENHANCED's modifier pass produced pixel-identical captures. + Both comparison copies used the same opaque body-underlay control to + exclude unrelated CMT weapon/lamp materials from eligibility. +- For the body, a temporary diagnostic alternated the original CMT shader + and the feature's stock-based profile on the same frozen in-game scene. + Twenty consecutive frame comparisons had zero differing pixels. This + isolates the shader from different random idle animations or lighting + phases between processes. The shield was visibly active in the captures. +- Normal runtime captures showed ENHANCED on stock Xbox shields. Render-path + audits also confirmed both body and hands overrides on stock CE + `deathisland` and MCC `BetterWithFriends/b30` shield chains. +- Authored magenta/scale variants of those Xbox, CE and MCC maps retained + their original body shader pointers and received no enhanced arm pass. + Unaltered CMT body/arm materials also received neither override. Their + authored appearance remained visible in gameplay. + +The visual claim concerns the shield shader, not replacing another map's +armor, hands, animations, lighting or camera with CMT's. Those remain the +map's own. The automated harness covers toggling, split-screen state, +failed reads, reloads and capacity. Live runs cover Xbox UI-to-CE/MCC loads +and shutdown; a full gameplay Xbox-to-CE-to-MCC transition chain, live +split-screen, Android hardware and browser gameplay were not exercised. +No gameplay/network structures were changed. + +The final production Windows executable also passed the repository's +two-player network comparison on Beaver Creek, with real rendering, +CLASSIC versus ENHANCED, scripted damage/deaths and swapped host roles. +Both runs compared 22 seconds and passed the existing judge/tolerances +(562 and 660 prediction-drift samples). A local adapter supplied Windows +process handling and isolated file paths; the comparison logic was unchanged. +This does not cover browser transport or internet matchmaking. + +ENHANCED 2 follow-up validation: 63 focused tests passed. Both enhanced +settings exercise authored-shield refusal, malformed data, reloads, toggles +and split-screen state. An additional real-module test compares the complete +first-person shader byte-for-byte, checks that only the three body displacement +fields differ, and verifies stable copies across all three settings. Release +Windows, Android guest/host and web builds passed. Hidden Windows OpenGL +runs on a bounded Beaver Creek fixture with scripted damage confirmed the +small body separation at 1280x960; ENHANCED was also captured for comparison. +The initial small offset was retained without increasing it. Existing Xbox, +CE and MCC eligibility checks are unchanged; the previous family-specific +live authority audits were not repeated for this displacement-only extension. +Android/browser runtime and live split-screen remain untested. + +The ENHANCED 2 production build passed both host roles in the two-player +Beaver Creek network comparison against CLASSIC, with damage/death events +and real rendering (24 seconds compared per run, existing judge/tolerances). +No networking implementation or version changed. + +Profile consolidation: 63 focused tests passed, including exact CMT rendering +fields with only the approved body displacement substituted, both saved +spellings selecting the same shader, unchanged arms, and removal of the +submenu from the generated screens and asset manifest. Earlier ENHANCED +references in this validation history describe the original CMT comparison; +the approved ENHANCED 2 appearance is now the current ENHANCED profile. + +The consolidated profile built successfully for Windows, Android guest/host +and web. A hidden Windows OpenGL menu run at 1280x960 confirmed the relocated +row fits and an `enhanced2` environment value displays as ENHANCED. The shader +parameters are identical to the approved profile tested above; gameplay and +network runs were not repeated for this naming/menu consolidation. + +## Arm Shields authority and offset + +The approved third-person profile is unchanged. ENHANCED's first-person +shader now retains the validated stock modifier's offset source B, amount +0.03 and exponent 2 instead of CMT's unused C displacement. Its pattern, +colors, intensity and noise animation still use the CMT arm profile. + +The existing `viewmodel_shield_apply` runs first and remains responsible for +activation, animation values, arm distance and the renderer's FOV-dependent +cap. `shield_look_arms` only replaces its shader on eligible stock maps, +leaving colors and the values pointer intact. OFF leaves no pass to replace. +The minimal `port:` hook reorder in `first_person_weapon_draw` is necessary +because Arm Shields owns the geometry-distance information and pass setup; +no new renderer hook or duplicate displacement calculation was introduced. +CLASSIC and authored-map fallback retain the original implementation. + +Validation: 65 focused tests passed, including real Arm Shields renderer-cap +and negative-control tests, enabled/disabled enhanced arms, exact profile +fields and preserved values/color pointers. Windows, Android guest/host and +web release builds passed. Runtime checks and evidence are recorded below. + +Hidden Windows OpenGL runs on the same bounded Beaver Creek fixture captured +the old skin-tight ENHANCED arms, the new ENHANCED arms with Arm Shields ON, +ENHANCED with Arm Shields OFF, and CLASSIC with Arm Shields ON at 1280x960. +OFF showed no added first-person shield during scripted hits. The shader +pattern remains CMT's, so apparent brightness differs from CLASSIC even +though the offset source, amount, exponent and cap are the same. Original +maps and saves were untouched. The first-person hook is shared by Xbox, CE +and MCC; the unchanged conservative eligibility cases pass in the harness. +Earlier family-specific live authority audits were not repeated for this +pass-order change. Android/browser gameplay and live split-screen were not +exercised; split-screen values and FOV-limit behavior have harness coverage. + +The final production Windows executable passed both host roles in the +Beaver Creek two-player comparison with CLASSIC versus ENHANCED, Arm Shields +ON for both, scripted damage/deaths and real rendering (24 seconds compared +per run, unchanged judge/tolerances). No network protocol or version changed. + +## Animated overshield layer colours + +Visible Overshields remains independently optional. It now follows the +unit's current shield vitality: above 2.0 it is green (78, 253, 116), and +through 2.0 it is reddish-pink (253, 78, 116). The existing charging rise +remains active while charging; once charging is over, the persistent effect +ends at normal shield strength (1.0). Body and arm draws use the same +per-unit layer snapshot. First-person animation additionally requires Arm +Shields. Original shader brightness, animation speed and geometry are retained. + +The layer selection and snapshot live entirely in `overshield_effect.c`. +No source hook, map-family adapter, network message or gameplay value changed. +66 focused tests passed, including actual effect-state refresh, exact 2.0 +boundary, charge/drain direction, body/arm colour agreement, brightness, +expired/dead units and both setting guards. Windows, Android guest/host and +web release builds passed. Hidden Windows OpenGL runs used a real overshield +pickup in a bounded Beaver Creek fixture: logged shields charged through +1.97 to 2.97, then scripted damage reduced 2.91 to 1.29. Captures confirmed +green then reddish-pink on body and arms, and the effect ended when shields +were exhausted. Arm Shields OFF kept the arms clear; Visible Overshields +OFF also removed the persistent first-person effect at full charge. Original maps/saves +were untouched. Android/browser gameplay, CE/MCC live maps, live split-screen +and network sessions were not repeated for this visual-only colour change. + +## Selected-look precedence (21 October 2026) + +The current policy replaces the earlier authored-shield veto. CLASSIC is +still the default and returns the original shader. ENHANCED and its legacy +alias now replace valid authored modifiers; the original approved profile +parameters are unchanged. The material hook also omits plasma shells and +transparent parts using the authored modifier on registered biped/hands +models. Opaque surfaces and unrelated transparent materials stay intact. +The existing Arm Shields and animated Overshield controls retain ownership. + +69 focused tests pass, including an exact byte comparison of the approved +rendering fields against the CMT reference, authored shader/noise/function +cases, non-plasma modifiers, CLASSIC restoration, shell suppression, +Arm Shields OFF, the actual overshield intensity-channel resolver, missing +resources, cache reset and capacity. Windows, Android guest/host and web +release builds pass. Only the FOV and Viewmodels menu help XML changed when +regenerated from the settings generator. + +Windows OpenGL comparisons use the previous commit `657806db` and the new +build at 1280x960. Stock Beaver Creek CLASSIC/body, ENHANCED/body and +ENHANCED/arms retain their appearance. Disposable cyan-shield variants of +Xbox Beaver Creek and CE Death Island show the authored cyan look with +CLASSIC and the approved gold look with ENHANCED. CMT Snow Grove retains +its authored arm layer with CLASSIC; ENHANCED replaces it, and Arm Shields +OFF suppresses it. Frames come from separate runs, so animation phase is +not pixel-identical; profile equality is checked by the regression test. + +The MCC BetterWithFriends/b30 fixture disables its introductory scripts and +uses a steady outgoing B function for the material comparison, because the +scripted damage cue did not reduce shields. This checks material precedence, +not MCC damage behavior. The previous ENHANCED path and the new CLASSIC +control retain cyan; the new ENHANCED path draws the approved gold profile. +Test-only script references must be aligned to the +map's virtual tag addresses, not file offsets. Rejected initial fixtures and +local-network launch failures are retained in diagnostic logs and are not +counted as successful comparisons. Both builds emitted MCC resource/audio +diagnostics; this is not a full campaign compatibility claim. + +No original map or save was edited. Temporary runs are removed after capture, +and test saves are archived with verified hashes. Android/browser gameplay, +live split-screen, and two-machine networking were not repeated. Production +changes only affect local rendering and menu help, with no protocol or +simulation changes. + + +## Colour inheritance validation (2026-10-21) + +Compared against `8a4c23c8` in hidden Windows release runs at 1280x960 +(stock 640x480 rendering), with screenshots and logs retained locally in +`build/shield-colour/evidence`. No retail map or texture is committed. + +- Coldsnap 20th Anniversary XL RC5: player `characters\scyborg\scyborg`, + plasma `characters\ncyborg\shaders\nshield hit`, perpendicular white, + parallel black, colour source 3. ENHANCED inherits the red team's hue on + body and arms while retaining its pattern and layer. CLASSIC retains the + map's original shield; Arm Shields OFF removes the enhanced arm pass. +- Mercury Falling (`mercury_falling.map`, the user-confirmed map): the + player's `characters\cyborg\shaders\shield hit` has the stock + orange/blue pair and colour source 0. Both the tag inspection and CLASSIC + render confirm this. ENHANCED therefore retains gold on body and arms; + there is no map-name-based blue override. Mercury 2's blue Spartan-boss + shader is a different map/character and was not substituted. +- Xbox Beaver Creek: before/after ENHANCED retains the approved gold body + appearance. The CMT reference test still compares all approved body and + arm rendering fields byte-for-byte. + +Test-only copies fixed spawn positions and added a small damage reference. +Mercury startup/continuous scripts were made dormant and its B function was +held steady for material comparison after scripted damage did not expose a +shield. Its colour fields, textures, models and profile parameters were not +changed. The original maps and saves were untouched. The original long +Mercury package path failed in local network-test setup; an isolated short +`mcc_maps/mr` package loaded successfully. Both reference and changed builds +emit existing Mercury sound/tag diagnostics, visible in the captures. These +runs establish the compared material behaviour, not full campaign support. + +The 71 focused shield, Overshield and Arm Shields tests pass, including +fixed and per-object colour inheritance, tiny/invalid/unavailable colour +fallbacks, unchanged cached shader bytes, CLASSIC and unrelated-draw bypass, +map reset, existing toggle/split/capacity cases, and Overshield hook ordering. +Windows, Android guest/host target and web release builds pass. Android and +browser gameplay, live split-screen, two-machine co-op and full campaigns +were not rerun for this render-only change. No network or simulation data +changed. Screenshots are visual comparisons; differences in frame timing +mean they are not claimed to be pixel-identical. + +Disposable map fixtures, per-run executables, caches and redundant captures were +removed. Test saves were archived losslessly with verified SHA-256 hashes; +selected screenshots and useful logs remain in the evidence directory. + +## Depleted ENHANCED shield arcs + +ENHANCED can use Bigass v3's original plasma-bolt sprite atlas while a living +biped's shield is depleted and its recharge stun timer is still running. +The effect stops on recharge, death or selection of CLASSIC. First-person +arcs require Arm Shields and its eligible arm pass; their outward placement +uses the existing Arm Shields offset cap. Normal shield shader parameters, +colour inheritance and animated Overshield rendering are unchanged. + +The source asset is `altis\effects\bitmaps\plasma bolts`, referenced by +Bigass's `altis\effects\energy` particle. The original sequence has 31 frames +at 30 fps, 0.5-1 second lifetimes, 0.05 second fade-in and 0.15 second fade-out. +Two 512x512 DXT1 atlases, their original three mip levels and sprite bounds +are retained. The source map's cached flag is deliberately excluded from +our private texture ownership flags. + +The emitter is an approximation of placement, not a copy of Bigass's object +attachments or scripts: up to six body sprites or two arm sprites select +non-root model bones independently. This covers head, limbs and feet where +those bones exist. Body radius is 0.05-0.1 world units, with smaller arm +sprites. Hashing object identity, time and slot supplies visual variation +without advancing simulation RNG. The same image sequence, blending and +lifetime ranges are used; exact original emission positions are not claimed. +The local CLASSIC Bigass reference did not show persistent arcs throughout +the waiting period in this port, so the comparison is not evidence of a +frame-for-frame original-emitter match. + +### Local asset installation and provenance + +The user supplied `bigass_v3.map` and authorized local asset extraction. +The atlas belongs to its original authors; its tag path identifies it as +an Altis effect. No third-party source code, SDK headers or map pixels are +committed or relicensed. Reproduce the local bundle with: + +```sh +python tools/extract_shield_arcs.py /path/to/bigass_v3.map /data-root/shield_assets/bigass_arcs.bin +``` + +The extracted bundle is 345064 bytes, SHA-256 +`cb28214c0e5b3dc35650abac199113c8332fdf9093f5c973de1d2ecc32cb3cbd`. +It is a fixed-format local asset file, independent of mods and map-family +resource discovery. Without it, ENHANCED retains its existing appearance +and logs one installation hint per map when an arc would be drawn. Invalid +files and texture allocation failures also retain normal shields. + +### Integration and validation + +`shield_arcs.inl` extends the existing shield-look feature module. The body +and first-person rendering hooks are needed to access each rendered model's +pose; feature code alone cannot receive those poses. The cache-unload hook +restores the previous tag table before the menu/MCC/mod table owners unwind, +after the texture cache closes. It also covers failed load cleanup. No +existing tag, model, shader, gameplay state or map-family loading path is +modified. The private bitmap tag is appended only on the first eligible +draw and released at the map boundary. Disabling ENHANCED stops draws +immediately; retained private resources are released on unload. + +The Windows comparison uses hidden 1280x960 captures (640x480 stock render +resolution). Bigass body and first-person runs exercise depletion, the +waiting period and recharge; Arm Shields OFF removes the new arm effect. +Xbox Beaver Creek also exercises depletion and recharge. Mercury Falling +uses a disposable copy with dormant intro/continuous scripts and an aligned +script damage reference to its actual `elefant\innie\weapons\hose\bullet` +tag. MCC conversion restores tag names, so the temporary damage alias in +earlier attempts did not apply damage. The corrected test shows depleted +body arcs. Original map shaders, textures and models were not modified. +Useful failed-run logs are retained but are not counted as passing checks. + +The 85 focused tests cover existing preset/colour/Overshield/Arm Shields +behaviour, depleted-state gates, malformed bundles, texture failure and +repeat load/unload ownership. Windows, Android guest/host and web release +builds pass. Android/browser gameplay, full campaigns and live split-screen +are not verified by these tests. Local captures and the comparison video +are retained in `build/shield-arcs/evidence`. + +A hidden two-peer Xbox Beaver Creek run used ENHANCED on the host and +CLASSIC on the client with scripted hits. The repository's log comparator +passed 26 seconds at matching ticks: no state mismatches, no drift in 780 +samples and zero client corrections. The initial attempt lacked the lobby's +stock map catalogue and did not host; its logs are retained separately. +This is a local networking smoke test, not an internet/WebRTC or full +co-op regression. No protocol or simulation data changed, so the network +version is unchanged. + +Cleanup removed about 6.1 GiB of this assignment's disposable fixtures, +caches and redundant captures. The 558 test save/profile files were archived +losslessly with SHA-256 verification and original relative paths recorded. +About 18 MiB of evidence, logs and scripts remain; the current platform +builds and installed toolchains are retained. The local runtime bundle was +installed in the user's Gulch data root. No original maps or saves were +changed. + + +## Recharge layer + +ENHANCED now reuses its approved plasma profile during actual normal shield +regeneration. The drawing envelope follows shield vitality, easing from 30% +of the existing offset to a subtle body peak 15% above the approved offset. +First-person growth remains within the existing Arm Shields offset/FOV cap. +The layer fades in over the first 6% of shield vitality and contracts/fades +for half a second after reaching full charge. Outside recharge, the approved +hit appearance is unchanged. CLASSIC and map-authored colour selection are +unchanged; animated Overshields retain their separate state and colours. + +`shield_recharge.inl` owns all state and envelope calculations. It reads +shield charging, stun, vitality and death state without modifying simulation +or consuming gameplay randomness. Damage, depletion, death and Overshield +charging cancel it. Map reset, setting changes, time rewind, stale objects +and reused first-person pointers invalidate state. Full shields on initial +visibility do not trigger a completion pulse. Capacity exhaustion falls back +to ordinary rendering. + +Minimal `port:` hooks register the selected body/arms modifier before model +submission, retain the transparent pass when ordinary hit intensity is zero, +and apply the envelope at the existing plasma draw. Feature code alone cannot +observe those draw packets or prevent their early rejection. Existing shader +values pointers remain intact for Arm Shields and Overshield ownership. No +map loading, conversion or MCC boundary changes are needed. + +The 98 focused tests cover progression/retreat, cancellation, arm offset caps, +pointer reuse, capacity, stale frames and cleanup, alongside existing profile, +colour, Overshield and depleted-arc tests. Windows, Android guest/host and web +release builds pass. The Windows captures compare the preceding committed +build with recharge enabled, including Arm Shields OFF. Android/browser +runtime visuals and live split-screen have not been tested. + +Windows in-game checks exercised recharge on Xbox Beaver Creek, CE Coldsnap +20th Anniversary XL and MCC Mercury Falling. Coldsnap retains its authored +red plasma colour; Mercury's starting player retains its existing gold +palette. Mercury uses the same isolated dormant-script fixture described +above. These are targeted visual checks, not full map/campaign validation. + +A hidden ENHANCED-host/CLASSIC-client local network run passed the repository +comparator: 26 seconds at matching ticks, no mismatched seconds and no drift +across 780 samples. No protocol or simulation changes require a network +version bump. Internet/WebRTC transport was not retested. Captures, logs and +the before/after video are retained under `build/shield-recharge/evidence`. + +The CLASSIC in-game control remains clear during recharge. Cleanup removed +about 8.7 GiB of temporary fixtures, duplicate binaries and raw captures. +All 310 generated save/profile files were archived losslessly with SHA-256 +verification and their original relative paths recorded. About 27 MiB of +logs, evidence and scripts remain, alongside required platform builds and +toolchains. Original maps and user saves were untouched. + + +## Classic with Sprinkles + +Video Setup > FOV and Viewmodels > SHIELD LOOK now also offers CLASSIC WITH +SPRINKLES (`display.shield_look = "classic_with_sprinkles"`, or +`HALO_SHIELD_LOOK=classic_with_sprinkles`). CLASSIC remains the default and +retains map-authored shaders. ENHANCED retains its approved CMT appearance. + +The new preset uses the stock Xbox cyborg plasma surface: periods 2.2/3.0, +noise scales 10/6, primary direction (2, 0, -0.3), secondary direction +(0, 2, 0.5), and stock perpendicular/parallel RGB endpoints. Its rendering +fields match the local Beaver Creek reference byte-for-byte except for the +intentional body layer displacement. Both existing presets and the new one +resolve the same verified noise volume through the active map's loader. +No new texture bundle or mod-system dependency is introduced. + +Body and arm offsets, depleted arcs, recharge/retreat and Overshield +precedence use the existing feature interfaces. Arm Shields remains the +owner of arm visibility and its distance/FOV cap. Authored custom colours +continue through the existing draw-local colour path. Preset style overrides +authored materials as ENHANCED does; CLASSIC keeps its original behaviour. +Cache entries include the preset identity, retaining stable shader copies +across option changes rather than mutating queued draws. Map cleanup and +bounded-capacity fallback remain unchanged. No new shared-engine hooks or +MCC loading changes are needed. + +Validation: 100 focused tests, including stock-surface bytes, separate preset +pointers, custom colour inheritance, arm suppression and switching back to +unchanged ENHANCED/CLASSIC; Windows, Android guest/host and web builds. +Hidden Windows captures compare CLASSIC, ENHANCED and CLASSIC WITH SPRINKLES +on Xbox Beaver Creek and check Arm Shields ON/OFF. Coldsnap 20th retains its +custom red shield colour. The actual menu was checked for the complete label +at 1280x960; only this setting's selector was widened. The comparison video +was decoded successfully and retained in `build/shield-sprinkles/evidence`. + +A two-peer local test with Sprinkles on the host and CLASSIC on the client +passed the comparator over 26 seconds: no mismatched seconds or measured +drift across 780 samples, with one client correction logged. No simulation +or protocol data changed. Android/browser runtime visuals, internet/WebRTC, +live split-screen and full campaign compatibility remain unverified. + +Mercury Falling also reached gameplay and showed the new surface through +recharge and retreat. The starting player's existing stock palette was +retained. The first fixture was refused for a misaligned appended script +reference; the aligned copy passed without game-code or original-map edits. +Its failed-run log remains available separately. The fixture only makes +intro/continuous scripts dormant, fixes the test pose and adds a damage +reference; rendering tags and map colour data remain intact. + +Cleanup removed about 4.0 GiB of temporary maps, duplicate binaries and raw +captures. All 403 generated save/profile files were archived with SHA-256 +verification and original relative paths recorded. About 22 MiB of evidence, +logs and scripts remain, with required platform builds/toolchains retained. + + +### Sprinkles recharge visibility + +The original comparison used independently captured frame numbers, which +made Sprinkles appear to complete recharge sooner. A synchronized diagnostic +capture now associates each image with the actual simulation time, recharge +progress, fade and displacement. At equal simulation times the two presets +already had the same half-second retreat and layer offsets, but the classic +surface's broad bands lost visible coverage faster as intensity decreased. + +Sprinkles alone now uses `f * (1 + 0.75 * (1 - f))` for recharge visibility, +where `f` is the existing fade. This keeps the broader surface readable into +the retreat. The envelope is monotonic, starts/ends at zero and retains its +original peak. Recharge progress, full-charge transition, half-second end, +body displacement and Arm Shields distance/FOV limits remain unchanged. +ENHANCED still uses the original visibility formula exactly. This adjustment +changes neither preset's shader profile, texture parameters or RGB selection; +it applies only while the recharge envelope is active. Damage, depletion, +Overshield, map/settings cleanup and Arm Shields OFF still cancel/suppress +through their established gates. + +The temporary diagnostic logging was removed from production sources. +The comparison video uses only matching recorded simulation times and +progress across all three columns (ENHANCED, Sprinkles before, Sprinkles +after), with missing capture intervals held equally. It includes body/arms, +a labelled one-third-speed retreat replay and an Arm Shields OFF control. +Distinct classic/CMT surface patterns are preserved; the comparison verifies +recharge behaviour and perceived fade rather than identical pattern pixels. + +The 101 focused tests include a regression that checks the Sprinkles-only +visibility compensation, monotonic falloff, unchanged displacement, exact +retreat endpoint and arm suppression, alongside existing profile/colour, +Overshield and lifecycle checks. Windows, Android guest/host and web builds +pass. Android/browser runtime visuals and live split-screen are not tested. + +Production Windows checks also passed recharge on CE Coldsnap 20th and MCC +Mercury Falling using the existing isolated fixtures, retaining their colour +selection. A Sprinkles-host/CLASSIC-client local network comparison passed +26 seconds with no mismatched seconds or drift over 780 samples; one client +correction was logged. Internet transport was not retested; no simulation +or protocol changes require a network version change. + +Alignment evidence records 125 body and 123 arm sample times shared by all +three captures, with zero difference in recorded time or recharge progress. +The comparison video decodes successfully. Cleanup removed about 6.3 GiB of +disposable output; all 341 generated save/profile files were archived with +SHA-256 verification and relative paths. About 11 MiB of evidence, logs and +scripts remain under `build/shield-retreat`, with required platform builds +and toolchains retained. Original maps and user saves were untouched. + + +## ENHANCED HONEYCOMB + +`display.shield_look = "honeycomb"` (or `HALO_SHIELD_LOOK=honeycomb`) +selects a newly authored procedural surface inspired by the user's Infinite +reference image. It is not an extracted Infinite shader or texture. The +hexagonal lines have broad luminous edges, moving bright patches, and a faint +connecting film. At the user's request the surface is thicker visually; +the approved ENHANCED stand-off from the armour is unchanged. + +The immutable body/arms profiles retain ENHANCED's exact parameters. The +cache key additionally records honeycomb ownership so switching presets +cannot restyle queued draws or mutate another preset. The existing colour +inheritance, Arm Shields pass and cap, depleted Bigass arcs, recharge/retreat, +and separate Overshield control remain responsible for their own behaviour. +No mod, map-family loader, gameplay or network state changes are involved. + +The current plasma noise cannot produce a structured hexagonal surface. +A minimal `port:` hook around the plasma draw therefore supplies and clears +draw-local surface uniforms and uses the same front-face culling as the +opaque model, restoring the plasma culling state afterwards. +`shield_honeycomb_gl.h` owns the GLSL pattern; `d3d8_gl.c` transports its +uniforms and `nv2a_psh.c` includes the extension. `nv2a_vsh.c` carries the +existing model UVs in one extra varying (zero for fixed-function draws). +This is necessary because the plasma outputs contain volume noise coordinates, +not the model UVs. One grid follows the skin through animation, without the +intersecting projections from the first prototype. Pixel derivatives soften +thin edges. Original UV island seams and texel-density differences can remain +on arbitrary custom models; this does not re-unwrap or replace map geometry. + +The procedural pass uses the already resolved colour constants (including +map/object colours and Overshield precedence), the existing shield intensity +and height fade. Its colour is 65% perpendicular / 35% parallel; the structured +surface has its own visibility instead of the plasma noise's angle-dependent +cutoff. Scale zero returns the original fragment result unchanged, including +for all other presets and unrelated map materials. The state is cleared after +each plasma draw; no texture allocation or map-owned resource is introduced. + +Validation: 126 focused shield/menu/harness checks pass, including exact +ENHANCED profile parameters, preset ownership, draw-uniform clearing and Arm +Shields suppression. Clean Windows, Android and web production builds pass. +Windows captures cover body/arms damage, depleted arcs, recharge and retreat, +an Arm Shields OFF control, CE Coldsnap 20th's red colour and MCC Mercury +Falling's starting-player gold. These are bounded isolated fixtures retaining +the maps' rendering assets, not full campaign or arbitrary-model validation. +The comparison contains 282 shared body times and 314 shared arm times with +zero recorded time difference. Weapon poses can differ between runs; matching +simulation time is not proof of pixel-identical animation. The video decodes +successfully and representative frames were inspected. + +CLASSIC, ENHANCED and CLASSIC WITH SPRINKLES were also captured against the +previous renderer. Their profiles and disabled procedural path are unchanged; +the captures are not pixel-identical (maximum sampled whole-frame mean RGB +differences of 0.121, 0.309 and 1.262 respectively on a 0-255 scale). A local +two-peer HONEYCOMB-host/CLASSIC-client check passed 26 compared seconds, +778 samples without drift and zero client corrections. No network version +change is needed for draw-only state. Android/browser runtime visuals, +internet transport, live split-screen, a full Overshield pickup sequence and +runtime map-family transitions were not retested in this assignment. + +Cleanup removed 32.9 GiB of temporary captures, test binaries, fixtures and +caches. All 992 generated save/profile files were archived with relative +paths and verified SHA-256 hashes before removing loose copies. About 37 MiB +of evidence, logs, scripts and archived saves remain in +`build/shield-honeycomb`; production builds and installed toolchains remain. +Original maps and user saves were untouched. + +## Honeycomb link refinement + +The regular UV hexagons remain the basis of the surface. Their linear size +is reduced by 20% on body and arms (scales 87.5 and 225), increasing the cell +count over the same area by about 56%. The shell displacement, ENHANCED +profiles, inherited RGB, recharge envelope and Arm Shields gates are unchanged. +This correction lives in the existing shield feature and its procedural GLSL; +it adds no shared-engine hooks or map-family compatibility changes. + +The edge band is wider with a softer surrounding halo and a small, bounded +contribution from the existing plasma alpha. This gives the surface more +visual substance without moving it farther from the armour. The baseline +is deliberately subdued: a continuous spatial pulse brightens and dims both +links and their glow, rather than leaving a uniformly bright wire grid. +The original per-cell pulse could assign different brightness to opposite +sides of a shared link. Sampling a continuous field removes that discontinuity +while retaining visible variation. Filtering uses the unfolded UV footprint, +since derivatives of the folded edge distance can cancel at shared edges; +unresolved cells fade to their approximate average instead of sparkling. + +These changes do not weld model geometry or re-unwrap UV islands. Separate +displaced pieces, UV seams and different texel densities remain visible on +some models. This is a refinement of the regular pattern, not a claim of a +seamless shell on every authored model. + +The focused suite passes 164 checks, with the five optional asset checks +subsequently passing using the local stock, CMT and Bigass maps (169 unique +checks in total). The new regression executes the shipped pattern with fixed +pixel derivatives and samples both sides of all six shared edges over time, +checking continuity, a persistent dim link and a distinct pulse. It also +checks convergence when cells become subpixel. This CPU check does not replace +GPU visual testing. Clean Windows, Android and web production builds pass. + +Windows body/arm captures compare 70 matched samples each, with zero recorded +differences in simulation time, intensity or displacement. A temporary hook +holds the existing full-hit intensity and displacement from 11 to 12 seconds +for maximum-flare inspection; the video labels this controlled interval and +also shows recharge and retreat. The hook is absent from production sources +and builds. The video decodes successfully. Matching time does not guarantee +identical weapon idle poses. + +Clean-production Windows checks cover Arm Shields OFF, CE Coldsnap 20th's +authored red and MCC Mercury Falling's starting-player gold on the existing +bounded fixtures. A two-peer Honeycomb-host/CLASSIC-client check passed 26 +compared seconds, 780 samples, no drift and no client corrections. No protocol +or simulation state changed, so no network version increment is required. +Android/browser runtime visuals, internet transport, full campaign play and +runtime map-family transitions were not retested. Other presets retain their +profiles and scale-zero bypass; their visual output was not recaptured in +this refinement. + +Temporary captures, fixtures, binaries and generated caches were removed. +All 403 test save/profile files were archived with their relative paths and +verified SHA-256 hashes before removing loose copies. The comparison video, +diagnostic stills, logs and scripts remain in `build/honeycomb-refinement`; +production builds and installed toolchains remain available. Original maps +and user saves were untouched. + + +## CLASSIC HONEYCOMB + +`display.shield_look = "classic_honeycomb"` combines the CLASSIC WITH +SPRINKLES profile with the existing smaller pulsing honeycomb grid. It sits +immediately after CLASSIC WITH SPRINKLES in FOV & Viewmodels. CLASSIC remains +the default, and the four existing profiles and their shader formulas are +unchanged. + +Both components use the original Classic plasma fragment's resolved RGB, +including its viewing-angle blend, map-authored colour inheritance, object +colour channels and animated Overshield precedence. The new composite adds +65% of the original plasma opacity to 65% of the honeycomb opacity. The plasma +fills the spaces between links while the grid retains its continuous spatial +pulse and persistent dim edges. This avoids adding two full-bright surfaces. +It uses the same draw and shell; there is no second geometry layer or added +displacement. Body and arms use the existing 87.5 and 225 cell scales. + +The feature-owned profile uses both the Sprinkles and Honeycomb flags, so it +inherits the Classic recharge/retreat visibility compensation, common arcs, +map-colour rules and Arm Shields gate/cap. Queued draws select the mode by +retained shader identity. Existing reset paths clear it on map load/unload. +The only shared-engine change extends the existing draw-local honeycomb +setter with a Classic-composite flag, stored in an unused uniform component. +This is necessary because the feature module cannot access the final plasma +fragment colour. Pattern/composition logic stays in shield_honeycomb_gl.h; +there are no map-family loader or compatibility changes. Scale-zero draws +still return the original fragment and clear the composite flag. + +UV seams, disconnected geometry and varying texel density remain as described +above; the composite does not re-unwrap or weld models. Network messages and +simulation are unchanged, so no protocol version increment is needed. + + +Validation on Windows (release, portable, PGO/LTO off): 140 focused tests pass, +including local Xbox, CMT and Bigass reference checks. The new tests execute +the actual fragment composition and verify exact preservation of resolved +RGB, independent link brightness, disabled bypass, uniform cleanup, profile +identity, map/object colours, Arm Shields OFF and preset/reset/capacity paths. +Production Windows, Android and web builds pass after removing all temporary +capture instrumentation. This was self-reviewed; no independent review ran. + +The comparison uses bounded copies of Xbox Beaver Creek, with fixed spawn, +scripted depletion and recharge, plus a clearly labelled capture-only hold +of the existing maximum flare from 11 to 12 seconds. Each view has 70 matched +time/intensity samples. Body displacement matches exactly. Arms retain the +existing distance/FOV cap; differing idle poses cause a maximum recorded +0.000238 model-unit displacement difference. The test did not change that cap. +The video includes recharge, retreat and slowed maximum-flare views and passes +a full decode check. The capture hook is absent from production sources. + +Production runs additionally cover CE Coldsnap 20th and MCC Mercury Falling +body/arms with their red and starting-player gold respectively, depleted arcs, +recharge and a separate Xbox Arm Shields OFF run. These use bounded local +fixtures with fixed spawn/script access; they are not full campaign runs. +A Classic Honeycomb host and CLASSIC client passed 26 compared seconds, +780 ticks, with no drift or client corrections. Original maps were untouched. +Android/web visual runtime, Linux native builds, internet transport, live +map-family transitions and overshield pickup visuals were not rerun; the +existing overshield tests and unchanged colour-precedence path were checked. + +Local evidence, including the comparison video, build/test logs and scripts, +is retained under build/classic-honeycomb. Test saves are archived with paths +and verified hashes before removing loose copies. Disposable fixtures, +captures, binaries and generated map caches are removed; the current production +build and installed toolchains remain available. Nothing was pushed to main. + + +### Classic Honeycomb body link visibility correction + +The original composite tinted its grid with the final Classic fragment RGB. +Inspection of the translated plasma shader showed that RGB already contains +the noise mask, not just the resolved palette. This erased body links between +bright plasma bands; the first-person result was separately approved. + +Only the Classic Honeycomb body now combines 45% of the original plasma RGB +with 85% of the pulsing grid tinted by the existing resolved vertex colour +(xD1), before the plasma noise mask. It retains the original fragment alpha, +so hit/recharge/retreat and overshield fades remain authoritative. The vertex +colour comes from the same Classic profile, authored-colour overrides, object +tint and viewing-angle calculation; no Enhanced palette is substituted. +The arm branch is byte-for-byte unchanged. Density, geometry, offsets and all +other presets are unchanged. The existing feature-owned draw mode distinguishes +arms (1) and body (2); the shared call only forwards that mode. + +Validation: 140 focused tests pass, including a dark-plasma regression that +requires visible, colour-matched body links and exact preservation of the arm +formula. Windows, Android and web production builds pass. Windows Beaver Creek +captures compare 66 body and 69 arm samples at identical time and intensity. +Body displacement matches exactly; idle-pose-dependent arm caps differ by at +most 0.000066 model units. The labelled maximum flare is held by temporary +capture-only instrumentation, removed from production. The video includes +recharge/retreat, passes a full decode, and shows body links across dark regions. + +Production checks on the bounded CE Coldsnap 20th and MCC Mercury Falling +fixtures retain their red and starting-player gold, with visible body links, +depleted arcs and recharge. Runtime validation is Windows/OpenGL only; Linux +builds, Android/web visuals, internet play and map-family transitions were not +rerun. The previous 780-tick no-drift network check remains the last network +validation; this correction changes no simulation or protocol. Self-review +covered the full diff. Evidence is in build/classic-honeycomb-body; temporary +maps/captures/binaries are removed and test saves archived with verified hashes. + + +## CLASSIC HONEYCOMB (formerly CLASSIC HONEYCOMB 2) + +`display.shield_look = "classic_honeycomb2"` is a separate option immediately +following CLASSIC WITH SPRINKLES in FOV and Viewmodels. The original option and all +other presets retain their existing formulas. CLASSIC remains the default. + +The body links take their light directly from the resolved Classic plasma, +including its moving white highlights, as the approved first-person composite +does. In the body formula, `original.rgb * (0.45 + pattern * 1.5)` supplies the +Classic membrane and plasma-lit links; `resolved_colour * pattern * 0.08` +retains only a faint connecting core between waves. The body's original alpha +is preserved, so its hit, recharge and retreat envelope stays authoritative. +Grid coordinates, density, geometry and displacement are unchanged. The +first-person arms use the existing Classic Honeycomb composition unchanged, +including the Arm Shields gate and distance/FOV cap. + +The earlier trial multiplied a separate palette-coloured grid by a bounded +pre-colour noise mask. Its prominent constant core and lack of the Classic +highlight response did not deliver the requested arm-like brightness flow. +The correction multiplies the grid through actual plasma RGB instead. It needs +no extra combiner-register input, so the temporary pixel-translator argument +has been removed. The correction is entirely in the feature-owned shader helper; +no source/, engine translator, map loader or compatibility changes remain. +Only mode 3 uses this body formula. Modes 0, 1 and 2 retain their existing +formulas, and scale-zero draws still return the original fragment. + +A separate cached profile flag distinguishes the new body mode from queued +Classic Honeycomb draws. Both arms still select mode 1. Existing feature reset +and draw-uniform cleanup handle switching and map boundaries. The profile is +otherwise identical, retaining Classic With Sprinkles colour authority, authored +colours, overshield precedence, arcs, recharge and retreat. No simulation or +network protocol changes are involved. + +Validation: 151 focused shield tests pass. The revised composition regression +holds the hex grid fixed while changing the actual Classic plasma and requires +the link contribution to brighten with it, including a white highlight when +that palette channel is zero. It failed on the earlier formula before passing +with the correction. Profile identity, queued-mode separation, map/object +colours, lifecycle/capacity, the exact arm formula and the faint body-link core +are also covered. Windows, Android and web production builds pass. Self-review +covered the full diff; no independent review ran. Capture instrumentation is +removed from production sources and builds. + + +Windows captures compare the previous and corrected CLASSIC HONEYCOMB 2 at +138 matched body samples and 137 arm samples, with identical game time and +intensity. Body displacement matches exactly. The unchanged idle-pose arm cap +differs by at most 0.000054 model units. A second, clearly labelled capture +holds the body's intensity at 1 and displacement at 0.0125 for 100 samples +from 9.6 to 12.9 seconds. Its close-up shows moving link highlights separately +from the recharge envelope. These fixed-flare holds are capture-only hooks. +The comparison includes normal recharge/retreat, the held flare and unchanged +arms, and passes a full video decode check. + +Production checks on bounded CE Coldsnap 20th and MCC Mercury Falling fixtures +retain their red and starting-player gold colours, respectively, with arcs +and normal recharge. A separate Xbox Arm Shields OFF run has no arm layer. +Original maps and saves remain untouched. Runtime visuals were checked on +Windows/OpenGL only; Linux builds, Android/web visuals, internet transport, +live map-family transitions and overshield pickup visuals were not rerun. +The existing overshield regressions pass and its precedence code is unchanged. +This fragment-only correction changes no simulation/protocol code; the previous +26-second / 771-tick net_compare pass remains the latest network check, with +zero position drift, one client correction and three seconds of differing +shield reports. + +Evidence, test/build logs and reproduction scripts are in +build/classic-honeycomb2-flow. The previous trial evidence remains in +build/classic-honeycomb2. This run's disposable fixtures, raw captures, temporary +binaries and generated map caches are removed after verification. Test saves +are archived losslessly with original relative paths and verified SHA256 hashes. +The production build and installed toolchains remain. The finalized menu names +and their stable configuration values are listed at the top of this document. diff --git a/docs/upstream_562_validation.md b/docs/upstream_562_validation.md new file mode 100644 index 0000000000..1270b621a1 --- /dev/null +++ b/docs/upstream_562_validation.md @@ -0,0 +1,281 @@ +# OpenCE release 562 integration review + +Reviewed 6-7 November 2026. This record covers the authorized merge into +GulchCE testing. The subsequent user-authorized promotion is recorded below. + +## Inputs and boundaries + +- Testing base: `c9014bea1af3654812a3a5c1573c23cfaaa41547`. +- OpenCE main: `fc9deb0b10eaae1d62caedb0710968b4e77e6e16`, release PR + [562](https://github.com/OpenCommunityEdition/OpenCE/pull/562). +- Merge: `9871f523eb958c05e6ae6d3bed4ccd2a0946f53c`. +- Follow-ups: `7d18c17b6` (platform layout and integration fixtures) and + `ab85031c8` (generated frontend controls). + +This is an upstream merge plus focused fixes to existing render behavior. +Xbox and Custom Edition loading paths remain independent of MCC. MCC guards, +script extensions, Workshop discovery and package code are preserved. The +changes introduce no new MCC compatibility behavior. Network protocol/version +is unchanged: the additional fixes affect render caches and clocks, not wire +formats or shared simulation rules. + +## Decisions for each incoming PR + +PR numbers below refer to OpenCE. The release merge also contains its direct +follow-up commits; those are included in the resulting tree review. + +| PR | Subject | Integration decision | +| --- | --- | --- | +| 441 | Browser ping ordering and progress | Take, including the queued-request delay correction `a06b4204`. | +| 522 | StageKit executable replacement | Take the ETXTBSY fix. | +| 525 | Controller remapping | Preserve GulchCE's existing fixed implementation (`f1e6ec`). | +| 526 | Controller dead zones | Take with stock `-1` defaults; regenerate CE and modern menus, preserve platform-specific row placement and footer actions. | +| 530 | First-person melee interpolation | Preserve GulchCE's stronger fix `5f23f414f`. | +| 534 | Widescreen chapter titles | Preserve GulchCE's corrected implementation `06c945c62`. | +| 536 | Scope blur edges | Take the half-pixel correction. | +| 538 | Scope zoom labels | Take Xbox glyph/bounds corrections; preserve separate CE/MCC layout and GulchCE reticle sizing. | +| 539 | Server map names and immediate rotation | Take case handling and long-rotation fixes. | +| 540 | Reversed-depth bias | Preserve GulchCE's depth/shield correction `65180b24c`. | +| 541 | Lens-flare occlusion slots | Take corrected upstream ownership/visibility serial handling (`6f1a31d6`, `cdd43c65`); preserve renderer extensions. | +| 542 | Interpolated shadow center | Take while retaining existing crash guards. | +| 545 | Camera shake per tick | Take with explicit cache resets on map initialization, disposal and checkpoint restore. | +| 546 | Contrail point ticks | Combine exact nominal tick duration with GulchCE's existing aging fix; preserve per-frame physics and texture animation. | +| 547 | Flag cloth ticks | Take with explicit reset of accumulated time and last tick on map initialization, disposal and checkpoint restore. | +| 548 | Empty-handed flashlight | Take the focused local-player change; preserve optional dynamic lighting. | +| 550 | Sound Doppler | Preserve GulchCE's corrected implementation `1bd6ebbd9`. | +| 551 | Sound declick/flush | Preserve GulchCE's corrected implementation `033440749`. | +| 552 | Lightning per tick | Preserve GulchCE's stronger lifecycle/seed fix `22b34ca16`. | +| 553 | Stale script object indices | Take while retaining MCC early casts, parameter and thread hooks. | + +Our contrail aging fix already existed at `5b3693666`. Upstream's contribution +is the exact elapsed tick duration rather than a sum of render-frame times. +The combined implementation retains independent frame/state deltas, advances +state transitions separately for each elapsed tick, handles double speed, and +invalidates its clock after a checkpoint restore. It does not reconstruct +historical emission poses or provide general sub-tick trail interpolation. +See [contrail timing](contrail_timing.md). + +## Combined implementation review + +Reviewed subsystem ownership, declarations, initialization/disposal, saved-state +callbacks, callers, generated menus/assets, documentation and regression +fixtures. Camera matrices and flag/contrail clocks live outside the saved game +buffer. They therefore require three small registrations in the existing +`game_state.c` after-load callback table; subsystem-only resets cannot observe +a restored checkpoint. Reset implementations remain in their owning modules. +Every added game-source change carries a `port:` marker. + +Existing audio, first-person, lightning, cinematic-title, render interpolation, +MCC and Workshop implementation files remain unchanged from the testing base. +Shared renderer changes retain GulchCE depth, shield and lighting integration. +No unrelated refactoring was justified. Fixture adaptations account for retained +MCC interfaces, visibility ownership fields and generated controller rows; +they do not disable those production checks. + +## Automated validation + +Code at `ab85031c8` passed the complete +[Build workflow](https://github.com/chestahh/GulchCE/actions/runs/42316635322): +Windows, Linux, Android and web jobs all succeeded. These branch jobs build +their configured debug variants; release/profile jobs gated on main were not +run. The local Windows build additionally used portable release, PGO off and +LTO off, LLVM 23.1.4. + +- Linux's combined engine/harness/StageKit regression command: **2,429 passed, + 27 skipped**, plus seven passing subtests. The other Linux regression + commands passed, including controller/HUD and co-op checkpoint tests. +- Web: page/importer/service-worker and build checks, Chromium/Firefox smoke + and room tests, and native WebRTC interoperability passed. Retail-map + browser internet gameplay was not exercised. +- Android: guest/native/app build and configured importer/touch checks passed. +- [MCC workflow](https://github.com/chestahh/GulchCE/actions/runs/42316635244): + both jobs passed. Reader/validator: 1,407 passed/14 skipped and 36 passed; + Windows adapter commands: 40 passed/one skipped, 1,520 passed/16 skipped, + and 38 passed. +- Local focused effects/render/cache/web checks: **272 passed, five skipped**. +- Local audio/Doppler/cancellation/depth checks: **60 passed, six skipped**. +- Local frontend generation/navigation/presentation checks: **38 passed**. +- Lifecycle and contrail harnesses extract production functions and the real + after-load callback table. Deliberately restoring frame-based aging or + removing lifecycle hooks causes the relevant tests to fail. Their graphics, + attachment and physics stubs do not prove visual or map compatibility. +- `git diff --check` and changed-document local-link checks passed. + +An exploratory broad local Windows run was not green (1,642 passed, 730 failed, +13 skipped), largely because that suite assumes POSIX headers/linker flags, +CRT behavior and newline conventions. Actual integration-fixture failures were +fixed and rerun. The final Linux CI suite above is the supported full-suite +result; the exploratory run is not counted as a pass. Local Android/web ninja +targets are unavailable in the Windows-generated graph; CI supplies full builds. + +## Real-engine Windows qualification + +Runs used hidden windows, separate writable data/save roots, at most two +instances, original retail/CE map copies, and the unmodified `net_compare` +judge/tolerances. Original maps, Workshop packages and user saves were untouched. + +- Xbox Blood Gulch, two peers: **47 matched seconds**, no reported divergence + or judge problems, normal exits; maximum position difference 0.143. +- Local Custom Edition Death Island, two peers: **51 matched seconds**, no + reported divergence or judge problems, normal exits; maximum position + difference 0.0924. These are tolerance-based checks, not bit-exact equality. +- One process: Xbox b40 checkpoint save/revert, attempted Workshop Mercury + load, CE Death Island, then Xbox Blood Gulch. The checkpoint was restored, + CE loaded, and subsequent Xbox simulation ran with normal exit and no + exception. Mercury's resource selection failed, so this is **not** a + successful three-family transition test. +- Campaign co-op without a valid checkpoint cue reported aim/alive divergences. + An exact source snapshot of the pre-merge testing commit reproduced the same + 55-degree opening aim discrepancy, later alive discrepancy and maximum + position difference (1.2973). This establishes those observed symptoms also + occur before the merge; it does not establish that campaign co-op is correct. + +- A corrected two-peer b40 run executed `game_save` at tick 901 and + `game_revert` at tick 1201; the host confirmed the saved game was taken. + Both processes exited normally after continued simulation. The unchanged + judge still reported the opening cinematic aim difference (56 degrees), + so this run is not a clean campaign-network pass. +- The pre-merge testing binary also refused Workshop Mercury with the same + missing matching `bitmaps.map` diagnostic. A second current-build attempt, + Workshop `3675162225/ring_mp`, failed resource selection too. Both exited + normally. Workshop discovery succeeded; MCC gameplay did not start. + Inspection shows Mercury's map under the item's `maps` folder and resource + files under `halo1/maps`, while `steam_workshop_package_folder` selects the + map's containing folder. This is evidence for a path-selection issue, not + proof that those resources are otherwise compatible. No package files were + moved and no unrelated MCC compatibility changes were made. + +## Promotion limits + +The MCC resource-loading failure recorded above is resolved by the follow-up +below. At the end of that review, main was left unchanged while campaign co-op +qualification remained open. The later promotion does not close that limitation. +Green asset-free tests and builds do not establish full MCC or campaign compatibility. No visual A/B captures were added in this merge; +the prior contrail captures documented in `contrail_timing.md` cover the earlier +aging fix, not this exact integrated binary. + +Local logs, result JSON, runner scripts and losslessly archived test saves are +retained in the integration worktree's ignored `build/` folder. Copied test maps, +generated map caches and disposable baseline build outputs are removed after +qualification. The ready Windows build remains available for follow-up testing. + +Cleanup retained approximately 59 MiB for the Windows executable, symbols and +SDL runtime, and 5.1 MiB of runtime evidence including verified save archives. +The temporary baseline source/build, copied maps, caches, build objects and +qualification virtual environment were removed. Logs and package-version records +remain available; no test game processes remain running. + +## MCC resource-discovery follow-up + +The user subsequently authorized fixing resource discovery generally, including +both authored package resources and installed shared MCC resources. Code commit +`2959e99b22f1079bf3bd9c63c11578d16928fa62` implements that rule without map-name, +checksum or Workshop-ID exceptions. Read [resource installation](mcc_maps.md#subscribed-steam-workshop-items) +and the [loading walkthrough](reading/maps_and_resources.md) for precedence, +ownership and the small MCC-only virtual-file-service hook. + +Review covered the entire resolver, its host-file caller, package and shared +precedence, independent types, bounded paths, disabled discovery, lifecycle, +resource validation and content-based network identity. No shared simulation +or wire format changed; resource contents still decide peer admission. No new +cache or open-stream owner was introduced. The existing resource reader rejects +invalid authored files and ambiguous shared matches rather than replacing them. +No unrelated refactoring was needed. + +Seven synthetic cases failed before implementation. The final local Windows +suite covering Steam discovery, MCC resources/identity/maps/protocol, Android +imports and web build checks passed **259 tests**, with **10 platform/tool +skips**. Tests cover unrelated package identities, mixed case, per-type lookup, +local overrides, invalid/unmatched/ambiguous resources, other Steam libraries, +path bounds, forbidden paths, disabled discovery and unchanged Xbox/CE roots. +Windows portable release rebuilt successfully with PGO/LTO off. + +Code at `2959e99b2` passed the complete +[Build workflow](https://github.com/chestahh/GulchCE/actions/runs/42319635736): +Windows, Linux, Android and web, including Chromium/Firefox and native WebRTC +checks. Both jobs in the +[MCC workflow](https://github.com/chestahh/GulchCE/actions/runs/42319635900) +also passed: reader/validator commands reported 1,425 passed/14 skipped and +36 passed; Windows adapters reported 40 passed/one skipped, 1,538 passed/16 +skipped and 38 passed. Platform debug/release scope is as documented above. + +Real-engine checks used the same hidden, isolated, at-most-two-instance rules: + +- Mercury Falling loaded its own bitmap and sound files directly from the + Workshop item's `halo1/maps`; player simulation advanced through tick 570. +- Ring loaded the shared bitmap file directly from the installed MCC game; + player simulation advanced through tick 720. +- Two-peer Ring: **45 matched seconds**, no divergences or judge problems, + maximum position difference 0.2002, normal exits. +- Two-peer Bigass: **41 matched seconds**, no divergences or judge problems, + maximum position difference 0.0736, normal exits. Both peers selected the + package's authored bitmap and sound resources in place. +- One process completed Xbox b40 checkpoint save/revert, refusal of a deliberately + invalid MCC package bitmap, Mercury with authored resources, Ring with shared + resources, CE Death Island and a return to Xbox Blood Gulch. Every post-load + simulation marker executed; the saved state restored, the invalid resource + was refused, all intended maps loaded, no exception was reported and exit was + normal. This closes the previously failed resource/transition check. + +The invalid package was a disposable fixture, not an edit to installed content. +No Workshop resources were copied into shared folders to obtain these passes. +The executable used for these runtime checks has SHA-256 +`6cb70d41816f35224b143007483c1234ca232eeecc01e33fb2c0eed2ab29f66f`. +Logs/results are under `build/runtime-562-final`, including +`workshop-mercury-fixed`, `workshop-ring-fixed`, `mcc-ring-network`, +`mcc-bigass-network` and `lifecycle-resources-fixed`. Save archives are verified +against SHA-256 manifests before removing loose inactive copies. Copied test +maps and generated map caches were removed; originals remain untouched. + +These checks establish the repaired discovery paths and representative gameplay, +not complete MCC campaign compatibility. Shared sound discovery/selection is +covered synthetically; the installed shared-resource runtime example required +external bitmaps only. The pre-existing b40 co-op comparison issue remains a +separate qualification limit. Main was not promoted at that point. + +## Subsequent promotion to main + +On 7 November 2026, the user explicitly requested merging current testing into +main and monitoring CI. The initial merge inputs were testing +`9bf9554aa86dbeba9fa49f5d8ff1b99f2ba82c1b` and main +`c5ae133ff69701ca9d48d32808969c13afe00d9f`. That testing revision's +[platform builds and regression checks](https://github.com/chestahh/GulchCE/actions/runs/42324288419) +and [MCC validation](https://github.com/chestahh/GulchCE/actions/runs/42324288332) +passed before the conflict-free merge. + +Before release publication, the user clarified that the CPU mask-conversion and +collision-continuation optimization is still being developed and must be left +out. The initial Build/release run was cancelled. A focused revert on main +removes all changes from `9bf9554aa`; testing and its ongoing work are untouched. +The corrected engine, platform and build configuration exactly match +the previously reviewed testing revision +`045cb99bce3fba18a3ddb61f88e327ba4544d09e`. Main's existing README and agent/coding +guidance remain intact, and the Workshop diagnostic branch is excluded. + +The release-note collector additionally suppresses the withdrawn optimization's +original annotation only in histories containing its withdrawal, as documented +in [the changelog guide](changelog.md). A real Git-history regression reproduces +the stale note before correction and checks retained testing previews and later +restoration notes. This bookkeeping change does not alter game code. + +The optimization commit remains in Git ancestry because main was already pushed; +when that work is ready, its full intended change must be deliberately restored +and validated. Merging later descendants alone will not restore reverted lines. +Fresh CI on corrected main builds debug and release configurations before +publication. The b40 co-op comparison discrepancy remains an explicitly recorded +pre-existing qualification limit, not a resolved defect or a clean network pass. + +## Validated lighting follow-up + +Later on 7 November, eight controlled combat runs supported retaining only the +CPU mask conversion. Testing `e96be13db711ad305cd812a8211d7894d13135ae` restored +the previous recursive collision traversal and passed its +[Build workflow](https://github.com/chestahh/GulchCE/actions/runs/42328462980) +and [MCC validation](https://github.com/chestahh/GulchCE/actions/runs/42328462944). +The user then authorised promotion of that validated work. This later promotion +deliberately restores the mask conversion, its tests and documentation; it does +not restore the discarded shared collision rewrite or alter the preceding MCC +resource work. The original withdrawn release note stays suppressed, while the +follow-up supplies its own reviewed annotation. See the +[controlled comparison](dynamic_emitter_expansion_acceptance.md#controlled-comparison-and-retained-change-7-november-2026) +for all eight results and the remaining sustained-FPS limit. diff --git a/docs/visibility_queries.md b/docs/visibility_queries.md new file mode 100644 index 0000000000..aac2aca30d --- /dev/null +++ b/docs/visibility_queries.md @@ -0,0 +1,166 @@ +# Desktop visibility query readback + +The desktop renderer uses OpenGL 4.5 sample-count queries for lens flare +occlusion. Earlier AMD investigation logs reported invalid query names; the +pool fix uses glCreateQueries to instantiate and validate typed objects. +This remains in place. It does not establish a driver root cause. + +The f85d9d91 comparison on Radeon RX 6900 XT / driver 26.8.1.260806 recorded +176438 available same-query comparisons: 142382 direct CPU results were +nonzero while their mapped results were zero; the other 34056 pairs were +both zero. No mapped count was nonzero, no mapped value changed after the +direct read, and no comparison reported an unavailable query or GL error. +This isolates a discrepancy in query-buffer/mapped delivery on that system. +It does not prove the underlying implementation or driver cause. + +AMD's proprietary driver consumes direct CPU results, bypassing +query buffers, persistent mappings and copy fences entirely. Three batches own +4096 queries each; initialization validates all 12288 names for nonzero, +uniqueness, instantiated objects and GL errors before publishing any IDs. +The obsolete desktop single-query fallback and comparison setting are removed. + +Each test records its result slot and pixel/MSAA scale. On the CPU path, Present polls the +oldest submitted batch, checks GL_QUERY_RESULT_AVAILABLE for each query, +and requests GL_QUERY_RESULT only when available. CPU query reads save, +clear and restore the query-buffer binding so pointers cannot become buffer +offsets. Results are published in submission order, including repeated slots +and completed zeros. Partial batches resume at their first unread query. +An entire batch remains reserved until all its results are consumed. + +For other GL vendors, a buffered path avoids per-query +CPU readback. It retains the same typed, validated query pool, ordered batches +and per-test scaling. Each batch has a disjoint 4096-element range of a coherent +persistent mapping. Sealing writes an uncopied sentinel, then queues the +query-result copies followed by a fence. Later Presents poll that fence after +the swap with `GL_SYNC_FLUSH_COMMANDS_BIT` and zero timeout; neither query +availability alone nor a fixed number of elapsed frames permits reading the +mapping. Only a signaled fence permits publishing the complete batch and reusing +its queries and storage. A full ring retains the previous results and skips new +measurements. This also prevents repeated result slots from aliasing in-flight +writes, unlike the original shared per-slot mapping. + +Copy or fence failures quarantine the affected batch and switch later reads +to direct CPU delivery; its cached counts remain +unchanged and its queries cannot be reused. Completed fence objects are deleted; +the 48 KiB mapped buffer, like the query pool, belongs to the GL context until +shutdown. Buffer allocation or mapping failure falls back to direct CPU delivery. +AMD never allocates this buffer or queues these copies. This vendor boundary is +intentional: completion checks alone did not solve AMD's mapped-delivery problem. + +The current frame's batch is sealed before the swap and first polled after a +later swap. Normal submission asks the driver no synchronous questions; +optional `debug.gl_debug` checks still query errors. The uncopied sentinel +detects missing copies after a fence completes without requiring those checks. +There is no glFinish, wait loop or blocking fence wait. Ordinary driver-call +overhead still exists and needs performance testing on AMD and NVIDIA. + +Game-side result requests return the latest completed count immediately. +When all batches are busy, new measurements are skipped and completed counts +remain available. Persistent GPU overload can therefore delay visibility +changes. Query-read errors quarantine the batch without publishing a false +zero or permitting uncertain query reuse; other batches continue. If all +batches fail, counts freeze and the log identifies the errors. The pool is +context-owned until shutdown, matching the existing GL device lifetime. + +GLES atomic counters and boolean queries, depth testing, polygon bias, shader +generation, Xbox/Custom Edition/MCC dispatch and networking are unchanged. +The desktop CPU and buffered paths are excluded by `HALO_GLES`; +neither establishes that Android's reported lighting issue is fixed. +Map changes retain the existing device-owned result-slot lifecycle. This is +a repair to the common renderer's result delivery, not an MCC adaptation or +gameplay change, and needs no protocol version change. + +API reference: [glGetQueryObject](https://registry.khronos.org/OpenGL-Refpages/gl4/html/glGetQueryObject.xhtml) +explains availability, blocking result requests and query-buffer pointer +interpretation. The CPU path checks availability before requesting each result. +[ARB_buffer_storage](https://registry.khronos.org/OpenGL/extensions/ARB/ARB_buffer_storage.txt) +specifies that server writes to a coherent persistent mapping become visible to +the CPU after the corresponding fence completes. + +`tools/test_visibility_readback_contract.py` compiles the actual allocation, submission, +readback and retrieval functions against a delayed GPU. It covers delays beyond +the ring, partial completion, ordering, repeated slots, scaling changes, zeros, +capacity, reuse, GL-error quarantine, binding restoration and invalid pools. +Negative controls must fail when key safety conditions are deliberately broken. +The CPU cases assert that no buffer or fence operations occur, including on AMD. +Buffered cases additionally cover copy completion later than query completion, +disjoint storage, fence placement, zero-timeout polls, map failure fallback, +copy errors, missing fences and failed waits. The tests compile the production +functions, rather than a separate implementation of their logic. + +With `debug.gl_debug` enabled, `visibility CPU` or `visibility buffer` summaries appear every 120 +frames. `submitted` and `completed` count batches in that interval; `pending` +counts current sealed, non-quarantined batches; `oldest_age` is their maximum +age in frames. `samples` counts consumed query results, `nonzero` counts their +nonzero raw counts, and `raw_max` is their largest raw count. `unavailable` +counts polls that deferred consumption, `dropped` counts skipped measurements, +and `failures` counts GL errors and buffer/fence failure reports. Unavailable polls alone are normal; sustained +drops, failures or absent completions need review. + +The b0c5d017 AMD test used this normal asynchronous CPU path on Radeon +RX 6900 XT / driver 26.8.1.260806, at 1920x1200 with anti-aliasing off. The +player reported correct lights with no flickering. Its emitted summaries +recorded 7416 submitted and completed batches, 36160 query results and 32405 +nonzero results, with no unavailable polls, dropped measurements or readback +failures. The process exited normally. The log supports successful delivery; +visual correctness comes from the player's report, not the counters alone. + +No diagnostic launcher or special rendering setting is needed. For a regression +report, enable `debug.gl_debug` (`HALO_GL_DEBUG=1`), keep lens-flare occlusion +enabled, and capture the startup lines and `visibility CPU` summaries along +with GPU/driver, map, resolution, anti-aliasing, symptoms and a short video. +Check visible glows, occlusion behind solid cover, repeated camera movement, +map changes and restart. Include frame-rate observations: this validation does +not establish performance parity across all drivers or GPUs. Earlier diagnostic +launchers and test instructions have been retired; historical commits and +delivered packages retain the investigation steps. + +## NVIDIA performance validation + +On 18 October 2026, the RTX 5070 Ti / NVIDIA 617.42 / Core i7-14700K comparison +used Windows portable release builds with PGO and LTO. All other objects were +shared; only the renderer and its GL loader differed between original c8cf7d83, +CPU fix 92eaa0cd and NVIDIA optimization 95748a74. Nine 75-second hidden real-GL +runs alternated the three variants, each with fresh saves, the Xbox A10 opening, +1920x1080 output, AA off, occlusion on, interpolation on, VSync off and uncapped +FPS. Each sample window covered 10-60 seconds after the first visibility query. +An identical in-memory timer recorded Present-entry intervals; detailed profiling +hooks were absent. All slow frames inside the window were retained. + +| Renderer | Median average FPS | FPS range | Mean frame time | p99 frame time | 1% low FPS | +| --- | ---: | ---: | ---: | ---: | ---: | +| Original | 1211.27 | 1208.84-1252.71 | 0.8256 ms | 1.5456 ms | 448.31 | +| CPU fix | 645.84 | 639.28-1000.26 | 1.5484 ms | 3.0935 ms | 253.96 | +| NVIDIA optimization | 1178.51 | 788.32-1188.02 | 0.8485 ms | 1.6259 ms | 335.01 | + +Each metric is the median of three per-run measurements. The 1% low is the +reciprocal of the mean of the slowest 1% of intervals. Median throughput improved +82.5% over the CPU fix and was 2.7% below the original. The wide run-to-run ranges +are material, and slow-frame performance has not fully recovered. This is one +uncapped scene, not a deterministic replay, a GPU-only timer or evidence of the +same gain at a capped frame rate. Background applications and driver scheduling +were not controlled; no driver or power settings were changed. + +Detailed profiling put the CPU readback routine near 0.025 ms/frame, much less +than the earlier roughly 0.69 ms/frame regression. Additional time appeared in +draw submission and presentation. Removing flushes, error checks or pool audits, +shrinking the pool, reducing availability polls, changing CPU read timing and +using non-waiting CPU result requests did not recover throughput. The measured +improvement comes from the NVIDIA buffered path; the exact internal driver +mechanism is not established. Its error checks remain enabled. Profiling hooks +and experimental variants are not part of the production renderer. + +For renderer commit 95748a74, Windows, Linux, Android and web debug/release CI +passed, along with MCC map validation. Linux CI reported 439 passed and 6 skipped; +26 focused local visibility, MCC shader and protocol tests passed. Local web +tests encountered five Windows-only Unix-path/pthread limitations; the web CI +tests passed on their supported host. Android build success is not Android GPU +runtime validation, and no new AMD hardware run was available. + +The normal local Windows release also completed Xbox A10 -> MCC Tiny Halo -> +Xbox A10 transitions with 4x MSAA and occlusion enabled. A delayed console marker +confirmed simulation continued after each load. Thirty visibility summaries +reported no unavailable polls, dropped measurements or readback failures; the +process exited normally. Captures and logs were retained. This is a bounded +smoke test, not full map compatibility or visual occlusion coverage. No Custom +Edition maps were available for a local runtime test. diff --git a/docs/windows_stutter_investigation.md b/docs/windows_stutter_investigation.md new file mode 100644 index 0000000000..0dd5f8783a --- /dev/null +++ b/docs/windows_stutter_investigation.md @@ -0,0 +1,174 @@ +# Windows irregular-hitch investigation + +This records the initial investigation. The subsequent implementation, +validation and remaining limits are documented in +[Renderer preparation](render_preparation.md). + +Players reported irregular hitches on Custom Edition and MCC maps in both +singleplayer and multiplayer, on two successive GulchCE builds. Reports +include Dynamic Lighting enabled and disabled; switching to current OpenCE +reportedly removed the hitches. This investigation does not yet establish +the cause of that difference or provide a gameplay fix. + +## Scope and source findings + +The inspected GulchCE revision is `d0b597a59`, built on Windows with +`--portable --release`. Upstream main was verified remotely on 29 October +2026 as `f2597b704d59e66257dba7629f22a0f78f5f3d09`, matching the local +upstream reference. An upstream executable was not run for this investigation. + +The shared renderer's `program_get` in +[d3d8_gl.c](../port/linux/src/d3d8_gl.c) loads a saved program binary or +synchronously links a program when that cache misses. This work happens on +the drawing thread when a shader combination is first encountered. Both +upstream and GulchCE contain this mechanism. + +The existing `--stalls` diagnostic in +[lighting_performance_build.py](../tools/lighting_performance_build.py) +predated the direct desktop link path. Its status-query matching also became +ambiguous when `program_cache_load` added another query with identical text. +`instrument_shader_stalls` now brackets compilation and both linking paths, +including their completion-status queries, without timing the cache loader +as a link. These hooks exist only in diagnostic builds. The regression tests +inspect the instrumented real functions and check the cache-loader exclusion. + +The optional honeycomb surface is emitted into every translated pixel shader, +with a uniform selecting the disabled path. A diagnostic-only alternative +omitted its pixel-shader declarations and call. No production shader or +feature setting was changed. Removing this code did not eliminate shader-link +hitches, so this experiment does not justify changing the feature as a fix. + +## Custom Edition runtime evidence + +The successful runs used an NVIDIA RTX 5070 Ti, driver 617.42, Windows OpenGL, +1920x1080, a 120 FPS cap, V-sync off, Dynamic Lighting off, and the classic +shield look. They ran CE Death Island in a local match with seven Heroic bots +and automated player input. Audio and screenshots were disabled. Each process +was hidden, used isolated saves, disabled internet hosting, and exited normally +after 110 seconds. Pacing summaries cover process seconds 20 through 105. +The combat histories differed; the numbers are observations, not an A/B speedup. + +| Diagnostic | Worst frame | Frames over 50 ms | Observation | +| --- | ---: | ---: | --- | +| Production renderer with timing hooks, empty application shader cache | 35.117 ms | 0 | A separate 32.953 ms frame included 2.132 ms compiling and 21.671 ms linking. | +| Honeycomb pixel code omitted, empty application shader cache | 254.669 ms | 1 | The worst frame included 3.177 ms compiling and 224.898 ms linking 15 programs. | +| Same experimental renderer, reusing its previous application shader cache | 34.711 ms | 0 | The worst frame included 26.604 ms linking one new program. | + +The cached repeat made 78 binary-cache lookup attempts and linked four +programs, compared with 90 links in its preceding run. Its total measured +link time was 46.564 ms rather than 1,142.732 ms. Different combat histories +and driver-cache state prevent treating these totals as a controlled speedup. +They support cache misses as a contributor, while showing that a previous +playthrough does not necessarily cover every program a later one encounters. + +The empty application caches do not imply cold driver caches. The separate +driver cache was not cleared or otherwise controlled. The temporary probe also +timed application binary-cache reads and writes; neither accounted for the +large link stall above. The worst production-renderer frame was not explained +by its measured shader calls, so shader work is not established as the only +source of slow frames. + +Three earlier sandboxed runs failed their local loopback connection and stayed +in menus. They are excluded from gameplay conclusions. Retrying outside the +sandbox reached gameplay. + +## Matching Digsite reproduction + +The reporter subsequently identified an RTX 5070 Ti and +`mcc_maps/DigsiteMP/10.map`. The installed Digsite package was found outside +the build directory. The map, its bitmap/sound resource files, and menu data +were copied into an isolated test directory; original maps, configuration, +saves and shader caches were not modified. + +These runs used the same revision and GPU above, 2560x1440, a 120 FPS cap, +V-sync off, MSAA 8x, 16x anisotropic filtering, highest model detail, +1024-pixel shadows, per-pixel lighting, first-person legs and viewmodel +shields. The user's shield settings were Shield Glow enabled and +`classic_honeycomb2`. Other Dynamic Lighting switches were already off. +Audio processing remained enabled with volume zero. Each hidden process +ran a local Slayer match with seven Heroic bots and automated player input +for 160 seconds, with isolated saves and internet hosting disabled. + +The temporary probe timed shaders, simulation, rendering, input, UI, +network frame work, presentation and MCC texture handling. It retained +frame measurements in memory and wrote them on exit. Summaries below use +gameplay frames at simulation tick 600 or later, excluding map startup +and the first 20 simulation seconds. Rendering contains the shader and +texture measurements: these columns are nested, not additive. + +| Run | Shader-cache seed | Worst settled frame | Frames over 50 ms | Observation | +| --- | --- | ---: | ---: | --- | +| User settings | A copy of the player's existing cache | 74.868 ms | 1 | 62.433 ms linking three programs, 4.056 ms compiling, 0.572 ms in simulation. | +| Dynamic Lighting disabled | Cache saved by the preceding run | 12.974 ms | 0 | Worst frame included 9.480 ms linking. | +| User settings restored | Cache saved by the disabled run | 30.196 ms | 0 | Worst frame included 26.710 ms in MCC texture handling and no shader compile/link calls. | + +The first run also recorded a separate 27.083 ms frame with 26.010 ms in +MCC texture handling and no shader compile/link calls. The restored-settings +run still encountered one 20.195 ms frame containing 17.390 ms of linking. +Its final program counters were 126 binary-cache loads, three links and no +driver-refused binaries. Thus cache reuse reduces observed shader work even +with Shield Glow restored; it does not cover every later shader combination. + +These are different bot combat histories with progressively populated +application and driver caches. The disabled run is not a controlled measure +of the cost of Dynamic Lighting, and none of these timings establishes a +general speedup. The measured 75 ms hitch was predominantly synchronous +shader work, rather than a simulation or network-frame stall. That does not +rule out other causes in other frames or sessions. + +MCC texture timing initially wrapped the entire `xgpu_mcc_texture_get` in +[mcc_texture_bridge.c](../port/linux/src/mcc_texture_bridge.c), including +identity lookup, palette handling and first-use upload. It must not be +reported as GPU upload time alone. Source inspection shows retained GPU +textures, with replacement on P8 palette changes and cleanup on disposal. +The adapter does not rebuild every texture on every frame. + +A fourth run restored the same user settings and reused the third run's +cache, with additional clocks inside `xgpu_mcc_texture_upload` in +[xbox_textures.c](../port/linux/src/xbox_textures.c). Its worst settled +frame was 15.104 ms: 8.916 ms in MCC texture handling, including 2.300 ms +decoding pixels and 0.762 ms in texture image upload calls for 18 texture +preparations. No program linking occurred in that frame. The remaining +texture-handling time includes allocation, GL state changes and other +adapter work; the probe does not attribute it more precisely. + +That run also measured two 2048x2048, 12-level texture preparations during +startup at 23.022 and 21.581 ms. Respectively, 9.653/8.834 ms was CPU decode +and 8.777/8.352 ms was spent in GL texture image calls. These startup events +demonstrate first-use preparation costs but do not identify the exact +textures responsible for the earlier settled 26 ms measurements. The fourth +run did not reproduce those long settled texture stalls. Its upload detail +messages were emitted only after preparations over 2 ms; extra logging and +clocks make this diagnostic unsuitable as a clean performance comparison. + +The evidence now includes a reproduction on the reported map and GPU. +Campaign, remote multiplayer, AMD and Intel were not tested. A controlled +OpenCE executable comparison on a shared Xbox/CE map remains necessary to +attribute the reported fork-specific difference; OpenCE does not provide +the same MCC loading path. Shader/resource preparation during gameplay is +an established source of hitches, but a safe gameplay fix is not established +by this investigation. + +## Validation and retained evidence + +The normal Windows release build passed. The corrected diagnostic backend +and the Digsite diagnostic variants compiled separately, and the nine focused +tests in +[test_lighting_performance.py](../tools/test_lighting_performance.py) passed. +The review covered timing boundaries, the direct-link and binary-cache paths, +test assertions, MCC texture ownership, and the limits of the runtime evidence. +No game, network, +map-family, or optional-feature behavior changes were made. Android and web +builds were not run for this Windows diagnostic-tool correction. + +Local scripts, settings, build metadata, frame CSVs, logs, summaries and +verified save archives are under `build/stutter-20261029` and +`build/stutter-digsite10`. These local outputs +are not committed. The experimental renderer is not a proposed gameplay fix. +Generated map caches and temporary diagnostic binaries were removed; the +normal Windows build and original maps and saves were preserved. The Digsite +cleanup additionally removed its copied map/resource files after comparing +their hashes with the originals: 1,158,338,456 bytes removed, approximately +16 MB retained as diagnostic evidence. Save archives were verified before +removing their loose copies. Production source hashes and local document +links were checked after testing. diff --git a/port/android/README.md b/port/android/README.md index bcf9830def..3671cfc29c 100644 --- a/port/android/README.md +++ b/port/android/README.md @@ -55,18 +55,40 @@ are serialized and the activity refuses to import while the game process runs. Limits are 4,096 files, 16 GiB total, less than 2 GiB per map, 256 KiB per JSON file and 64 declared campaign missions. Hub/flashback mission kinds are refused. -Start the game after importing. Enable **CAMPAIGN MISSIONS** in Settings > -Network Setup > Map Sharing > MCC Packages for mission ordering and progression; +Start the game after importing. Enable **CAMPAIGN MISSIONS** in Modern Settings > +Online > Map Sharing > MCC Packages (Network Setup > Map Sharing > MCC Packages +in the Stock, Classic PC and Xbox styles) for mission ordering and progression; it is off by default. **COLLECTION FOLDERS** can group identified imported packages without Steam. See [MCC packages](../../docs/mcc_maps.md) for desktop discovery, resource rules and compatibility limits. -The archived [Android importer test](https://github.com/chestahh/GulchCE/blob/1db929c5e34101a45f644436e031016b5584c7bf/tools/test_mcc_android_importer.py) -compiles and runs the actual Java core with +`tools/test_mcc_android_importer.py` compiles and runs the actual Java core with JDK 17+, including failure rollback, cancellation, malformed metadata, path traversal and legacy/save preservation. These checks do not exercise an Android -document provider or establish on-device rendering compatibility. This wider -test is not included in the focused upstream regression subset. +document provider or establish on-device rendering compatibility. + +## Lighting availability + +The optional Dynamic Lighting renderer is excluded from Android builds after +reports of missing or dark models across multiple device families. Video Setup +does not show its submenu. Saved projectile, muzzle, emitter, AR/Needler glow, +Shield Glow and occlusion settings cannot activate it; their values may remain +in an older `config.toml`, but are ignored. New Android configs omit these keys. +The stock game's lights, muzzle flashes, explosions and shield surfaces remain. + +The build replaces the feature modules with +[`dynamic_lighting_disabled.c`](guest/dynamic_lighting_disabled.c), which leaves +stock radii, colours and materials unchanged and retains the overshield map +reset. Android's model shaders omit the added uniforms and volume samplers, +including when Per-Pixel Lighting is enabled. Disabling settings alone would +not remove shader code emitted regardless of their values. + +Network host policy and messages are unchanged. Android can still host or join +games with other lighting settings; it cannot render Shield Glow even when +requested by the host. Animated Overshield surfaces remain available and obey +the existing host policy. This is an Android compatibility fallback, not a +diagnosis or repair of every device rendering issue. Device playtests are still +needed to confirm recovery on the affected devices. ## Requirements @@ -291,14 +313,14 @@ The buttons at the top of the screen: vibration setting of the game's profile), aiming with the gyroscope (off by default), a floating move stick (off by default: the stick goes where your thumb lands in the lower left of the screen), the opacity of - the controls, "Held buttons don't aim" (off by default: a finger - that swipes from a button only holds it), - "Hide or add buttons" (hide a button, add a copy of a - button) and "Edit buttons size". - - "Edit buttons layout": drag the controls, and the "Options" button - itself, to new positions, then push "Save" in the middle of the - screen. "Export" and "Import", beside it, write and read a layout - file with the file picker of the system. + the controls, whether held-button swipes also aim (on by default), and + a three- or four-finger cheat-menu gesture (three by default). The panel + scrolls on short displays. It also contains "Hide or add buttons" (hide + a button, add a copy of a button) and "Edit buttons size". + - "Edit buttons layout": drag the controls to new positions, then push + "Save". "Export" and "Import" write and read a layout file with the + file picker of the system. Export, Import and Save stay centered; + Options can be dragged with the controls. - "Look sensitivity". "Hide" and "Options" act when the finger lifts on them: a swipe that @@ -306,6 +328,48 @@ starts on them turns the view instead. The app keeps the layout in its own preferences, not in `config.toml`. Removing the app's data or the app removes the layout. +Layout files now use version 4 and still accept versions 1–3. OpenCE version-4 +files without GulchCE's cheat gesture field use the three-finger default. Imported +Options positions are bounded and rescaled to the display. Drawn controls +accept touches in Android's edge-gesture area; empty-space edge swipes +remain available to Android. + +Settings > Gamepad > Android Controls > Gyro Aim adds independent gyro settings. The +default, **TOUCH SETTINGS** (`input.gyro_aim = "legacy"`), keeps the layout's +saved gyro switch and look sensitivity, including imported layouts. A new +layout still has gyro off. **OFF**, **ON** and **ZOOM ONLY** override that +switch; ON and ZOOM ONLY use their own horizontal/vertical sensitivity and +inversion, leaving swipe sensitivity and the profile's Invert Look alone. +Unzoomed samples in ZOOM ONLY are discarded, so entering zoom does not +apply a turn accumulated earlier. Hiding controls or backgrounding the app +still stops gyro input. + +| Setting | Default | Environment variable | +| --- | --- | --- | +| `input.gyro_aim` | `"legacy"` | `HALO_GYRO_AIM` | +| `input.gyro_sensitivity_horizontal` | `1.0` (0.25–10) | `HALO_GYRO_SENSITIVITY_HORIZONTAL` | +| `input.gyro_sensitivity_vertical` | `1.0` (0.25–10) | `HALO_GYRO_SENSITIVITY_VERTICAL` | +| `input.gyro_invert_horizontal` | `false` | `HALO_GYRO_INVERT_HORIZONTAL` | +| `input.gyro_invert_vertical` | `false` | `HALO_GYRO_INVERT_VERTICAL` | + +The **Cheat Menu** setting in **Android Controls** is off by default +(`android.cheat_menu = false`, `HALO_ANDROID_CHEAT_MENU`). When enabled, +the **CHEATS** touch button beside **Hide/Touch** opens the menu directly +during offline gameplay or while hosting co-op or multiplayer. It remains +visible when the gameplay controls are hidden, and disappears in the layout +editor, cinematics and when joining another host. +Touch **Options > Cheats** also exposes invincibility, unlimited ammunition, +bottomless clip, super jump, omnipotence, no fall damage, Medusa, bump +possession, Easy Rider (no rider ejection), weapon/powerup/vehicle spawning +and camouflage. It +uses the same cheat actions as a desktop host. Only the host controls them +in a network game; joining clients cannot submit requests. +While it is enabled, tapping three fingers together (or four, as selected +in General) within a quarter-second also opens it. The gesture releases +held controls before opening the dialog; it does nothing when Cheats is off. +Menu-owned switches restore their prior values when disabled or leaving a +map; closing the dialog alone keeps them enabled. Spawns are ordinary game +objects. See [implementation, credits and limits](../../docs/reading/bots_and_android_features.md). ## Settings @@ -645,8 +709,28 @@ whose storage GL cannot allocate is streamed instead. writes a buffer a queued draw reads, and the static ranges' reuse, unload and reload, address reuse and allocation failure. +Streamed vertices and indices go into pooled buffers, a buffer for each +draw that no queued draw reads, written with `glBufferSubData` and reused +only after the ring's frame fence (`web_chunk_get`, as the web build does): +unsynchronized writes into the frame's one stream buffer drew some +geometry as long spikes on Snapdragon. Geometry the game writes once (the +models and BSPs of Xbox, Custom Edition and mod maps) gets GL buffers of +its own, filled at its first draw and released when it unloads; a range +whose storage GL cannot allocate is streamed instead. +`tools/test_android_static_geometry.py` checks both with fake GL: no upload +writes a buffer a queued draw reads, and the static ranges' reuse, unload +and reload, address reuse and allocation failure. + ## Find problems +CI APK packages include a `diagnostics` folder with a bounded, read-only +[shader-log collector](diagnostics/collect_shader_logs.py) and +[instructions](diagnostics/README.txt). Run it on a computer with Python 3 and +Android platform-tools, then relaunch the app and reproduce the problem. It +records the game's log tag, shader source/errors and device information into +a ZIP without changing app settings or saves. Device logs remain on the +computer until the tester chooses to share them. + - Enter `adb logcat -s halo` to see the log of the port and the errors of the game. `files/debug.txt` is the log of the game. - If the guest code stops, the log shows the registers and the frame chain. @@ -683,6 +767,39 @@ and reload, address reuse and allocation failure. instruction there), so `tools/android_asm_convert.py` writes each as the vector form, which leaves the register and the exception flags the same. + +### GulchCE updates + +The Android updater checks `chestahh/GulchCE` releases and compares GulchCE +Build workflow numbers, just like the desktop updater. Release tags stay +`build-` and asset filenames stay unchanged. Successive Android +releases must use the same signing key to install over each other. + +### GulchCE release signing + +The Build workflow requires both repository Actions secrets on `main`: + +- `ANDROID_KEYSTORE_BASE64`: the base64-encoded permanent keystore, with + private-key alias `halo`. +- `ANDROID_KEYSTORE_PASSWORD`: the keystore and private-key password (the + same password for both). + +Missing either secret fails the Android job before compilation and prevents +release publication. Other branches may use a debug key when both secrets +are absent; a partial signing configuration fails on every branch. Malformed +base64 fails during staging; Gradle rejects an invalid keystore or password. + +Keep an offline backup of the permanent keystore and its password outside +the repository. Reuse this key for every release; do not regenerate it when +moving machines or updating secrets. GitHub cannot return secret values. + +Older GulchCE releases used a new runner debug key for each build. Moving +from one of those APKs to the permanent key requires backing up saved games, +uninstalling the old app and installing the new one (see the backup commands +above). Uninstalling deletes the app's data. Later releases signed with the +permanent key can update in place. Stable signing does not guarantee that +Google Play Protect immediately removes an unfamiliar-developer warning. + ## Custom Edition texture storage When the chip policy enables texture fixes, cached Custom Edition textures diff --git a/port/android/app/src/main/java/com/halo/decomp/AndroidCheatMenu.java b/port/android/app/src/main/java/com/halo/decomp/AndroidCheatMenu.java new file mode 100644 index 0000000000..7333c2f45f --- /dev/null +++ b/port/android/app/src/main/java/com/halo/decomp/AndroidCheatMenu.java @@ -0,0 +1,71 @@ +package com.halo.decomp; + +import android.app.AlertDialog; +import android.content.Context; +import android.widget.Button; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.Switch; +import android.widget.Toast; +import java.util.function.Consumer; + +/* Optional offline/host controls, inspired by thelinkin3000's Android overlay + * and its credited antecedents, hardran3's OpenCE-Ultrahand and HaloDrones. + * The engine rechecks permission for every request; UI state is advisory. */ +final class AndroidCheatMenu { + private static native int nativeState(); + private static native boolean nativeRequest(int request); + + static boolean enabled() { + return (nativeState() & 1) != 0; + } + + static boolean available() { + return (nativeState() & 3) == 3; + } + + private static boolean request(Context context, int command) { + if (nativeRequest(command)) return true; + Toast.makeText(context, "Cheats unavailable or queue busy", Toast.LENGTH_SHORT).show(); + return false; + } + + static void show(Context context, Consumer openDialog) { + int state = nativeState(); + if ((state & 2) == 0) { + openDialog.accept(new AlertDialog.Builder(context).setTitle("Cheats") + .setMessage("Available during gameplay when playing offline or hosting the game.") + .setPositiveButton("Close", null).create()); + return; + } + LinearLayout panel = new LinearLayout(context); + panel.setOrientation(LinearLayout.VERTICAL); + int padding = (int)(16 * context.getResources().getDisplayMetrics().density); + panel.setPadding(padding, padding, padding, padding); + String[] switches = {"Invincibility", "Unlimited ammunition", "Bottomless clip", "Super jump", + "Omnipotent", "No fall damage", "Medusa mode", "Bump possession", "Easy Rider"}; + for (int i = 0; i < switches.length; i++) { + final int command = i; + Switch toggle = new Switch(context); + toggle.setText(switches[i]); + toggle.setChecked((state & (1 << (8 + i))) != 0); + toggle.setOnClickListener(view -> { + if (!request(context, command | (toggle.isChecked() ? 0x100 : 0))) + toggle.setChecked(!toggle.isChecked()); + }); + panel.addView(toggle); + } + String[] actions = {"Spawn weapons", "Spawn powerups", "Active camouflage", "Spawn vehicles"}; + for (int i = 0; i < actions.length; i++) { + final int command = switches.length + i; + Button button = new Button(context); + button.setText(actions[i]); + button.setOnClickListener(view -> request(context, command)); + panel.addView(button); + } + ScrollView scroll = new ScrollView(context); + scroll.addView(panel); + openDialog.accept(new AlertDialog.Builder(context).setTitle("Cheats") + .setView(scroll).setNegativeButton("Close", null).create()); + } +} diff --git a/port/android/app/src/main/java/com/halo/decomp/TouchControls.java b/port/android/app/src/main/java/com/halo/decomp/TouchControls.java index d8dcfd6243..9cfd5be97a 100644 --- a/port/android/app/src/main/java/com/halo/decomp/TouchControls.java +++ b/port/android/app/src/main/java/com/halo/decomp/TouchControls.java @@ -1,5 +1,9 @@ package com.halo.decomp; +/* Layout/editor additions adapted from thelinkin3000/halo-ce-universal + * 18a94774a73ca275e9c0ab4f281e492ad8bb656e (AGPL-3.0-or-later), + * built on MrBruh's OpenCE touch controls. See the provenance guide. */ + import android.app.AlertDialog; import android.content.Context; import android.content.SharedPreferences; @@ -26,6 +30,8 @@ import android.view.WindowManager; import android.widget.Button; import android.widget.LinearLayout; +import android.widget.RadioButton; +import android.widget.RadioGroup; import android.widget.ScrollView; import android.widget.SeekBar; import android.widget.Switch; @@ -61,6 +67,7 @@ public final class TouchControls extends View implements SensorEventListener, In private static final int TOOLBAR_EXPORT = -6; private static final int TOOLBAR_IMPORT = -7; private static final int TOOLBAR_SAVE = -8; + private static final int TOOLBAR_CHEATS = -9; private static final float TOOLBAR_RADIUS = 28; private static final float OPTIONS_RADIUS = TouchLayout.OPTIONS_RADIUS; /** the editor's items, this far apart */ @@ -156,6 +163,7 @@ private static final class Kind { private static native void nativeState(int lx, int ly, int rx, int ry, int lt, int rt, int buttons); private static native void nativeLook(float dx, float dy); private static native void nativeGyro(float dx, float dy); + private static native int nativeGyroMode(); private static native void nativeLookReset(); private static native int nativeRumble(); private static native int nativeScene(); @@ -191,6 +199,7 @@ private static final class Kind { /** each finger on a toolbar item: {x, y, item}; the item acts when it lifts there */ private final SparseArray toolbarFingers = new SparseArray<>(); private final int[] axes = new int[6]; + private boolean menuFingersDown; private int lookPointer = -1; private float lookX; private float lookY; @@ -218,6 +227,7 @@ private static final class Kind { private boolean showing; private long shownSince = -1; private boolean gyroRegistered; + private int gyroMode = -1; private int lastAmplitude; private long lastVibration; private final int[] bindings = DEFAULT_BINDINGS.clone(); @@ -231,6 +241,13 @@ public void run() { if (!deviceInputActive) return; scene = nativeScene(); + int mode = nativeGyroMode(); + if (mode != gyroMode) { + gyroMode = mode; + gyroAim.reset(); + nativeLookReset(); + updateSensors(); + } updateShowing(); readBindings(); updateRumble(); @@ -362,6 +379,28 @@ private float editorY() { return logicalHeight / 2; } + private float cheatsX() { + return logicalWidth / 2 - toolbarRadius(TOOLBAR_RADIUS) - toolbarRadius(OPTIONS_RADIUS) - 12; + } + + private float cheatsY() { + return Math.max(toolbarY(), insetTop / scale + toolbarRadius(OPTIONS_RADIUS) + 8); + } + + private int hitControl(float x, float y) { + for (int i = 0; i < layout.size(); i++) { + if (layout.shown(i) && layout.type(i) != TouchLayout.LEFT + && inside(x, y, layout.x(i), layout.y(i), layout.radius(i))) + return i; + } + int stick = TouchLayout.LEFT; + float reach = editing ? 1 : STICK_REACH; + if (layout.shown(stick) && !held(stick) + && inside(x, y, layout.x(stick), layout.y(stick), layout.radius(stick) * reach)) + return stick; + return NOTHING; + } + private float toolbarRadius(float radius) { return Math.max(radius, minimumRadius()); } @@ -537,6 +576,9 @@ private int hit(float x, float y) { if (inside(x, y, optionsX(), optionsY(), toolbarRadius(OPTIONS_RADIUS))) return TOOLBAR_OPTIONS; if (!editing) { + if (AndroidCheatMenu.available() + && inside(x, y, cheatsX(), cheatsY(), toolbarRadius(OPTIONS_RADIUS))) + return TOOLBAR_CHEATS; if (inside(x, y, logicalWidth / 2, toolbarY(), toolbarRadius(TOOLBAR_RADIUS))) return TOOLBAR_TOGGLE; return hidden ? NOTHING : hitControl(x, y); @@ -555,28 +597,11 @@ private int hit(float x, float y) { return NOTHING; } - /** the control under a point (logical units), or NOTHING */ - private int hitControl(float x, float y) { - for (int i = 0; i < layout.size(); i++) { - if (layout.shown(i) && layout.type(i) != TouchLayout.LEFT - && inside(x, y, layout.x(i), layout.y(i), layout.radius(i))) - return i; - } - int stick = TouchLayout.LEFT; - float reach = editing ? 1 : STICK_REACH; - if (layout.shown(stick) && !held(stick) - && inside(x, y, layout.x(stick), layout.y(stick), layout.radius(stick) * reach)) - return stick; - return NOTHING; - } - /** * whether a finger went down where Android keeps its edge gestures; in * sticky full screen the first swipe in from an edge only shows the * system bars, and Android also hands it over as an ordinary finger. - * Only fingers on no control are kept out of them: the zones stay their - * full size while the bars are hidden (all of the hidden 3-button bar), - * and a control drawn there would never press + * Drawn controls still take touches there; only empty-space swipes stay with Android. */ private boolean inGestureZone(float x, float y) { int[] insets = ((HaloActivity) getContext()).getSystemGestureInsetsPixels(); @@ -613,7 +638,24 @@ public boolean performClick() { private void gameTouch(MotionEvent event) { int index = event.getActionIndex(); int id = event.getPointerId(index); - switch (event.getActionMasked()) { + int action = event.getActionMasked(); + if (action == MotionEvent.ACTION_DOWN) + menuFingersDown = false; + // Consume the chord until every finger lifts; no held shot or look leaks into the dialog. + if (!menuFingersDown && action == MotionEvent.ACTION_POINTER_DOWN + && event.getPointerCount() == layout.menuFingers + && event.getEventTime() - event.getDownTime() <= 250 && AndroidCheatMenu.enabled()) { + reset(); + menuFingersDown = true; + post(() -> AndroidCheatMenu.show(getContext(), this::openDialog)); + return; + } + if (menuFingersDown) { + if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) + menuFingersDown = false; + return; + } + switch (action) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_DOWN: fingerDown(id, event.getX(index), event.getY(index)); @@ -645,7 +687,7 @@ && inFloatingZone(x, y) && !inGestureZone(px, py)) { floatStick(x, y); target = stick; } - if (target == TOOLBAR_OPTIONS || target == TOOLBAR_TOGGLE) { + if (target == TOOLBAR_OPTIONS || target == TOOLBAR_TOGGLE || target == TOOLBAR_CHEATS) { toolbarFingers.put(id, new float[] {px, py, target}); } else if (target != NOTHING) { owners.put(id, target); @@ -726,6 +768,8 @@ private void toolbarAction(int item) { showOptions(); else if (item == TOOLBAR_TOGGLE) setHidden(!hidden); + else if (item == TOOLBAR_CHEATS && AndroidCheatMenu.available()) + AndroidCheatMenu.show(getContext(), this::openDialog); performClick(); } @@ -854,7 +898,9 @@ private void openDialog(AlertDialog dialog) { } private void showOptions() { - String[] items = {"General", "Edit buttons layout", "Look sensitivity"}; + String[] items = AndroidCheatMenu.enabled() + ? new String[] {"General", "Edit buttons layout", "Look sensitivity", "Cheats"} + : new String[] {"General", "Edit buttons layout", "Look sensitivity"}; AlertDialog dialog = new AlertDialog.Builder(getContext()) .setTitle("Options") .setItems(items, (d, which) -> { @@ -863,8 +909,10 @@ private void showOptions() { } else if (which == 1) { editing = true; setHidden(false); - } else { + } else if (which == 2) { post(this::showSensitivity); + } else { + post(() -> AndroidCheatMenu.show(getContext(), this::openDialog)); } }) .setNegativeButton("Close", null) @@ -907,6 +955,11 @@ private void showGeneral() { gyro.setText(gyroscope != null ? "Gyroscope aiming (experimental)" : "Gyroscope aiming (not on this phone)"); gyro.setChecked(layout.gyroscopeEnabled); gyro.setEnabled(gyroscope != null); + if (gyroMode != -1) { + gyro.setText("Gyroscope: controlled by Settings > Gamepad > Android Controls > Gyro Aim"); + gyro.setChecked(gyroMode != 0); + gyro.setEnabled(false); + } gyro.setOnCheckedChangeListener((view, enabled) -> { layout.gyroscopeEnabled = enabled; gyroAim.reset(); @@ -932,6 +985,22 @@ private void showGeneral() { }); panel.addView(buttonsStill); + panel.addView(text("Fingers that tap together to open Cheats (when enabled):")); + RadioGroup fingers = new RadioGroup(getContext()); + fingers.setOrientation(RadioGroup.HORIZONTAL); + for (int count = TouchLayout.MIN_MENU_FINGERS; count <= TouchLayout.MAX_MENU_FINGERS; count++) { + RadioButton choice = new RadioButton(getContext()); + choice.setId(count); + choice.setText(count + " fingers"); + fingers.addView(choice); + } + fingers.check(layout.menuFingers); + fingers.setOnCheckedChangeListener((group, count) -> { + layout.menuFingers = count; + saveLayout(); + }); + panel.addView(fingers); + TextView opacityLabel = text(""); SeekBar opacity = new SeekBar(getContext()); int steps = Math.round((TouchLayout.MAX_OPACITY - TouchLayout.MIN_OPACITY) * 20); @@ -1163,8 +1232,12 @@ private void toast(String message) { // ---------- the gyroscope and the vibration + private boolean gyroEnabled() { + return gyroMode == -1 ? layout.gyroscopeEnabled : gyroMode != 0; + } + private void updateSensors() { - boolean needed = deviceInputActive && showing && !hidden && layout.gyroscopeEnabled && gyroscope != null; + boolean needed = deviceInputActive && showing && !hidden && gyroEnabled() && gyroscope != null; if (needed && !gyroRegistered) { gyroAim.reset(); gyroRegistered = sensors.registerListener(this, gyroscope, SensorManager.SENSOR_DELAY_GAME); @@ -1177,7 +1250,7 @@ private void updateSensors() { @Override public void onSensorChanged(SensorEvent event) { - if (!deviceInputActive || !showing || hidden || !layout.gyroscopeEnabled || editing || openDialogs > 0) { + if (!deviceInputActive || !showing || hidden || !gyroEnabled() || editing || openDialogs > 0) { gyroAim.reset(); return; } @@ -1185,8 +1258,9 @@ public void onSensorChanged(SensorEvent event) { .getDefaultDisplay().getRotation(); if (gyroAim.sample(event.timestamp, event.values[0], event.values[1], rotation, gyroDelta)) { // as a swipe of this many logical units (which the profile's invert leaves alone) - nativeGyro(-gyroDelta[0] / LOOK_RADIANS_PER_UNIT * sensitivity, - -gyroDelta[1] / LOOK_RADIANS_PER_UNIT * sensitivity); + float gyroSensitivity = gyroMode == -1 ? sensitivity : 1f; + nativeGyro(-gyroDelta[0] / LOOK_RADIANS_PER_UNIT * gyroSensitivity, + -gyroDelta[1] / LOOK_RADIANS_PER_UNIT * gyroSensitivity); } } @@ -1274,6 +1348,8 @@ private void drawToolbar(Canvas canvas) { canvas.drawText("Drag the controls and Options, then push Save", middle, editorY() + toolbarRadius(OPTIONS_RADIUS) + 24, paint); } else { + if (AndroidCheatMenu.available()) + toolbarItem(canvas, cheatsX(), cheatsY(), OPTIONS_RADIUS, "CHEATS", false); toolbarItem(canvas, logicalWidth / 2, toolbarY(), TOOLBAR_RADIUS, hidden ? "Touch" : "Hide", false); } } diff --git a/port/android/app/src/main/java/com/halo/decomp/TouchLayout.java b/port/android/app/src/main/java/com/halo/decomp/TouchLayout.java index 90a6c010ff..d24d72ef3b 100644 --- a/port/android/app/src/main/java/com/halo/decomp/TouchLayout.java +++ b/port/android/app/src/main/java/com/halo/decomp/TouchLayout.java @@ -1,5 +1,9 @@ package com.halo.decomp; +/* Layout/editor additions adapted from thelinkin3000/halo-ce-universal + * 18a94774a73ca275e9c0ab4f281e492ad8bb656e (AGPL-3.0-or-later), + * built on MrBruh's OpenCE touch controls. See the provenance guide. */ + import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; @@ -11,7 +15,7 @@ * size and whether it shows, with the settings that go with them, in the * overlay's logical units. Places are kept for the display the layout is * on and saved on a 960 x 540 grid, so a layout moves between displays of - * other shapes. A layout file is Java properties text (version 3; 1 and 2 + * other shapes. A layout file is Java properties text (version 4; versions 1 through 3 * are still read). */ final class TouchLayout { @@ -26,6 +30,8 @@ final class TouchLayout { static final float MAX_OPACITY = 1f; static final float MIN_SENSITIVITY = 0.25f; static final float MAX_SENSITIVITY = 4f; + static final int MIN_MENU_FINGERS = 3; + static final int MAX_MENU_FINGERS = 4; /** the Options button's radius, before a finger's width (minimumRadius) */ static final float OPTIONS_RADIUS = 34; /** @@ -87,6 +93,8 @@ static final class Configuration { float opacity = 1f; /** the move stick goes where the thumb lands in the lower left, not at its place */ boolean floatingStick = false; + /** the fingers that tap together to open the overlay menu, MIN_MENU_FINGERS..MAX_MENU_FINGERS */ + int menuFingers = 3; /** a finger that holds a button also aims when it swipes */ boolean buttonsAim = true; /** where the Options button is, in logical units; NaN until it is dragged (TouchControls then places it) */ @@ -273,6 +281,7 @@ String exportConfiguration(float sensitivity) { values.setProperty("gyroscope", Boolean.toString(gyroscopeEnabled)); values.setProperty("opacity", Float.toString(opacity)); values.setProperty("floating-stick", Boolean.toString(floatingStick)); + values.setProperty("menu-fingers", Integer.toString(menuFingers)); values.setProperty("buttons-aim", Boolean.toString(buttonsAim)); if (optionsMoved()) { values.setProperty("options.x", Float.toString(optionsX * GRID_WIDTH / width)); @@ -323,6 +332,11 @@ static Configuration importConfiguration(String text) { layout.floatingStick = readBoolean(values, "floating-stick"); } if (version >= 4) { + // OpenCE version 4 layouts have no GulchCE cheat-menu gesture field. + int fingers = Integer.parseInt(values.getProperty("menu-fingers", "3")); + if (fingers < MIN_MENU_FINGERS || fingers > MAX_MENU_FINGERS) + throw new IllegalArgumentException("Invalid menu fingers"); + layout.menuFingers = fingers; layout.buttonsAim = readBoolean(values, "buttons-aim"); // (no place: Options where it always was) String x = values.getProperty("options.x"); diff --git a/port/android/app/src/main/java/com/halo/decomp/Updater.java b/port/android/app/src/main/java/com/halo/decomp/Updater.java index 266a98e96b..1b3f4eefd8 100644 --- a/port/android/app/src/main/java/com/halo/decomp/Updater.java +++ b/port/android/app/src/main/java/com/halo/decomp/Updater.java @@ -47,7 +47,7 @@ * app must keep for Android to install a new version over it. */ final class Updater { - private static final String REPOSITORY = "OpenCommunityEdition/OpenCE"; + private static final String REPOSITORY = "chestahh/GulchCE"; private static final String USER_AGENT = "halo-ce-universal-updater"; private static final int TIMEOUT_MILLISECONDS = 20000; /** the most a download (a release's zip, about 35 MB) or the app in it may be */ @@ -202,8 +202,8 @@ private static void ask(Activity activity, int latest) { if (activity.isFinishing()) return; new AlertDialog.Builder(activity) - .setTitle("Halo: new version") - .setMessage("A new version of Halo was detected (build " + latest + "; this is build " + .setTitle("GulchCE: new version") + .setMessage("A new version of GulchCE was detected (build " + latest + "; this is build " + BuildConfig.HALO_BUILD_NUMBER + ").\n\nDo you want to update? The game will close and start " + "the new version.") .setCancelable(false) @@ -215,7 +215,7 @@ private static void ask(Activity activity, int latest) { private static void confirmNever(Activity activity) { new AlertDialog.Builder(activity) - .setTitle("Halo: new version") + .setTitle("GulchCE: new version") .setMessage("Stop asking about new versions?\n\nTo ask again, set auto = true in the [update] section " + "of config.toml.") .setCancelable(false) @@ -247,7 +247,7 @@ private static void update(Activity activity, int latest) { layout.addView(status); layout.addView(bar); AlertDialog progress = new AlertDialog.Builder(activity) - .setTitle("Halo: new version") + .setTitle("GulchCE: new version") .setView(layout) .setCancelable(false) .show(); @@ -275,7 +275,7 @@ private static void update(Activity activity, int latest) { activity.runOnUiThread(() -> { progress.dismiss(); new AlertDialog.Builder(activity) - .setTitle("Halo: new version") + .setTitle("GulchCE: new version") .setMessage("The update failed:\n\n" + e.getMessage()) .setPositiveButton("OK", null) .show(); diff --git a/port/android/diagnostics/Collect-Shader-Logs.cmd b/port/android/diagnostics/Collect-Shader-Logs.cmd new file mode 100644 index 0000000000..3a84024435 --- /dev/null +++ b/port/android/diagnostics/Collect-Shader-Logs.cmd @@ -0,0 +1,9 @@ +@echo off +cd /d "%~dp0" +where py >nul 2>nul +if errorlevel 1 ( + python "%~dp0collect_shader_logs.py" %* +) else ( + py -3 "%~dp0collect_shader_logs.py" %* +) +pause diff --git a/port/android/diagnostics/README.txt b/port/android/diagnostics/README.txt new file mode 100644 index 0000000000..f8e6745aa1 --- /dev/null +++ b/port/android/diagnostics/README.txt @@ -0,0 +1,53 @@ +GulchCE Android shader diagnostic + +The APK beside this folder uses stock lighting on Android. Dynamic Lighting +is compiled out, including its glow shaders. Desktop lighting is unchanged. +This is a testing build; affected devices still need a visual check. + +INSTALL +Install the APK as an update, or use: + adb install -r ../app-debug.apk +If Android reports a signature mismatch, keep the existing app and saves. +Do not uninstall to work around it; report the mismatch instead. + +CAPTURE A PROBLEM +You need Python 3 and Android SDK Platform-Tools on the computer: + https://www.python.org/downloads/ + https://developer.android.com/tools/releases/platform-tools + +1. Enable USB debugging on the device. Connect it to the computer and accept + the device's authorization prompt. "adb devices" should show "device". +2. Windows: double-click Collect-Shader-Logs.cmd. Or run from this folder: + python collect_shader_logs.py + macOS/Linux: + python3 collect_shader_logs.py + If adb is not on PATH, provide its full path: + python collect_shader_logs.py --adb "C:/platform-tools/adb.exe" + With several devices connected, add --serial DEVICE_SERIAL. +3. Once capture starts, close and reopen GulchCE to capture startup GPU + information and shader compilation. Load the affected map and reproduce + missing/black models, weapon rendering or other visual problems. +4. Capture ends after two minutes, or press Ctrl+C to finish early. You can + select another limit with --seconds 300 (maximum ten minutes). +5. Send the resulting shader-logs-*.zip with the map name/family, affected + weapon/object, settings, what happened and an approximate time in the log. + The folder also contains reproduction.txt as a prompt for these details. + +WHAT IT CAPTURES +Only the game's "halo" log tag is recorded. Existing renderer diagnostics +include shader compiler errors and generated GLSL source, program-link errors, +and the startup OpenGL renderer/version. The collector preserves complete log +lines and creates a short summary, plus device/Android and installed-app info. +The bundled build revision is included if present. It keeps partial output +when adb disconnects, and stops after the time limit or about 32 MiB of logs. + +The collector does not enable lighting, change settings, install/stop the app, +clear device logs, copy maps/saves, or upload anything. Review logs before +sharing: game logs can include map paths and multiplayer details. A clean +summary alone does not establish that rendering is correct. Include a clip +or screenshot when the visual fault occurs without a shader error. + +No root access is needed. If the APK still fails to render, this capture can +also be made with a previously installed build for comparison; include which +APK was installed. It does not enable extra GL tracing, which may affect FPS. +Logcat reference: https://developer.android.com/tools/logcat diff --git a/port/android/diagnostics/collect_shader_logs.py b/port/android/diagnostics/collect_shader_logs.py new file mode 100644 index 0000000000..0743720d2a --- /dev/null +++ b/port/android/diagnostics/collect_shader_logs.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python3 +"""Read GulchCE shader/device logs over adb without changing app data or settings.""" +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path +import shutil +import subprocess +import time +import zipfile + +PACKAGE = 'com.halo.decomp' +PROPERTIES = ('ro.product.manufacturer', 'ro.product.model', 'ro.board.platform', + 'ro.build.version.release', 'ro.build.version.sdk', 'ro.opengles.version') +MAX_LOG_BYTES = 32 * 1024 * 1024 + + +def query(adb, *args): + result = subprocess.run([*adb, *args], capture_output=True, text=True, + errors='replace', timeout=15) + if result.returncode: + raise RuntimeError(result.stderr.strip() or result.stdout.strip() or 'adb command failed') + return result.stdout.strip() + + +def collect(adb, output, seconds): + if query(adb, 'get-state') != 'device': + raise RuntimeError('Authorize USB debugging on the phone, then retry.') + output.mkdir(parents=True, exist_ok=False) + metadata = {'started_utc': datetime.now(timezone.utc).isoformat(), + 'duration_limit_seconds': seconds, 'package': PACKAGE} + for key in PROPERTIES: + metadata[key] = query(adb, 'shell', 'getprop', key) + (output / 'app-version.txt').write_text(query(adb, 'shell', 'dumpsys', 'package', PACKAGE), encoding='utf-8') + revision = Path(__file__).with_name('build-revision.txt') + if revision.exists(): + shutil.copy2(revision, output / revision.name) + log = output / 'shader-logcat.txt' + errors = output / 'adb-errors.txt' + command = [*adb, 'logcat', '-v', 'threadtime', '-T', '1', 'halo:V', '*:S'] + print('Capture started. Close and reopen GulchCE now, then reproduce the issue.', flush=True) + print(f'Recording for up to {seconds:g} seconds. Ctrl+C finishes early.', flush=True) + start = time.monotonic() + with log.open('wb') as raw, errors.open('wb') as err: + process = subprocess.Popen(command, stdout=raw, stderr=err, + creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0)) + reason = 'time limit' + try: + while time.monotonic() - start < seconds: + if process.poll() is not None: + reason = 'adb exited early' + break + if log.stat().st_size >= MAX_LOG_BYTES: + reason = 'log size limit' + break + time.sleep(0.1) + except KeyboardInterrupt: + reason = 'stopped by tester' + finally: + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=5) + metadata['stop_reason'] = reason + metadata['captured_seconds'] = round(time.monotonic() - start, 2) + metadata['logcat_exit_code'] = process.returncode + (output / 'device.json').write_text(json.dumps(metadata, indent=2) + '\n', encoding='utf-8') + # Keep complete shader lines in the raw capture, not just error matches. + text = log.read_text(encoding='utf-8', errors='replace') + markers = ('cannot compile', 'cannot link', 'OpenGL ', 'GL error', 'GPU:', 'guest abort', 'fatal') + summary = [line for line in text.splitlines() if any(marker in line for marker in markers)] + (output / 'summary.txt').write_text('\n'.join(summary) + '\n\n' + 'No matching errors does not prove correct rendering. See shader-logcat.txt for full shader source.\n', + encoding='utf-8') + (output / 'reproduction.txt').write_text( + 'Map name and family (Xbox/CE/MCC):\nWeapon or object affected:\n' + 'Graphics settings and FPS cap:\nWhat you saw and approximate capture time:\n' + 'Did the same map work before updating?\n', encoding='utf-8') + archive = output.with_name(output.name + '.zip') + with zipfile.ZipFile(archive, 'x', compression=zipfile.ZIP_DEFLATED) as package: + for path in sorted(output.iterdir()): + package.write(path, path.name) + print(f'Logs saved to {output}\nShare {archive} with your reproduction details.', flush=True) + if reason == 'adb exited early': + raise RuntimeError(f'adb stopped before the capture ended; inspect {errors}. Partial logs were retained.') + return archive + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--adb', default='adb', help='Path to Android platform-tools adb') + parser.add_argument('--serial', help='Device serial if more than one device is connected') + parser.add_argument('--seconds', type=float, default=120, help='Capture duration (1 to 600; default 120)') + parser.add_argument('--output', type=Path, default=Path('shader-logs-' + datetime.now().strftime('%Y%m%d-%H%M%S'))) + args = parser.parse_args() + if not 1 <= args.seconds <= 600: + parser.error('--seconds must be between 1 and 600') + adb = [args.adb] + (['-s', args.serial] if args.serial else []) + try: + collect(adb, args.output.resolve(), args.seconds) + except (OSError, RuntimeError, subprocess.TimeoutExpired) as error: + parser.exit(1, f'{error}\nInstall Android platform-tools and authorize the selected USB device.\n') + + +if __name__ == '__main__': + main() diff --git a/port/android/guest/dynamic_lighting_disabled.c b/port/android/guest/dynamic_lighting_disabled.c new file mode 100644 index 0000000000..9afe5700dd --- /dev/null +++ b/port/android/guest/dynamic_lighting_disabled.c @@ -0,0 +1,96 @@ +/* Android's stock-lighting implementation of the optional renderer hooks. + The build excludes the feature modules, so saved settings and host glow + policy cannot create extra lights, textures, traces or material overrides. + Overshield surfaces still follow host policy and keep their map reset. */ +#include "cseries.h" +#include "real_math.h" +#include "plasma_lighting.h" +#include "plasma_model_shader.h" +#include "rocket_lighting.h" +#include "muzzle_lighting.h" +#include "covenant_lighting.h" +#include "covenant_emitter_lighting.h" +#include "ammo_counter_lighting.h" +#include "needler_lighting.h" +#include "shield_glow.h" +#include "overshield_effect.h" + +void plasma_lighting_prepare(long light, long object, long definition) {} +float plasma_lighting_radius(long light, long object, float radius) { return radius; } +int plasma_lighting_vehicle_occlusion(long light) { return FALSE; } +void plasma_lighting_frame_end(void) {} +void plasma_lighting_reset(void) {} +void plasma_lighting_window_begin(void) {} +void plasma_lighting_submitted(long light, long rasterizer) {} +int plasma_lighting_selected(long rasterizer) { return FALSE; } +int plasma_lighting_prong_cone(long rasterizer, float axis[3], float origin[3], float *radius) { return FALSE; } +void plasma_model_lighting_reset(void) {} +void plasma_model_lighting_slot(long light, short slot) {} +unsigned int plasma_model_lighting_mask(void) { return 0; } +void plasma_falloff_begin(long rasterizer) {} +void plasma_falloff_specular_begin(long rasterizer) {} +void plasma_specular_begin(long rasterizer) {} +unsigned long plasma_specular_color(unsigned long material) { return material; } +void plasma_falloff_end(void) {} +void plasma_falloff_dispose(void) {} + +void rocket_lighting_update(void) {} +void rocket_lighting_forget(void) {} +void rocket_lighting_frame_end(void) {} +void rocket_lighting_window_begin(void) {} +void rocket_lighting_submitted(long light, long rasterizer) {} +int rocket_lighting_selected(long rasterizer) { return FALSE; } +float rocket_lighting_radius(long light, long object, float radius) { return radius; } + +void muzzle_lighting_shot(long weapon, short trigger) {} +void muzzle_lighting_update(void) {} +void muzzle_lighting_frame_end(void) {} +void muzzle_lighting_forget(void) {} +void muzzle_lighting_window_begin(void) {} +void muzzle_lighting_submitted(long light, long rasterizer) {} +int muzzle_lighting_selected(long rasterizer) { return FALSE; } +float muzzle_lighting_radius(long light, float radius) { return radius; } +int muzzle_lighting_vehicle_occlusion(long light) { return FALSE; } + +void covenant_lighting_update(void) {} +void covenant_lighting_forget(void) {} +void covenant_lighting_frame_end(void) {} +void covenant_lighting_window_begin(void) {} +void covenant_lighting_submitted(long light, long rasterizer) {} +int covenant_lighting_selected(long rasterizer) { return FALSE; } +float covenant_lighting_radius(long light, long object, float radius) { return radius; } +float covenant_lighting_scale(const char *name) { return 0.0f; } +void covenant_lighting_color(long object, long definition, real_rgb_color *color) {} +int covenant_lighting_owns(long light, long object) { return FALSE; } + +int covenant_emitter_lighting_enabled(void) { return FALSE; } +void covenant_emitter_lighting_update(void) {} +void covenant_emitter_lighting_frame_end(void) {} +void covenant_emitter_lighting_forget(void) {} +void covenant_emitter_lighting_window_begin(void) {} +void covenant_emitter_lighting_submitted(long light, long rasterizer) {} +int covenant_emitter_lighting_selected(long rasterizer) { return FALSE; } +long covenant_emitter_lighting_occlusion_ignore(long light) { return NONE; } +float covenant_emitter_lighting_radius(long light, float radius) { return radius; } +int covenant_emitter_lighting_cone(long rasterizer, float axis[3], float origin[3], float *radius) { return 0; } + +int ammo_counter_lighting_position(long weapon, real_point3d *position, real_vector3d *direction) { return 0; } +void ammo_counter_lighting_screen(struct shader *shader, real_rgb_color *color) {} +void ammo_counter_lighting_draw_begin(struct shader *shader, unsigned long output) {} +void ammo_counter_lighting_draw_end(void) {} +void ammo_counter_lighting_forget(void) {} +int needler_lighting_position(long weapon, real_point3d *position, real_vector3d *direction) { return 0; } +void needler_lighting_material(struct shader *shader, real_rgb_color *color) {} +void needler_lighting_forget(void) {} +void needler_lighting_transparent(struct shader *shader, struct pixel_shader_definition *pixel, int stages) {} + +boolean shield_glow_enabled(void) { return FALSE; } +void shield_glow_reset(void) { overshield_effect_reset(); } +void shield_glow_update(void) {} +void shield_glow_frame_end(void) {} +void shield_glow_window_begin(void) {} +void shield_glow_submitted(long light, long rasterizer) {} +boolean shield_glow_selected(long rasterizer) { return FALSE; } +float shield_glow_radius(long light, float radius) { return radius; } + +int covenant_emitter_lighting_vehicle_occlusion(long light) { (void)light; return 0; } diff --git a/port/android/guest/runtime/guest_host.h b/port/android/guest/runtime/guest_host.h index 448b9bed59..4e647986ae 100644 --- a/port/android/guest/runtime/guest_host.h +++ b/port/android/guest/runtime/guest_host.h @@ -147,6 +147,11 @@ void host_touch_look_read(float *delta); void host_touch_rumble(unsigned int low, unsigned int high); /* tells the overlay when to show: touch_input.c's _touch_scene_* */ void host_touch_scene(int scene); +/* -1 preserves the touch layout; 0 off, 1 on, 2 zoom only. */ +void host_touch_gyro_mode(int mode); +/* Typed offline cheat requests; no pointers cross this bridge. */ +void host_android_cheats_state(int state); +int host_android_cheats_read(void); /* the game control on each of the 16 controller buttons (touch_game.c), for the overlay's labels */ void host_touch_bindings(const int *controls); diff --git a/port/android/host/host_android_cheats.c b/port/android/host/host_android_cheats.c new file mode 100644 index 0000000000..29474445aa --- /dev/null +++ b/port/android/host/host_android_cheats.c @@ -0,0 +1,58 @@ +/* UI-thread requests consumed by the game thread. No guest pointers or +command strings cross the Android host/guest boundary. */ +#include +#include + +#define CHEAT_QUEUE_CAPACITY 8 +static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; +static int state, requests[CHEAT_QUEUE_CAPACITY], first, count; + +void host_android_cheats_state(int value) +{ + pthread_mutex_lock(&lock); + state = value; + if (!(value & 2)) first = count = 0; + pthread_mutex_unlock(&lock); +} + +int host_android_cheats_read(void) +{ + int result = -1; + pthread_mutex_lock(&lock); + if ((state & 2) && count) + { + result = requests[first]; + first = (first + 1) % CHEAT_QUEUE_CAPACITY; + count--; + } + pthread_mutex_unlock(&lock); + return result; +} + +JNIEXPORT jint JNICALL Java_com_halo_decomp_AndroidCheatMenu_nativeState(JNIEnv *env, jclass cls) +{ + int result; + (void)env; + (void)cls; + pthread_mutex_lock(&lock); + result = state; + pthread_mutex_unlock(&lock); + return result; +} + +JNIEXPORT jboolean JNICALL Java_com_halo_decomp_AndroidCheatMenu_nativeRequest(JNIEnv *env, jclass cls, jint request) +{ + int accepted = 0; + (void)env; + (void)cls; + pthread_mutex_lock(&lock); + if ((state & 2) && count < CHEAT_QUEUE_CAPACITY && (request & ~0x10F) == 0 && + (request & 0xFF) <= 12 && ((request & 0xFF) < 9 || !(request & 0x100))) + { + requests[(first + count) % CHEAT_QUEUE_CAPACITY] = request; + count++; + accepted = 1; + } + pthread_mutex_unlock(&lock); + return accepted ? JNI_TRUE : JNI_FALSE; +} diff --git a/port/android/host/host_touch.c b/port/android/host/host_touch.c index 00b4f5d3f3..7c5052bb4a 100644 --- a/port/android/host/host_touch.c +++ b/port/android/host/host_touch.c @@ -44,6 +44,7 @@ static int64_t gyro_ns; static int rumble_amplitude; static int64_t rumble_ns; static volatile int touch_scene; +static int gyro_mode = -1; /* the overlay's devices (host_touch_devices): a touchscreen, a game controller (a stick or a hat, not a phone's few gamepad keys) */ #define HOST_TOUCH_DEVICE_TOUCHSCREEN 1 @@ -137,6 +138,26 @@ JNIEXPORT void JNICALL Java_com_halo_decomp_TouchControls_nativeGyro( pthread_mutex_unlock(&touch_lock); } +void host_touch_gyro_mode(int mode) +{ + pthread_mutex_lock(&touch_lock); + if (gyro_mode != mode) + gyro_delta[0] = gyro_delta[1] = 0.0f; + gyro_mode = mode; + pthread_mutex_unlock(&touch_lock); +} + +JNIEXPORT jint JNICALL Java_com_halo_decomp_TouchControls_nativeGyroMode(JNIEnv *env, jclass cls) +{ + int mode; + (void)env; + (void)cls; + pthread_mutex_lock(&touch_lock); + mode = gyro_mode; + pthread_mutex_unlock(&touch_lock); + return mode; +} + JNIEXPORT void JNICALL Java_com_halo_decomp_TouchControls_nativeLookReset(JNIEnv *env, jclass cls) { (void)env; diff --git a/port/android/host_imports.list b/port/android/host_imports.list index 741c5f5fc5..1c90567498 100644 --- a/port/android/host_imports.list +++ b/port/android/host_imports.list @@ -66,6 +66,9 @@ host_touch_read host_touch_look_read host_touch_rumble host_touch_scene +host_touch_gyro_mode +host_android_cheats_state +host_android_cheats_read host_touch_bindings host_touch_devices host_https_get diff --git a/port/assets/changelog/catchup.json b/port/assets/changelog/catchup.json new file mode 100644 index 0000000000..c8aad88bcd --- /dev/null +++ b/port/assets/changelog/catchup.json @@ -0,0 +1,38 @@ +{ + "schema_version": 1, + "baseline": "ecb6ba92271c1718397fc1b09b567c17c0b4fbf5", + "notes": [ + {"commit": "26324d4a3f12965ce4ea98951a4fabd6ebd79ba3", "text": "Fixed screen fades in MCC campaign maps.", "category": "GRAPHICS"}, + {"commit": "26324d4a3f12965ce4ea98951a4fabd6ebd79ba3", "text": "Fixed repeat races in Rally and weapon movement speeds in Bigass.", "category": "GAMEPLAY"}, + {"commit": "c8cf7d83a0a029becf69797aa62da0748ca9e96a", "text": "Fixed repeated equipment selection in MeinCrap.", "category": "GAMEPLAY"}, + {"commit": "c8cf7d83a0a029becf69797aa62da0748ca9e96a", "text": "Fixed a dark layer over Frogfoot's water.", "category": "GRAPHICS"}, + {"commit": "b0c5d017d4230ef0ff978c57da0839eea558c469", "text": "Fixed missing light glows on AMD graphics cards.", "category": "GRAPHICS"}, + {"commit": "95748a74ce13a77444a7bb3bfe236bf97cfbb21d", "text": "Improved rendering performance on NVIDIA graphics cards.", "category": "GRAPHICS"}, + {"commit": "da38822634ea294323b1db3ecc3a3d5c8a224a3a", "text": "Added text chat for private multiplayer games.", "category": "MULTIPLAYER"}, + {"commit": "7abd376b85a6c9e2713f00364ddec06d2600c31f", "text": "Mute a player's voice and text chat from the scoreboard.", "category": "QUALITY OF LIFE"}, + {"commit": "90dd65cab46d2760750506f4b05821e6ecc8794d", "text": "Added streamer mode to hide offensive words in names and other text.", "category": "QUALITY OF LIFE"}, + {"commit": "90ab2ff094e7e453500315aa2009f84d4865d694", "text": "Access multiplayer chat settings from the pause menu, including co-op.", "category": "INTERFACE"}, + {"commit": "eb16cf4bdc7d2d7d6325d365a39e7beddb494546", "text": "Raised the maximum map sharing speeds.", "category": "MULTIPLAYER"}, + {"commit": "bc37efd5da325afc5f157eaa4f85a7fd16271a7a", "text": "Refreshed the browser launcher with a clearer Ready to Play screen.", "category": "INTERFACE"}, + {"commit": "1b61b529294dee3bd3c90a816781400d24dcc709", "text": "Improved browser multiplayer on unreliable connections.", "category": "MULTIPLAYER"}, + {"commit": "81a768bc81fadfdaa8a1a78141e7fc2efe69a07f", "text": "Fixed the browser loading notice and joining games from browser rooms.", "category": "INTERFACE"}, + {"commit": "6cb966a7d84b71459d18978ad8b3f7ecf16ff0c9", "text": "Added optional bots for local Slayer games through the Xbox menus.", "category": "GAMEPLAY"}, + {"commit": "6cb966a7d84b71459d18978ad8b3f7ecf16ff0c9", "text": "Co-op hosts can add extra weapons, pickups and vehicles.", "category": "GAMEPLAY"}, + {"commit": "6cb966a7d84b71459d18978ad8b3f7ecf16ff0c9", "text": "Added a personal friendly-fire toggle to the online co-op pause menu.", "category": "GAMEPLAY"}, + {"commit": "6cb966a7d84b71459d18978ad8b3f7ecf16ff0c9", "text": "Added optional third-person views for Warthog and Scorpion passengers in campaign and co-op.", "category": "GAMEPLAY"}, + {"commit": "6cb966a7d84b71459d18978ad8b3f7ecf16ff0c9", "text": "Added the Bumper Jumper controller layout.", "category": "CONTROLS"}, + {"commit": "6cb966a7d84b71459d18978ad8b3f7ecf16ff0c9", "text": "Added an alternate Linux driver option for PlayStation controllers.", "category": "CONTROLS"}, + {"commit": "6cb966a7d84b71459d18978ad8b3f7ecf16ff0c9", "text": "Added optional HDR lighting and output for supported HDR displays.", "category": "GRAPHICS"}, + {"commit": "6cb966a7d84b71459d18978ad8b3f7ecf16ff0c9", "text": "Added texture filtering and model detail options for sharper distant scenery.", "category": "GRAPHICS"}, + {"commit": "6cb966a7d84b71459d18978ad8b3f7ecf16ff0c9", "text": "Added an Extra Effects menu for optional visual effects.", "category": "GRAPHICS"}, + {"commit": "6cb966a7d84b71459d18978ad8b3f7ecf16ff0c9", "text": "Added an optional multiplayer match clock.", "category": "MULTIPLAYER"}, + {"commit": "6cb966a7d84b71459d18978ad8b3f7ecf16ff0c9", "text": "Added a connection meter and colour-coded scoreboard ping readings.", "category": "MULTIPLAYER"}, + {"commit": "6cb966a7d84b71459d18978ad8b3f7ecf16ff0c9", "text": "Hosts can disable optional mouse aim assist while keeping controller and touch assistance.", "category": "MULTIPLAYER"}, + {"commit": "6cb966a7d84b71459d18978ad8b3f7ecf16ff0c9", "text": "Fixed starting split-screen matches without another computer joining.", "category": "MULTIPLAYER"}, + {"commit": "6cb966a7d84b71459d18978ad8b3f7ecf16ff0c9", "text": "PC menu text now follows the language of your Custom Edition maps where available.", "category": "INTERFACE"}, + {"commit": "6cb966a7d84b71459d18978ad8b3f7ecf16ff0c9", "text": "The main menu background now keeps playing behind other menus.", "category": "INTERFACE"}, + {"commit": "6cb966a7d84b71459d18978ad8b3f7ecf16ff0c9", "text": "Added 5.1 surround sound and adjustable audio buffering on Windows and Linux.", "category": "AUDIO"}, + {"commit": "6cb966a7d84b71459d18978ad8b3f7ecf16ff0c9", "text": "Game setup can find an Xbox disc image placed beside the executable.", "category": "QUALITY OF LIFE"}, + {"commit": "6cb966a7d84b71459d18978ad8b3f7ecf16ff0c9", "text": "Improved startup on NVIDIA systems using a Linux Wayland desktop.", "category": "QUALITY OF LIFE"} + ] +} diff --git a/port/assets/changelog/notes.json b/port/assets/changelog/notes.json new file mode 100644 index 0000000000..d0317a6aa8 --- /dev/null +++ b/port/assets/changelog/notes.json @@ -0,0 +1,39 @@ +{ + "schema_version": 2, + "head": "ca3bfbaa4c1275c5ef2c94e236942a67b9c33fd2", + "entries": [ + { + "build": null, + "date": "2026-10-18", + "commit": "ca3bfbaa4c1275c5ef2c94e236942a67b9c33fd2", + "notes": [ + "Fixed screen fades in MCC campaign maps.", + "Fixed repeat races in Rally and weapon movement speeds in Bigass.", + "Fixed repeated equipment selection in MeinCrap.", + "Fixed a dark layer over Frogfoot's water.", + "Fixed missing light glows on AMD graphics cards.", + "Improved rendering performance on NVIDIA graphics cards.", + "Added streamer mode to hide offensive words in names and other text.", + "Added text chat for private multiplayer games.", + "Mute a player's voice and text chat from the scoreboard.", + "Access multiplayer chat settings from the pause menu, including co-op.", + "Refreshed the browser launcher with a clearer Ready to Play screen.", + "Raised the maximum map sharing speeds." + ], + "categories": [ + "GRAPHICS", + "GAMEPLAY", + "GAMEPLAY", + "GRAPHICS", + "GRAPHICS", + "GRAPHICS", + "QUALITY OF LIFE", + "MULTIPLAYER", + "QUALITY OF LIFE", + "INTERFACE", + "INTERFACE", + "MULTIPLAYER" + ] + } + ] +} diff --git a/port/assets/hud/corrections/README.md b/port/assets/hud/corrections/README.md index 90b5bcdbac..d5e55bf821 100644 --- a/port/assets/hud/corrections/README.md +++ b/port/assets/hud/corrections/README.md @@ -15,7 +15,10 @@ tints the resulting monochrome coverage. CE's existing 8x artwork remains untouched, as explicitly requested. Run `python tools/hud_corrections.py` from the repository root. It requires -Pillow, NumPy and SciPy. These supplied pictures never go through an SVG renderer. +Pillow, NumPy, SciPy and an SVG renderer for the separate Xbox Classic letter +cutouts. The committed Classic outputs were rendered with `resvg-py==0.5.0`; +the older button generator also supports `rsvg-convert`. The supplied reticle +and lettering pictures never go through either SVG renderer. See [the runtime walkthrough](../../../../docs/reading/hud_corrections.md) for -stock identification, texture ownership and verification limits. +map-family guards, texture ownership and verification limits. diff --git a/port/assets/menus/README.md b/port/assets/menus/README.md index 2015adce8e..6cdd3d2d1a 100644 --- a/port/assets/menus/README.md +++ b/port/assets/menus/README.md @@ -13,6 +13,8 @@ controller, the keyboard and the mouse, on every port. | `NON_HANDDRAWN.md` | The pictures that are not redraws: those drawn from the Xbox's map (the player's own), and the placeholders, to be redrawn | | `UNWIRED.md` | The menus' functions that do nothing yet: the lists they fill are empty, and the settings they change do not change | | `menus.json` | The files the game embeds | +| `ce/main_menu.changelog.port.xml` | Port-owned player notes screens and their bitmap definitions | +| `modern/` | Opt-in GulchCE Settings, hosting and lobby frontend (native browsers preserved), generated independently by `python tools/frontend_menu.py`; excluded from gameplay's menu set | `tools/ce_menus.py` writes all of them from the PC version's tags and the redraws, but the settings screens (Controls Setup, Gamepads, Mouse, Audio, @@ -32,6 +34,19 @@ one screen (by its name, `main_menu/settings_select/...`), for looking at it. ## Writing them again +For the separate Modern generator, install the pinned Pillow wheel with +`python -m pip install --only-binary=:all: -r tools/requirements-frontend.txt`, +then run `python tools/frontend_menu.py`. Its FreeType renderer must match the +checked-in title art; the generator explicitly uses basic font layout instead of +the optional RAQM shaping backend. CI uses the same pinned wheel and compares +decoded pixels. + +That generator also calls `tools/mcc_xbox_menu.py` for the separate Xbox-style +MCC profile, campaign, mission and multiplayer wrappers. They retain native +Xbox card geometry and use existing profile/difficulty services. See the +[MCC preview walkthrough](../../../docs/reading/mcc_level_previews.md) for +image bounds, completion badges and lifecycle boundaries. + `tools/ce_menus.py` writes every file in `ce/` and `menus.json` again, the settings screens too (it runs `tools/port_settings.py`'s): @@ -58,6 +73,77 @@ It needs `rsvg-convert`, Pillow, NumPy and SciPy. It writes every file, so `git status` should show only the screens meant to change; then `ninja linux` (or `ninja android`) embeds them in the game. +The port-owned pause panels can be regenerated without the PC tags: +`python tools/ce_menus.py --pause-art-only`. This updates only their SVGs, +PNGs, bitmap definitions and the asset manifest. + +Port-owned settings screens can also be regenerated without the PC tags: +`python tools/ce_menus.py --settings-only`. This writes `port_settings.py`'s +screens and registers new XML files in the embedding manifest. + +Child positions in `tools/ce_menus.py`'s `CHILD_OFFSETS` can be applied to +the existing XML without the PC tags: `python tools/ce_menus.py --child-offsets-only`. +This uses the same positions as a full regeneration and leaves other widget +properties and artwork intact. + +The changelog artwork and player notes can be regenerated without PC tags: +`python tools/ce_menus.py --changelog-only` (or `python tools/changelog_menu.py`). +It uses the committed handmade letter redraws and OpenCE font, and needs +`rsvg-convert`, Pillow, NumPy and fontTools. `tools/changelog_menu.py` owns +the page layout and navigation. Full menu generation includes the same +output. Both read the committed player notes in `port/assets/changelog/notes.json`. +Each screen shows one build, headed BUILD followed by its exact GitHub build +number and its date. Local preview notes are marked UNRELEASED. Up/Down, +the controller's stick or the mouse wheel scrolls the reading area one line +at a time; its UP and DOWN buttons sit together at the reading area's lower +right and work with a pointer or touch. The visible +line indicator shows the position. Previous and Next switch entire builds +(older and newer, respectively), starting their reading area at the top. +An empty history says that no player-facing changes were recorded. +Notes are grouped under blue category headings, in the order the categories +first appear in that build. Notes keep their order within each category. +Uncategorized notes appear under GENERAL. Notes use normal line spacing; +only category groups have a blank separator line. + +To update text without rendering artwork, run +`python tools/changelog_menu.py --text-only`. This needs only Python's standard +library and preserves the existing bitmap definitions. `--notes ` reads +an alternate schema-version-2 notes JSON file. Invalid dates, build numbers, commit IDs, +oversized notes and unsupported text are refused before writing the XML. + +Build changes use `open` with `no_history` on every changelog screen root. +The engine checks the invoking root's history flag: opening the first page +records the main menu, and moving between builds preserves that entry, so +Back or Escape returns directly to the main menu. + +`port/linux/game/changelog_menu_runtime.inl` owns scrolling. It changes only +the eight visible slots' indices into each build's paired immutable body and +blue-heading string lists; its offset belongs to that screen instance. The +two lists must have matching counts. Three event registrations +and their dispatch in `menu_tags.c` and `menu_functions.c` connect it to the +existing menu interfaces: generated XML alone cannot change visible text +indices in response to input. The runtime accepts only the changelog's own +root namespace and resets the instance offset on creation; deletion frees +that instance normally. Xbox, Custom Edition and MCC screens outside the +feature keep their existing paths. The footer omits horizontal tab flags so +the mouse wheel follows the vertical scroll handlers, including over buttons. + +CHANGELOG occupies its own small list beneath the build labels, leaving the six original +central buttons, coordinates and Up/Down wrapping intact. Right selects the +corner button directly beneath the orange version labels. Its existing +artwork is scaled uniformly to the visible text block's width. +Both the Gulch build label and button share the original version text's +visible centerline. Left returns to the remembered central selection. Mouse hover +and clicks use the existing column-list target rules, including the paired +scroll arrows. The feature runtime handles only this exact PC main root and +its own corner container. Its small focus/update handlers are necessary because +XML alone cannot preserve the central selection while updating the corner's +selection frame. The same callback synchronizes only the changelog's own +arrow/footer selection frames, since the engine updates only the active list. +Disabling `display.changelog` unlinks only that container at +startup; the original menu behavior remains. Changes take effect after restart. +The additional orange Gulch build label matches the existing version label. + A settings screen (Controls Setup, Gamepads, Mouse, Audio, Video or Network Setup) is changed in `tools/port_settings.py`, not in its XML, and written with the command above. diff --git a/port/assets/menus/ce/main_menu.changelog.port.xml b/port/assets/menus/ce/main_menu.changelog.port.xml new file mode 100644 index 0000000000..a48bc5ccca --- /dev/null +++ b/port/assets/menus/ce/main_menu.changelog.port.xml @@ -0,0 +1,204 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/port/assets/menus/ce/main_menu.multiplayer_type_select.lobby.xml b/port/assets/menus/ce/main_menu.multiplayer_type_select.lobby.xml index df9e3687cd..ffee4a68ed 100644 --- a/port/assets/menus/ce/main_menu.multiplayer_type_select.lobby.xml +++ b/port/assets/menus/ce/main_menu.multiplayer_type_select.lobby.xml @@ -111,10 +111,17 @@ - - - - + + + + + + + + + + + diff --git a/port/assets/menus/ce/main_menu.multiplayer_type_select.server_settings.xml b/port/assets/menus/ce/main_menu.multiplayer_type_select.server_settings.xml index 7bab7cbfc4..3d25f97793 100644 --- a/port/assets/menus/ce/main_menu.multiplayer_type_select.server_settings.xml +++ b/port/assets/menus/ce/main_menu.multiplayer_type_select.server_settings.xml @@ -1,41 +1,41 @@ - + - + - + - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + - + - + @@ -48,7 +48,7 @@ - + @@ -56,20 +56,7 @@ - - - - - - - - - - - - - - + @@ -78,7 +65,7 @@ - + @@ -91,15 +78,89 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + - + @@ -107,7 +168,7 @@ - + @@ -115,7 +176,7 @@ - + @@ -126,7 +187,7 @@ - + @@ -137,7 +198,7 @@ - + @@ -148,7 +209,7 @@ - + @@ -159,7 +220,7 @@ - + @@ -170,7 +231,7 @@ - + @@ -203,6 +264,7 @@ + @@ -221,9 +283,17 @@ + + + + + + + + diff --git a/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.controller_appearance.xml b/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.controller_appearance.xml index 18854cd810..cafaf16e80 100644 --- a/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.controller_appearance.xml +++ b/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.controller_appearance.xml @@ -13,15 +13,14 @@ - - - - - - - - - + + + + + + + + @@ -29,38 +28,29 @@ - - - - - - - - - - - - - - - - - - - + + + + + + + + + + - + @@ -69,7 +59,7 @@ - + @@ -78,7 +68,7 @@ - + @@ -87,7 +77,7 @@ - + @@ -96,7 +86,7 @@ - + @@ -104,7 +94,7 @@ - + @@ -120,9 +110,8 @@ - - + @@ -132,10 +121,9 @@ - - - - + + + diff --git a/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.controller_remapping.xml b/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.controller_remapping.xml index 08657998a0..971ea9ea0c 100644 --- a/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.controller_remapping.xml +++ b/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.controller_remapping.xml @@ -44,7 +44,7 @@ - + diff --git a/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.controls_setup.xml b/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.controls_setup.xml index 1f6159a76a..055568b562 100644 --- a/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.controls_setup.xml +++ b/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.controls_setup.xml @@ -35,7 +35,7 @@ - + diff --git a/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.gamepad_setup.android.xml b/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.gamepad_setup.android.xml new file mode 100644 index 0000000000..aeb2b920ce --- /dev/null +++ b/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.gamepad_setup.android.xml @@ -0,0 +1,85 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.gamepad_setup.gyro.xml b/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.gamepad_setup.gyro.xml new file mode 100644 index 0000000000..6094ca79ee --- /dev/null +++ b/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.gamepad_setup.gyro.xml @@ -0,0 +1,98 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.gamepad_setup.xml b/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.gamepad_setup.xml index d0c9b7189f..73758fa9f9 100644 --- a/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.gamepad_setup.xml +++ b/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.gamepad_setup.xml @@ -13,17 +13,28 @@ - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + @@ -119,13 +130,21 @@ + + + + + + + + - + @@ -148,6 +167,7 @@ + @@ -161,7 +181,8 @@ - + + diff --git a/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.network_setup.bots.manage.xml b/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.network_setup.bots.manage.xml new file mode 100644 index 0000000000..9bc77e0e82 --- /dev/null +++ b/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.network_setup.bots.manage.xml @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.network_setup.bots.xml b/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.network_setup.bots.xml new file mode 100644 index 0000000000..2487a44c7d --- /dev/null +++ b/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.network_setup.bots.xml @@ -0,0 +1,145 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.network_setup.in_game.xml b/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.network_setup.in_game.xml index 35377c3a9a..f76812f73b 100644 --- a/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.network_setup.in_game.xml +++ b/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.network_setup.in_game.xml @@ -13,10 +13,11 @@ - - - - + + + + + @@ -24,13 +25,21 @@ + + + + + + + + - + @@ -38,7 +47,7 @@ - + @@ -46,7 +55,7 @@ - + @@ -54,7 +63,7 @@ - + @@ -67,6 +76,7 @@ + @@ -74,6 +84,7 @@ + diff --git a/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.network_setup.mcc_packages.xml b/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.network_setup.mcc_packages.xml index 91ded30392..cf53c889d2 100644 --- a/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.network_setup.mcc_packages.xml +++ b/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.network_setup.mcc_packages.xml @@ -7,7 +7,7 @@ - + diff --git a/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.network_setup.xml b/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.network_setup.xml index 41c4ddd412..c7f66a24d8 100644 --- a/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.network_setup.xml +++ b/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.network_setup.xml @@ -14,19 +14,21 @@ - - - - - - - - - - - - - + + + + + + + + + + + + + + + @@ -70,13 +72,21 @@ + + + + + + + + - + @@ -84,7 +94,7 @@ - + @@ -92,7 +102,7 @@ - + @@ -100,7 +110,7 @@ - + @@ -108,7 +118,7 @@ - + @@ -125,6 +135,7 @@ + @@ -137,6 +148,7 @@ + diff --git a/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.video_settings.dynamic_lighting.xml b/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.video_settings.dynamic_lighting.xml new file mode 100644 index 0000000000..40fd972fac --- /dev/null +++ b/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.video_settings.dynamic_lighting.xml @@ -0,0 +1,158 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.video_settings.extra_effects.xml b/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.video_settings.extra_effects.xml index c66b9fa01d..77c084a73d 100644 --- a/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.video_settings.extra_effects.xml +++ b/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.video_settings.extra_effects.xml @@ -14,14 +14,12 @@ - - - - - - - - + + + + + + @@ -38,29 +36,11 @@ - - - - - - - - - - - - - - - - - - - + @@ -69,7 +49,7 @@ - + @@ -78,7 +58,7 @@ - + @@ -87,7 +67,7 @@ - + @@ -96,7 +76,7 @@ - + @@ -107,7 +87,7 @@ - + @@ -121,8 +101,6 @@ - - @@ -133,8 +111,6 @@ - - diff --git a/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.video_settings.fov_viewmodels.xml b/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.video_settings.fov_viewmodels.xml index b7020429fc..a34e500260 100644 --- a/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.video_settings.fov_viewmodels.xml +++ b/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.video_settings.fov_viewmodels.xml @@ -14,12 +14,14 @@ - - - - - - + + + + + + + + @@ -63,32 +65,49 @@ + + + + + + + + + - + + + + + + + + + + - + - - - - - + + + + + - - + @@ -105,9 +124,11 @@ + + - + @@ -115,8 +136,11 @@ + + - + + diff --git a/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.video_settings.graphics.xml b/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.video_settings.graphics.xml index d3c081e8d3..dc30c13068 100644 --- a/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.video_settings.graphics.xml +++ b/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.video_settings.graphics.xml @@ -13,16 +13,17 @@ - - - - - - - - - - + + + + + + + + + + + @@ -30,11 +31,20 @@ + + + + + + + + + - + @@ -43,7 +53,7 @@ - + @@ -52,7 +62,7 @@ - + @@ -61,7 +71,7 @@ - + @@ -70,7 +80,7 @@ - + @@ -79,7 +89,7 @@ - + @@ -88,7 +98,7 @@ - + @@ -97,7 +107,7 @@ - + @@ -106,7 +116,7 @@ - + @@ -115,7 +125,7 @@ - + @@ -131,6 +141,7 @@ + @@ -144,10 +155,11 @@ + - + diff --git a/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.video_settings.shoulder_camera.xml b/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.video_settings.shoulder_camera.xml new file mode 100644 index 0000000000..e887766521 --- /dev/null +++ b/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.video_settings.shoulder_camera.xml @@ -0,0 +1,98 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.video_settings.xml b/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.video_settings.xml index a9197020ee..989586a8cd 100644 --- a/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.video_settings.xml +++ b/port/assets/menus/ce/main_menu.settings_select.player_setup.player_profile_edit.video_settings.xml @@ -9,33 +9,35 @@ - + - - - + + + - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + @@ -140,13 +142,21 @@ + + + + + + + + - + @@ -170,6 +180,7 @@ + @@ -185,6 +196,7 @@ - + + diff --git a/port/assets/menus/ce/main_menu.xml b/port/assets/menus/ce/main_menu.xml index 650ec304cb..527cf9961b 100644 --- a/port/assets/menus/ce/main_menu.xml +++ b/port/assets/menus/ce/main_menu.xml @@ -11,12 +11,17 @@ + + + + + diff --git a/port/assets/menus/ce/port/main_menu/changelog/header_changelog.png b/port/assets/menus/ce/port/main_menu/changelog/header_changelog.png new file mode 100644 index 0000000000..2bfbe80b62 Binary files /dev/null and b/port/assets/menus/ce/port/main_menu/changelog/header_changelog.png differ diff --git a/port/assets/menus/ce/port/main_menu/menu_changelog__0.png b/port/assets/menus/ce/port/main_menu/menu_changelog__0.png new file mode 100644 index 0000000000..7ee6ca74e8 Binary files /dev/null and b/port/assets/menus/ce/port/main_menu/menu_changelog__0.png differ diff --git a/port/assets/menus/ce/port/main_menu/menu_changelog__1.png b/port/assets/menus/ce/port/main_menu/menu_changelog__1.png new file mode 100644 index 0000000000..c7e6f06a58 Binary files /dev/null and b/port/assets/menus/ce/port/main_menu/menu_changelog__1.png differ diff --git a/port/assets/menus/menus.json b/port/assets/menus/menus.json index d886050c97..76751ee9c1 100644 --- a/port/assets/menus/menus.json +++ b/port/assets/menus/menus.json @@ -4,6 +4,7 @@ "ce/bitmaps.xml", "ce/error.xml", "ce/main_menu.campaign_select.xml", + "ce/main_menu.changelog.port.xml", "ce/main_menu.difficulty_select.xml", "ce/main_menu.gametype_select.xml", "ce/main_menu.mods.xml", @@ -49,10 +50,14 @@ "ce/main_menu.settings_select.player_setup.player_profile_edit.controller_appearance.xml", "ce/main_menu.settings_select.player_setup.player_profile_edit.controller_remapping.xml", "ce/main_menu.settings_select.player_setup.player_profile_edit.controls_setup.xml", + "ce/main_menu.settings_select.player_setup.player_profile_edit.gamepad_setup.android.xml", "ce/main_menu.settings_select.player_setup.player_profile_edit.gamepad_setup.dead_zones.xml", + "ce/main_menu.settings_select.player_setup.player_profile_edit.gamepad_setup.gyro.xml", "ce/main_menu.settings_select.player_setup.player_profile_edit.gamepad_setup.xml", "ce/main_menu.settings_select.player_setup.player_profile_edit.mouse_settings.xml", "ce/main_menu.settings_select.player_setup.player_profile_edit.name_edit.xml", + "ce/main_menu.settings_select.player_setup.player_profile_edit.network_setup.bots.manage.xml", + "ce/main_menu.settings_select.player_setup.player_profile_edit.network_setup.bots.xml", "ce/main_menu.settings_select.player_setup.player_profile_edit.network_setup.discord_account.xml", "ce/main_menu.settings_select.player_setup.player_profile_edit.network_setup.in_game.xml", "ce/main_menu.settings_select.player_setup.player_profile_edit.network_setup.map_sharing.xml", @@ -63,10 +68,12 @@ "ce/main_menu.settings_select.player_setup.player_profile_edit.network_setup.server_browser.xml", "ce/main_menu.settings_select.player_setup.player_profile_edit.network_setup.streamer_mode.xml", "ce/main_menu.settings_select.player_setup.player_profile_edit.network_setup.xml", + "ce/main_menu.settings_select.player_setup.player_profile_edit.video_settings.dynamic_lighting.xml", "ce/main_menu.settings_select.player_setup.player_profile_edit.video_settings.extra_effects.xml", "ce/main_menu.settings_select.player_setup.player_profile_edit.video_settings.fov_viewmodels.xml", "ce/main_menu.settings_select.player_setup.player_profile_edit.video_settings.graphics.xml", "ce/main_menu.settings_select.player_setup.player_profile_edit.video_settings.hdr_calibration.xml", + "ce/main_menu.settings_select.player_setup.player_profile_edit.video_settings.shoulder_camera.xml", "ce/main_menu.settings_select.player_setup.player_profile_edit.video_settings.xml", "ce/main_menu.settings_select.player_setup.player_profile_edit.xml", "ce/main_menu.solo_level_select.xml", @@ -74,6 +81,9 @@ "ce/shell.xml", "ce/strings.xml", "ce/port/blank__0.png", + "ce/port/main_menu/changelog/header_changelog.png", + "ce/port/main_menu/menu_changelog__0.png", + "ce/port/main_menu/menu_changelog__1.png", "ce/port/main_menu/menu_mods__0.png", "ce/port/main_menu/menu_mods__1.png", "ce/port/main_menu/mods/header_mods.png", @@ -255,6 +265,38 @@ "ce/shell/main_menu/settings_select/player_setup/player_profile_edit/profile_options__6.png", "ce/shell/main_menu/settings_select/player_setup/player_profile_edit/profile_options__8.png", "ce/shell/main_menu/settings_select/player_setup/player_profile_edit/video_settings/header_profile_video_settings__0.png", - "ce/shell/main_menu/solo_level_select/header_load_level__0.png" + "ce/shell/main_menu/solo_level_select/header_load_level__0.png", + "modern/button_0.png", + "modern/button_1.png", + "modern/help_panel_0.png", + "modern/mcc_campaigns.png", + "modern/mcc_campaigns_entry_0.png", + "modern/mcc_campaigns_entry_1.png", + "modern/panel_0.png", + "modern/row_0.png", + "modern/row_1.png", + "modern/rule_0.png", + "modern/settings.xml", + "modern/tab_0.png", + "modern/tab_1.png", + "modern/title_0.png", + "modern/title_bots_0.png", + "modern/title_campaign_0.png", + "modern/title_coop_0.png", + "modern/title_difficulty_0.png", + "modern/title_gametypes_0.png", + "modern/title_host_0.png", + "modern/title_lobby_0.png", + "modern/title_maps_0.png", + "modern/title_mcc_packages_0.png", + "modern/title_multiplayer_0.png", + "modern/title_preview_0.png", + "modern/title_server_0.png", + "modern/title_session_0.png", + "modern/title_sharing_0.png", + "modern/title_voice_0.png", + "modern/xbox_a.png", + "modern/xbox_b.png", + "modern/xbox_x.png" ] } diff --git a/port/assets/menus/modern/button_0.png b/port/assets/menus/modern/button_0.png new file mode 100644 index 0000000000..ee56c1383a Binary files /dev/null and b/port/assets/menus/modern/button_0.png differ diff --git a/port/assets/menus/modern/button_1.png b/port/assets/menus/modern/button_1.png new file mode 100644 index 0000000000..2a3343aa25 Binary files /dev/null and b/port/assets/menus/modern/button_1.png differ diff --git a/port/assets/menus/modern/help_panel_0.png b/port/assets/menus/modern/help_panel_0.png new file mode 100644 index 0000000000..d4b8b5ae90 Binary files /dev/null and b/port/assets/menus/modern/help_panel_0.png differ diff --git a/port/assets/menus/modern/mcc_campaigns.png b/port/assets/menus/modern/mcc_campaigns.png new file mode 100644 index 0000000000..04fbae3914 Binary files /dev/null and b/port/assets/menus/modern/mcc_campaigns.png differ diff --git a/port/assets/menus/modern/mcc_campaigns_entry_0.png b/port/assets/menus/modern/mcc_campaigns_entry_0.png new file mode 100644 index 0000000000..aa8903da0b Binary files /dev/null and b/port/assets/menus/modern/mcc_campaigns_entry_0.png differ diff --git a/port/assets/menus/modern/mcc_campaigns_entry_1.png b/port/assets/menus/modern/mcc_campaigns_entry_1.png new file mode 100644 index 0000000000..c9d83ddac9 Binary files /dev/null and b/port/assets/menus/modern/mcc_campaigns_entry_1.png differ diff --git a/port/assets/menus/modern/panel_0.png b/port/assets/menus/modern/panel_0.png new file mode 100644 index 0000000000..1a51b7c041 Binary files /dev/null and b/port/assets/menus/modern/panel_0.png differ diff --git a/port/assets/menus/modern/row_0.png b/port/assets/menus/modern/row_0.png new file mode 100644 index 0000000000..f0e2905f17 Binary files /dev/null and b/port/assets/menus/modern/row_0.png differ diff --git a/port/assets/menus/modern/row_1.png b/port/assets/menus/modern/row_1.png new file mode 100644 index 0000000000..b1213e2578 Binary files /dev/null and b/port/assets/menus/modern/row_1.png differ diff --git a/port/assets/menus/modern/rule_0.png b/port/assets/menus/modern/rule_0.png new file mode 100644 index 0000000000..af54522a35 Binary files /dev/null and b/port/assets/menus/modern/rule_0.png differ diff --git a/port/assets/menus/modern/settings.xml b/port/assets/menus/modern/settings.xml new file mode 100644 index 0000000000..84bb945eb7 --- /dev/null +++ b/port/assets/menus/modern/settings.xml @@ -0,0 +1,6060 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/port/assets/menus/modern/tab_0.png b/port/assets/menus/modern/tab_0.png new file mode 100644 index 0000000000..4d4e91c7da Binary files /dev/null and b/port/assets/menus/modern/tab_0.png differ diff --git a/port/assets/menus/modern/tab_1.png b/port/assets/menus/modern/tab_1.png new file mode 100644 index 0000000000..4d4e91c7da Binary files /dev/null and b/port/assets/menus/modern/tab_1.png differ diff --git a/port/assets/menus/modern/title_0.png b/port/assets/menus/modern/title_0.png new file mode 100644 index 0000000000..c4cef3ec0b Binary files /dev/null and b/port/assets/menus/modern/title_0.png differ diff --git a/port/assets/menus/modern/title_bots_0.png b/port/assets/menus/modern/title_bots_0.png new file mode 100644 index 0000000000..14f79a25ba Binary files /dev/null and b/port/assets/menus/modern/title_bots_0.png differ diff --git a/port/assets/menus/modern/title_campaign_0.png b/port/assets/menus/modern/title_campaign_0.png new file mode 100644 index 0000000000..9ad09bbe6c Binary files /dev/null and b/port/assets/menus/modern/title_campaign_0.png differ diff --git a/port/assets/menus/modern/title_coop_0.png b/port/assets/menus/modern/title_coop_0.png new file mode 100644 index 0000000000..48374d1ae5 Binary files /dev/null and b/port/assets/menus/modern/title_coop_0.png differ diff --git a/port/assets/menus/modern/title_difficulty_0.png b/port/assets/menus/modern/title_difficulty_0.png new file mode 100644 index 0000000000..1f7a722da1 Binary files /dev/null and b/port/assets/menus/modern/title_difficulty_0.png differ diff --git a/port/assets/menus/modern/title_gametypes_0.png b/port/assets/menus/modern/title_gametypes_0.png new file mode 100644 index 0000000000..786b5c53c2 Binary files /dev/null and b/port/assets/menus/modern/title_gametypes_0.png differ diff --git a/port/assets/menus/modern/title_host_0.png b/port/assets/menus/modern/title_host_0.png new file mode 100644 index 0000000000..5ca34eade1 Binary files /dev/null and b/port/assets/menus/modern/title_host_0.png differ diff --git a/port/assets/menus/modern/title_lobby_0.png b/port/assets/menus/modern/title_lobby_0.png new file mode 100644 index 0000000000..ce81ccc874 Binary files /dev/null and b/port/assets/menus/modern/title_lobby_0.png differ diff --git a/port/assets/menus/modern/title_maps_0.png b/port/assets/menus/modern/title_maps_0.png new file mode 100644 index 0000000000..9e883b92df Binary files /dev/null and b/port/assets/menus/modern/title_maps_0.png differ diff --git a/port/assets/menus/modern/title_mcc_packages_0.png b/port/assets/menus/modern/title_mcc_packages_0.png new file mode 100644 index 0000000000..d7cb48be94 Binary files /dev/null and b/port/assets/menus/modern/title_mcc_packages_0.png differ diff --git a/port/assets/menus/modern/title_multiplayer_0.png b/port/assets/menus/modern/title_multiplayer_0.png new file mode 100644 index 0000000000..6d87ca12d9 Binary files /dev/null and b/port/assets/menus/modern/title_multiplayer_0.png differ diff --git a/port/assets/menus/modern/title_preview_0.png b/port/assets/menus/modern/title_preview_0.png new file mode 100644 index 0000000000..8feffce145 Binary files /dev/null and b/port/assets/menus/modern/title_preview_0.png differ diff --git a/port/assets/menus/modern/title_server_0.png b/port/assets/menus/modern/title_server_0.png new file mode 100644 index 0000000000..748c2a4fa9 Binary files /dev/null and b/port/assets/menus/modern/title_server_0.png differ diff --git a/port/assets/menus/modern/title_session_0.png b/port/assets/menus/modern/title_session_0.png new file mode 100644 index 0000000000..e557572a45 Binary files /dev/null and b/port/assets/menus/modern/title_session_0.png differ diff --git a/port/assets/menus/modern/title_sharing_0.png b/port/assets/menus/modern/title_sharing_0.png new file mode 100644 index 0000000000..36532c4832 Binary files /dev/null and b/port/assets/menus/modern/title_sharing_0.png differ diff --git a/port/assets/menus/modern/title_voice_0.png b/port/assets/menus/modern/title_voice_0.png new file mode 100644 index 0000000000..4849c7a411 Binary files /dev/null and b/port/assets/menus/modern/title_voice_0.png differ diff --git a/port/assets/menus/modern/xbox_a.png b/port/assets/menus/modern/xbox_a.png new file mode 100644 index 0000000000..b409065446 Binary files /dev/null and b/port/assets/menus/modern/xbox_a.png differ diff --git a/port/assets/menus/modern/xbox_b.png b/port/assets/menus/modern/xbox_b.png new file mode 100644 index 0000000000..65b8c0b5e1 Binary files /dev/null and b/port/assets/menus/modern/xbox_b.png differ diff --git a/port/assets/menus/modern/xbox_x.png b/port/assets/menus/modern/xbox_x.png new file mode 100644 index 0000000000..fb3092d871 Binary files /dev/null and b/port/assets/menus/modern/xbox_x.png differ diff --git a/port/assets/menus/port_svg/main_menu/changelog/header_changelog.svg b/port/assets/menus/port_svg/main_menu/changelog/header_changelog.svg new file mode 100644 index 0000000000..6354ce30e7 --- /dev/null +++ b/port/assets/menus/port_svg/main_menu/changelog/header_changelog.svg @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/port/assets/menus/port_svg/main_menu/menu_changelog__0.svg b/port/assets/menus/port_svg/main_menu/menu_changelog__0.svg new file mode 100644 index 0000000000..3d002c3e64 --- /dev/null +++ b/port/assets/menus/port_svg/main_menu/menu_changelog__0.svg @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/port/assets/menus/port_svg/main_menu/menu_changelog__1.svg b/port/assets/menus/port_svg/main_menu/menu_changelog__1.svg new file mode 100644 index 0000000000..fc5d1cf81d --- /dev/null +++ b/port/assets/menus/port_svg/main_menu/menu_changelog__1.svg @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/port/linux/NETCODE.md b/port/linux/NETCODE.md index 0fee867d36..421fa425a4 100644 --- a/port/linux/NETCODE.md +++ b/port/linux/NETCODE.md @@ -16,7 +16,14 @@ with ideas from VALORANT's netcode articles, keeping the 30 Hz tick: client no longer runs only the ticks the host has sent. A client's clock starts with the host's first game update and takes the host's time from it (at a game's start as at a late join), so every machine reads the - game's timers alike. + game's timers alike. A smaller delay after a stall is recovered by running + extra simulation ticks toward a validated reliable host timestamp. Each + frame runs at most as many extra ticks as its normal time budget, with the + existing cap of 30 total ticks. Fractional frame time is preserved; the + target is never extrapolated. Paused, held and menu clocks do not catch up, + and MCC's host-approved speed still controls the normal budget. Initial + synchronization and the existing clock jump for deficits over 30 ticks + retain their separate paths. - **Own player predicted.** A client drives its own player (and the vehicle it drives) from its local input at once. Remote players are driven by the inputs the host relays every tick, the latest one held @@ -97,6 +104,64 @@ with ideas from VALORANT's netcode articles, keeping the 30 Hz tick: threads' wake times along with it. The object, device and name syncs bring the clients up to date. + Checkpoint loading retains the host's current session + roster (`network_coop_restore_players`), before rebuilding view and input + caches. Saved players who left lose their restored units and remain quit; + current players missing from the save are created in their authoritative + slots and use the normal co-op spawn rules. The machine-to-player table + is rebuilt too: it lives outside the checkpoint, whose datum identifiers + may differ. This fixes restores after reconnects, with either camera perspective. + If an authoritative sample says a unit is alive but the client's copy is + dead, the client requests the existing full object description, with the + existing retry backoff and host rate limit. A validated create replaces + that dead co-op copy instead of reusing it. This also handles a restored + object keeping its checkpoint handle; no client decides to resurrect it. + Recovery is independent of camera mode. Each distributed gameplay header + carries the host's checkpoint epoch, a 32-bit world generation outside the + saved game. It advances on new maps and host reverts, including two restores + at the same tick. Before any fresh object descriptions, the host sends a + reliable checkpoint boundary to every loaded client. Only this exact, + nonbatched host message can advance a client's epoch. Old-generation damage, + object descriptions, inventories, input and prediction are refused before + clock or gameplay processing. New-generation datagrams that overtake the + boundary are also refused; their periodic updates arrive again. + + Until the reliable snapshot end marker arrives, clients accept only its + ordered object descriptions and ordinary inventories. Gameplay sends are + held too, so surviving old replicas cannot generate new-world predictions + or hit reports during a partial snapshot. Client chat/vote actions during + that brief interval are not sent. The snapshot includes empty ordinary + inventories, which the normal periodic sender eventually stops repeating. + MCC extra grenade slots retain their separate periodic snapshots. The end + marker establishes ordering, not successful construction of every object; + failed creations retain the existing retry path. Only the first validated + description of a slot in an epoch may reconstruct an old corpse: a later + resend cannot revive a unit already killed in the current world. + + Client simulation continues during transfer. On the first validated ordered + end marker for the current epoch, `distributed_message_epoch_valid` retires + client projectiles and delayed gameplay effects created while the snapshot + was incomplete, clears queued hits through `network_damage_new_game`, and + resets provisional input, prediction and send histories through + `distributed_reset_checkpoint_state(FALSE)` before ordinary gameplay messages + resume. Already applied objects and inventories remain intact. Sender and per-message receive + times also remain, so older same-epoch datagrams cannot overwrite the ordered + snapshot. Duplicate end markers do not erase current gameplay or its histories. + + Adoption clears transient prediction, death, inventory, animation, input and + queued-effect histories. Client projectiles from the discarded prediction + and delayed effects capable of damage/object creation are deleted through + their normal lifecycle; host checkpoint projectiles and effects are + preserved. Existing live replicas and identity tracking remain, so a valid + description rebuilds a corpse without replacing healthy units unnecessarily. + Connection identity, authority and the current roster survive. A late joiner's + reliable ready request may carry epoch zero; the rate-limited snapshot reply + supplies the current boundary first. Duplicate boundaries do not reset state. + The [checkpoint regression](../../tools/test_coop_checkpoint_recovery.py) and + [dispatcher regression](../../tools/test_checkpoint_epoch.py) cover the earlier + dead-replica and old-life-kill failures. Actual runtime checks and their limits + are recorded in the [Milestone 10 fix evidence](../../docs/mcc_refactor_validation.md#stage-10-shared-checkpoint-recovery-fix). + The host's EXTRA ENEMIES (`coop_enemies.c`, `network.coop_enemies_mode`) give each squad of enemies a level places more of itself: PER PLAYER, a percentage of itself for each player past the first, to 8 times its size @@ -460,6 +525,105 @@ version (`tools/network_format.py`): `test_linux_port.py` fails when the sources' messages, kinds, bits, structs sent whole or the sizes of their arrays differ from it. +GulchCE version 29 combines upstream WebRTC signalling with its existing +MCC campaign snapshots (previously GulchCE version 28). + +GulchCE version 30 retains those messages and adds MCC package-qualified map +identities and package resource fingerprints to map admission. The existing +map-version field carries the fingerprint; no packet fields are added. Peers +must agree on this meaning, so version 29 clients cannot join version 30 games. +Xbox and Custom Edition map checksum calculations are unchanged. + +GulchCE version 27 includes MCC extra-grenade inventory/action support and campaign +state snapshots for gravity, dialogue gain and breadcrumb markers. All +participants need the same protocol version, including on Xbox or Custom +Edition maps; their existing inventory packet layouts are unchanged. MCC +sessions use this netcode and the existing host-controlled co-op systems, +not the official MCC client or matchmaking. See [MCC map support](../../docs/mcc_maps.md) +for resource requirements and the bounds of gameplay testing. + +GulchCE version 33 adds upstream Custom Edition map sharing alongside MCC. +Map sharing retains upstream IDs 83-86; MCC moves to 87-88. Versions 31-32 belong +to the separate camera test branch and are not compatible with this protocol. + +GulchCE version 34 adds MCC named-object presence chunks (message 89) for +MCC scenarios with more than 512 names, up to 32,767. The host sends bounded +512-name chunks every 15 ticks, in co-op and multiplayer. Clients validate +the count, range, padding, BSP and timestamp, and confirm a difference in +two distinct snapshots before creating/deleting scenery or devices. Native +unit/item replication is retained. Smaller MCC, Xbox and Custom Edition +maps keep their original name tables and messages. All peers need version +34; it cannot connect to version 33, including on legacy maps. Version 34 +also assigns campaign flag bit 3 to MCC script-controlled muting. + +GulchCE version 35 combines upstream OpenCE version 28's map-download +admission, multiplayer BSP, lighting and weapon-selection rules with the +MCC messages and semantics from GulchCE version 34. Both peers must use 35; +upstream version 28 and GulchCE version 34 cannot join these games. MCC +message IDs 87-89 and package fingerprints are retained. The wire-format +record is regenerated for the combined implementation. + +GulchCE version 36 requires both peers to use MCC package-first resource +selection and dependency-based fingerprints. Explicit root files take precedence +over automatic selection between `_shared/singleplayer` and `_shared/multiplayer`; +a candidate must satisfy all references of its type, and differing complete +candidates are refused as ambiguous. Only externally referenced +bitmap and sound files contribute; loose MCC levels now include their used +resources too. Identical selected contents match across installation locations. +Required missing files fail admission. Version 35 and earlier cannot join; +all players, including those playing Xbox/Custom Edition maps, need version 36. +No message layout or client authority changes. The checksums detect accidental +resource mismatches; they do not authenticate untrusted files or clients. + +GulchCE version 38 adds MCC weapon-authored third-person camera selection to +deterministic aiming. Existing inventory and weapon-selection synchronization +supplies the camera choice; no messages, packet layouts or client authority +change. All peers must use the same aiming behavior. Version 37 is reserved for +the separate optional third-person branch and is not compatible with this one. + +GulchCE version 39 permits authored MCC biped seats in the existing host-to-client +seat state. The host checks the action, proximity, occupancy and animation before +boarding; clients apply the host's object identity and seat. Biped parents do not +become client-owned predicted vehicles. No packet layout changes, but older peers +would reject these parents and disagree about attachments and camera/aiming. + +GulchCE version 40 adds host-authored MCC campaign effect flags to the existing +campaign snapshot (state version 3, unchanged packet size). Clients predict +jetpack, super-jump and ammunition behavior from those flags without enabling +their native cheat globals. While movement effects are active the host simulates +movement from validated inputs and does not accept client position/velocity +corrections. MCC possession uses host-owned player attachment; clients leave the +former body's fate to host object/damage replication. Xbox and Custom Edition +retain their original simulation paths, but all peers require version 40. +Xbox and Custom Edition keep their existing vehicle-seat behavior; all peers +still need the matching network version. + +GulchCE version 41 adds the reliable host-to-client MCC game-speed message +(message 90: the distributed header and one float). It carries the host-approved +clock multiplier, including zero while paused, so clients advance at the host's +scripted rate. Clients reject invalid values and messages from other clients; +the host does not accept client speed changes. Xbox and Custom Edition retain +their existing clock behavior. All peers need version 41 because older clients +would ignore the message and simulate MCC maps at the wrong rate. + +GulchCE version 44 combines version 42's MCC content identity with upstream +OpenCE version 29's Custom Edition map-name and hash-version semantics and +map-sharing validation. MCC message IDs and SHA-256 admission remain unchanged. +Version 43 is reserved for the optional camera branch. Older GulchCE and +upstream OpenCE peers cannot join these games. + +GulchCE version 42 appends a 32-byte MCC SHA-256 content fingerprint to the +host's fragmented game settings. Xbox/CE use zero in this extension and retain +their existing map checks. MCC clients bind the host's session name to a verified +local package, allowing different folder names. The fingerprint covers complete +map bytes and each required resource file with type/length framing; paths are +excluded. All 32 digest bytes must match before readiness and loading. The +32-bit map version remains for existing save/version bookkeeping, not as the +MCC content admission proof. All peers require version 42; host authority and +gameplay messages are unchanged. This checks installed content, not client +integrity or anti-cheat attestation. + + A client plays by its host's rules: in another's game (searching for it, in its lobby, or playing it) the developer console, the telnet console and the cheat buttons run only commands that change nothing of the game @@ -476,7 +640,7 @@ hack, which speeds up the machine's own clock, so that nothing on it can tell): every two seconds it measures how fast the ticks the client's messages are stamped with go by against its own clock's time, and how far ahead of its own time they are. A client's clock starts at the host's and -only ever jumps forward to it when behind, so an honest one is never ahead +recovers toward a reliable timestamp only when behind, so an honest one is never ahead while going faster (one that caught up, or a host that stalled, is one or the other, not both). One more than a tenth faster and half a second ahead has its players' predictions refused at once (the host's copies go as its @@ -955,7 +1119,9 @@ already published survives a subsequent admission failure. Implementation lives in `mcc_share.c`, `mcc_share_package.c`, `mcc_share_session.c`, `mcc_share_stage.c` and the MCC metadata helpers. Managed-copy receipts and the removal UI preserve separate ownership of -downloaded snapshots. +downloaded snapshots. Native platform, transport, real-map and follow-on-mission +checks and their limits are recorded in +[Milestone 13](../../docs/mcc_refactor_validation.md#milestone-13-implementation-evidence). Browser publication uses an owned OPFS journal and commit record instead of a directory rename; see [browser storage](../../docs/reading/browser_imports.md). Browser gameplay, downloads and persistence have their own Milestone 14 @@ -1117,7 +1283,7 @@ validation gates; native results do not establish browser compatibility. the client's round trip and a second before the report came; not checked for what the tags do not bound: a projectile that sticks, which what it sticks to carries, one whose timer starts once it bounces or rests, a weapon's own - detonation; no line of sight); the target within a few world units of + detonation); the target within a few world units of where the host had it at the tick the report was made at (a player's unit or vehicle: the host keeps a second of where they were) or of where it is (more for a fast one; also for one that is no longer a @@ -1142,6 +1308,17 @@ validation gates; native results do not establish browser compatibility. client's projectiles deal nothing (the report does), but once that client has left the game they deal what they hit, as its own do (a hit the client reported just before it left may so be dealt twice). + - A reported point hit also needs a structure line of sight from the + shooter's recent living trail. The host tries the target centre, then + a route through the reported impact clamped to the target's sphere; + both legs of that route must be clear. A driver or gunner may use the + recorded vehicle muzzle only if the eye-to-muzzle segment is clear. + History and trace counts are bounded; missing living history refuses + the report. This deliberately uses lag-compensation windows rather + than matching both endpoints to one tick. Melee, vehicle collision + and area damage retain their existing checks. An attached detonation + may bypass sight only with a matching unspent attachment recorded by + the host; its bounded ledger expires and clears for each new game. - The host sends its clients the damage it dealt to units, and a client replays what it does besides the harm (which the units' states bring): the player's screen flash and shake, the unit's flinch, pain @@ -1280,6 +1457,48 @@ Unity's Netcode for Entities, lightyear, netfox and the Ares source): ## Testing +In GulchCE Third Person sessions, the host's camera policy travels in the reliable game settings +record (bits 4-5 of `network_game.cooperative_flags`), for every transport +and game type. Zero allows player choice, one forces third person, and two +disables it. Receivers reject the reserved value and unknown flag bits. +Pregame edits are host-only; late joiners receive the same record. Camera +preferences are never written by receipt of a policy. The experimental camera +protocol prevents stock OpenCE clients, which cannot enforce this rule, +from joining. It also carries the current shoulder state in each +player input and host relay. It is a state, never accumulated with earlier +button presses. The host masks unknown input bits and Forced Off clears it. +Scoped, dead and seated units retain stock firing. Each simulation computes +the muzzle and cover correction from world markers. The camera feature does +not send muzzle positions. The separate upstream `network.fire_origins` +option retains its existing host controls and validation. +Damage still uses the existing validated hit reports. The host records its +own shoulder muzzle in visibility history, alongside the existing eye route, +so a legitimate shot from beside cover is not judged only from the head. +Both the eye-to-muzzle and muzzle-to-impact routes must be clear; weapon +ownership, rate, target history and damage limits still apply. Scoped, dead, +seated, Forced Off and ordinary first-person paths do not add this history. +The camera rules use agreement version 32744. Shared checkpoint recovery +also applies in Crossplay sessions through upstream protocol 43. Older camera +builds are excluded; camera policy bits leave upstream vehicle riding intact. +The host independently excludes weapon-authored following cameras from the +shoulder solver; stale or forged input bits cannot override that priority. +The relay rejects non-boolean shoulder values and truncated messages. + +Add `--combat` to the session runner below to exercise real bot firing on +both peers, including 100 ms receive delay and 5 percent packet loss. Muzzle +diagnostics identify shooters on each peer; this does not visually verify +effects or exercise the public internet transport. + +`tools/camera_policy_sessions.py --binary build/windows/halo.exe --maps +dist/halo-windows-release/maps --output build/camera-policy-sessions` runs +two headless Windows instances with isolated saves over loopback. Add +`--saves ` to copy a preselected profile for unattended startup; +the source saves are never changed. Use a new output folder for every run. It checks +all policies, an opposing client host preference, a late join and co-op. +The supplied map directory must contain ui, carousel, bloodgulch and a30. +The policy, saved preference, effective setting and active shoulder view +are included in `debug.network_test`'s per-second logs. + `debug.network_test` (`port/linux/game/network_test.c`) hosts or joins a game without the menus (in a team game the joining player takes the other team; `local:` plays a local split screen game instead, which the @@ -1289,7 +1508,14 @@ down); each machine logs every player's position, health and shields, where they aim and face, their animation state and how hard they move, weapons, grenades, score, kills and deaths every second, with the objects made and removed and the hits reported, dealt, rejected and replayed, so -two machines' views of one game can be compared. `debug.network_test_kill`, +two machines' views of one game can be compared. Observation uses the first +frame in each absolute 30-tick simulation second and records its actual tick. A late +first sample does not offset every following sample; missed states are never +invented or backfilled. The comparison still requires samples within two ticks. +The reported drift counters accumulate since the preceding observation and +are reset when read; they do not drive simulation or correction. Scripted test +actions keep their separate established cadence. +`debug.network_test_kill`, `debug.network_test_shoot`, `debug.network_test_vehicle` and `debug.network_test_pickup` script kills, hits, a vehicle ride and a weapon swap the bots' wandering does not reach (`debug.network_test_pickup_weapon` @@ -1334,6 +1560,30 @@ action button where the host has nothing for them to pick up, with where it has them and the nearest item: a client that sees a pickup the host does not. +The host's Session Compatibility selector defaults to Crossplay +(`opence_crossplay`). Xbox, Custom Edition and MCC maps all use OpenCE protocol +43, including its shared checkpoint, loading and content identity messages. +There is no separate MCC capability or join envelope. The optional shoulder +camera, its input and muzzle behavior remain disabled in Crossplay mode. +GulchCE Only (`gulchce_third_person`) advertises camera protocol 32744 for every +map family, requires a kind 102 envelope before admission and adds the shoulder +byte to relayed actions. The envelope's bound is 520 bytes: an eight-byte camera +header plus at most 512 bytes of ordinary join data, including account-link +credentials. Its header carries revision 1, camera version 32744 and zero +reserved bytes. Nested envelopes are rejected. Ordinary authorization and +map-family checks still apply. + +Session mode is selected before opening the lobby and locked until disposal, +including across rounds. The client binds camera permission to the selected +host's exact advertised version and clears it on disconnect. Unknown versions +are rejected; settings cannot grant capability. Player preferences are not +rewritten. All platforms and transports share this path. Common internet +listings use the base discovery format; admission establishes compatibility. +See [the camera guide](../../docs/reading/third_person.md) for lifecycle details. +Asset-free checks exercise both relay formats, malformed envelopes, host locks, +policy enforcement and the pinned upstream contract. Actual crossplay and +browser gameplay must also be tested against the resulting build. + ### Comparing two builds `tools/net_compare.py` checks that two builds play a network game in step: @@ -1451,3 +1701,6 @@ changes only the ticks in the air, as gravity does, is within what identical builds show, and not caught. Positions agree to 0.04 world units on average, 0.24 at most, in every game, perturbed or not: the netcode corrects them. + +MCC camera-relative projectile rays use upstream agreement 43 (camera mode 32744). +Xbox/CE agreement versions are unchanged. Firing and preview share `mcc_projectiles.c`. diff --git a/port/linux/README.md b/port/linux/README.md index 95c399f688..ccf6ec8b45 100644 --- a/port/linux/README.md +++ b/port/linux/README.md @@ -399,7 +399,7 @@ problem. ## Bots Computer players (bots) can play a local multiplayer game with you: -`bots.count` (1 to 15) of them join the lobby of a Slayer game played on +`bots.count` (1 to 63) of them join the lobby of a Slayer game played on this computer, which is Multiplayer > Split Screen in the Xbox's menus (`display.menus = "xbox"`; the PC version's menus have no game of this computer alone). They are players as you are: in the scores, the respawns @@ -407,9 +407,41 @@ and the game's rules, on the teams that `bots.teams` asks for, and they follow the teams' changes in the lobby. They look for enemies, aim, fire, throw grenades and pick up better weapons, as well as `bots.skill` lets them, and walk the paths that the campaign's AI finds on the maps' walkable -surfaces (`game/bots.c`). They are never in system link or internet games, -nor in other gametypes (but SWAT, Infection and Gun Game, which are -Slayer's: below), and nothing that the machines send each other changes. +surfaces (`game/bots.c`). These remain the defaults, including Slayer-derived +SWAT, Infection and Gun Game. Optional `bots.enhanced` selects an independent controller with CTF/King goals, +team roles, vantage points, skill-based aiming, powerup claims and Infection +goals. Bots can plan through teleporters and climbable ladders; `bots.routes` +selects direct paths or side lanes, and `bots.vehicles` enables ground vehicles +and turrets plus aircraft using authored vehicle types and seats, with passenger +waits, flipping, hull clearance and bounded 3D aircraft routes. Nearby bots can +board friendly player vehicles. Map-specific scripts and water-only boat routes +are not inferred; see the [controller guide](../../docs/reading/enhanced_bots.md). +The optional `bots.thread` path worker uses private snapshots; it defaults off +and fixed-tick benchmarks always use synchronous searches. +Enhanced policy takes effect at map load. `bots.network` permits host-controlled +bots in system link and internet games. Enable it before hosting, or press +**OK** in the lobby's Bots settings to apply it without re-hosting. Turning it +off there removes the lobby's bots. Once reserved, their machine IDs remain +reserved until the host closes, so pending updates cannot collide with humans. +If a human connection already holds one of those IDs, an error asks you to +re-host with Network Bots enabled. Changes during a match leave its bot policy +unchanged and are read when creating the next host. +The CE menus expose these settings at **Settings > Network > Bots**, with +shortcuts in Create Game and the host's lobby. During a match, **Manage +Current Bots** adds/removes bots by team without changing the saved count. +Network bots automatically make room for arriving humans and return after +humans leave. The first admitted humans plus Bot Count establish a session +population target, bounded by the player limit. Live add/drop commands adjust +that target for this session. There is no separate replacement toggle. +Internet and LAN browser populations, master listings and Discord presence +count humans only; bots remain ordinary players in the match and scoreboard. +See [population and crossplay](../../docs/reading/bot_population.md) for +join ordering, restoration and limits. +The lobby's player limit still applies: allow at least 64 slots for 63 bots +and one human. Xbox menu defaults and navigation are unchanged. +Clients receive ordinary player records and actions. All additions default +off (routes default to direct). See the +[implementation and credits](../../docs/reading/bots_and_android_features.md). `bots.skill` sets six levels, from `"recruit"` (for new players: it reacts late, aims loosely and never throws) to `"legendary"`. Each level fights as @@ -495,20 +527,28 @@ the setting for one start of the game. It has priority over the file. | `display.menu_cursor` | `"large"` | `HALO_MENU_CURSOR` | Windows, Linux and the web: the menus' pointer for the mouse, the game's blue arrow, sized to the window as Halo PC's was: `"small"`, `"medium"`, `"large"` or `"extra_large"` (18, 24, 32 or 40 of the menus' 480 lines tall), or `"off"` for the system's pointer. MENU CURSOR in Settings > Mouse writes its choice here. | | `display.show_fps` | `false` | `HALO_SHOW_FPS=1` sets `true` | `true`: the frame rate at the bottom right of a game, counted over half a second and green from 30 frames each second, red below. The game's own counter, which the Xbox version's `display_framerate` console variable showed. Refer to "Frame rate". | | `display.direct_camera` | `true` | `HALO_DIRECT_CAMERA` | `true`: in first person, on foot, the view points where the player aims in each frame, not where the last tick left it. Refer to "Frame rate". | +| `display.third_person` | `false` | `HALO_THIRD_PERSON` | Right-shoulder view on foot. Toggle in Settings > Video Setup > FOV And Viewmodels, then select OK; no restart needed. Zoom, vehicles, death and cinematics use their stock cameras. Unscoping restores the shoulder view immediately at its unscoped FOV, subject to camera collision. Free look must be released and pressed again after scoping or another forced camera change. The reticle shows the nominal aim point; it traces the weapon offset and muzzle-to-target path, including nearby cover and the fully charged secondary muzzle. It does not predict spread, gravity, homing or target movement. Camera collision pulls the view in near walls, with gradual recovery. In offline and network games, aimed shoulder shots originate at the world weapon muzzle and converge on the aim point, with checks for cover between eye, firing origin and muzzle. Alternating firing effects select their authored trigger muzzle. Targets behind the barrel never turn shots backwards. This changes close-range shot geometry. Network peers replicate the firing perspective and solve the same muzzle and cover checks. Third person uses the stock FOV; returning to first person restores `display.fov`. | +| `display.third_person_smooth` | `true` | `HALO_THIRD_PERSON_SMOOTH` | Smooth recovery and shoulder changes, with frame-rate-independent settling and bounded damping for small vertical steps; false selects Sharp. Free-look return finishes in 0.25 seconds in Smooth and immediately in Sharp. Collision-forced first person requires 0.10 seconds of continuous clearance before recovery in either mode. Set Camera Motion in FOV And Viewmodels > Shoulder Camera. Collision remains enabled in either mode. | +| `display.third_person_left_shoulder` | `false` | `HALO_THIRD_PERSON_LEFT_SHOULDER` | Use the left shoulder. Press B to swap during play, or choose the shoulder in FOV And Viewmodels > Shoulder Camera. | +| `display.third_person_distance` | `0.85` | `HALO_THIRD_PERSON_DISTANCE` | Distance behind the eye, 0.3�2.0 world units. | +| `display.third_person_height` | `0.12` | `HALO_THIRD_PERSON_HEIGHT` | Height along camera up, -0.2�0.6 world units. | +| `display.third_person_offset` | `0.24` | `HALO_THIRD_PERSON_OFFSET` | Lateral distance toward the selected shoulder, 0�0.6 world units. | +| `controls.swap_shoulder` | `"B"` | `HALO_KEY_SWAP_SHOULDER` | Swap shoulders in third person; remappable in Controls Setup > Camera. | +| `controls.free_look` | `"Left Alt"` | `HALO_KEY_FREE_LOOK` | Hold to orbit the shoulder camera with mouse or right stick while aim stays fixed. Release to return; follows Camera Motion Smooth/Sharp. Remappable in Controls Setup > Camera. | +| `controls.toggle_perspective` | `"N"` | `HALO_KEY_TOGGLE_PERSPECTIVE` | Press once to toggle first/third person. Remappable in Controls Setup > Camera. Scoping and collision still force first person. | | `display.fov` | `0.0` | `HALO_FOV` | The first-person view's field of view on foot, in degrees across at 16:9, from 20 to 150. `0`: the stock view. Refer to "Field of view". | | `display.viewmodel_fov` | `0.0` | `HALO_VIEWMODEL_FOV` | The first-person weapon's and hands' field of view, in degrees across at 16:9, from 20 to 150. `0`: the weapon's stock view, also when `display.fov` widens the world. Refer to "Field of view". | | `display.viewmodel_visible` | `true` | `HALO_VIEWMODEL_VISIBLE` | `true`: the first-person weapon, hands and what is attached to them are drawn. `false`: they are not; firing, animation, sound and lights go on, and other players' models are drawn. | | `display.passenger_third_person` | `false` | `HALO_PASSENGER_THIRD_PERSON` | Third-person view for the Warthog's passenger and the Scorpion's four passengers. Uses the gunner's camera on the Warthog and the driver's on the Scorpion, within the passenger's firing arc. Smooth entry and exit; weapon zoom is disabled while riding. The reticle follows the shot's centre ray. Local view only. In the campaign and co-op only: not in multiplayer, where seeing around the vehicle would be an advantage. | -| `display.viewmodel_shield` | `false` | `HALO_VIEWMODEL_SHIELD` | `true`: the energy shield's flare (its hits, its charging, its fall) is drawn on the first-person arms too, as on the body, with the unit's own shield shader, kept closer to the arms than to the body. The stock game draws it on the body only. | -| `display.first_person_legs` | `false` | `HALO_FIRST_PERSON_LEGS` | `true`: your own body is drawn from the waist down in first person, so you see your legs when you look down, moving as the body's animation moves them. Refer to "Field of view". | -| `display.shield_color` | `default` | `HALO_SHIELD_COLOR` | Your energy shield's flare as this machine draws it: `default` (the shield's own) or a multiplayer armor color (`white`, `black`, `red`, `blue`, `gray`, `yellow`, `green`, `pink`, `purple`, `cyan`, `cobalt`, `orange`, `teal`, `sage`, `brown`, `tan`, `maroon`, `salmon`), whatever the armor's, on the body and, with `display.viewmodel_shield`, on the first-person arms. The shield's own shader is drawn with its two colors replaced at their brightness; the flare is added to what is behind it, so `black` is drawn a faint grey. Only this machine sees it. | +| `display.shield_look` | `"classic"` | `HALO_SHIELD_LOOK` | Video Setup > FOV and Viewmodels > SHIELD LOOK, in order: DEFAULT, CLASSIC WITH SPRINKLES, MARK VI, INFINITE HONEYCOMB. Saved values are unchanged: `"classic"` preserves the established appearance; `"enhanced"` (MARK VI) applies CMT Snow Grove's plasma pattern and first-person shields with the approved small outward body flare (formerly ENHANCED 2). `"classic_with_sprinkles"` uses the stock Xbox shield surface with the same layer offsets, depleted arcs and recharge animation as MARK VI, preserving custom colours and Arm Shields control. `"classic_honeycomb2"` (INFINITE HONEYCOMB) makes the body links follow Classic plasma brightness with a visible minimum, retaining the same first-person arms. Saved `"enhanced2"` values migrate to `"enhanced"`; retired `"honeycomb"` and `"classic_honeycomb"` values return to DEFAULT. DEFAULT preserves map-authored shields; non-default presets apply only to player bipeds (local or remote), leaving AI shields unchanged, and override authored player shield modifiers on Xbox, CE and MCC maps, including plasma model shells, while inheriting custom plasma RGB or per-object colour channels. Stock and CMT palettes retain the approved preset colour; hue inheritance preserves preset peak brightness and does not change opacity, pattern, animation or offsets. Animated Overshield layer colours retain precedence. Independent of mods; Arm Shields controls whether first-person shields draw and supplies their offset and FOV limit. With the locally extracted Bigass sprite bundle, non-CLASSIC presets add electrical arcs while shields are depleted and waiting to recharge. During normal recharge, non-CLASSIC presets subtly grow the existing layer with shield vitality and retreats for half a second at full charge; arms remain within the Arm Shields limit. Local drawing only. See [Shield Look](../../docs/shield_look.md) for eligibility, reference data and validation limits. | +| `display.viewmodel_shield` | `false` | `HALO_VIEWMODEL_SHIELD` | `true`: the energy shield's flare is drawn on the first-person hands as on the body (the unit's own modifier shader, colors and values; not on the weapon), standing off them by no more than a small share of the view at the viewmodel's field of view; with `display.overshield_effect`, the overshield comes up on them as its rise passes the chest. `false`: the stock game's, on the body only. Only this machine's drawing changes (`viewmodel_shield.c`). Video Setup's FOV and Viewmodels screen sets it. | +| `display.first_person_legs` | `false` | `HALO_FIRST_PERSON_LEGS` | `true`: draw your animated legs in your own first-person view while alive and on foot. The body turns about the drawn pelvis to face the view. Private triangle buffers omit the head and arms, retaining the original torso-to-hip surface and all skinning weights; no bones are collapsed. The whole pose moves back at least 0.16 world units (about 49 cm). The animated upper surface and cut boundaries determine additional clearance at wider FOVs, so openings stay outside the view. Looking up and down alone does not change this offset. Unsupported skeletons or geometry hide the local body and log the reason. Private buffers are bounded to 256 parts and a 16 MiB CPU allocation budget, and released on disable or map teardown. Original map geometry, materials and palettes remain unchanged. Not in vehicles, third person, shadows or reflections; each split-screen view draws its own. `false`: stock behavior, with no local body in your view. Only local rendering changes (`first_person_legs.c`, `first_person_legs_geometry.c`). Video Setup's FOV and Viewmodels screen sets it. | | `display.high_res_hud` | `true` | `HALO_HIGH_RES_HUD` | `true`: the HUD (meters, counters, panels and their outlines, the motion sensor, reticles, waypoints, scopes) is drawn from the high-res assets in `port/assets/hud`, 8x the size of the maps' bitmaps. The bitmaps with English text keep the maps' own. `false`: the maps' own bitmaps. | -| `display.hud_button_style` | `classic` | `HALO_HUD_BUTTON_STYLE` | Manual high-res gameplay button style: `classic`, `gems`, `menu_gems` (Xbox Dark Gems), `xbox_modern`, `ps_classic`, `ps_gems`, `ps_dark_gems`, `ps_modern`, `switch_classic`, `switch_gems`, `switch_modern`, `keyboard`. Keyboard uses current gameplay bindings and works with High-Res HUD off; select it with auto detection off. Existing Xbox artwork and saved tokens are unchanged. Applies to Xbox and Custom Edition prompts. | -| `input.auto_button_detection` | `true` | `HALO_AUTO_BUTTON_DETECTION` | Gamepads > Button Appearance: restrict controller artwork to the assigned family. With Keyboard Glyphs enabled, keyboard/mouse activity selects gameplay keycaps; controller activity restores its artwork. Off uses the manual style. Detection runs independently of this choice. Controller artwork requires High-Res HUD; keyboard glyphs do not. | -| `display.menu_button_glyphs` | `false` | `HALO_MENU_BUTTON_GLYPHS` | Apply the selected keyboard, Xbox, PlayStation or Switch style to existing PC-menu A/B/X/Y legends and inline face-button tokens. Keyboard uses fixed menu controls (Return, Esc, Del, Tab), independently of gameplay bindings. Does not require High-Res HUD; Xbox menu selection and ordinary text buttons stay native. | -| `display.keyboard_glyphs` | `false` | `HALO_KEYBOARD_GLYPHS` | Gamepads > Button Appearance: opt in to automatic binding-aware keyboard/mouse gameplay prompts. Requires Auto Button Detection. Manual Keyboard style works with detection off independently of this setting. Enable Menu Glyphs separately to apply the same selection to PC-menu face-button legends. See [keyboard prompts](../../docs/reading/keyboard_prompts.md). | +| `display.hud_button_style` | `classic` | `HALO_HUD_BUTTON_STYLE` | Manual button style: `classic`, `gems`, `menu_gems` (Xbox Dark Gems), `xbox_modern`, `ps_classic`, `ps_gems`, `ps_dark_gems`, `ps_modern`, `switch_classic`, `switch_gems`, `switch_modern`, `keyboard`. Keyboard/mouse glyphs use current controls and work independently of High-Res HUD; disable auto detection to force this style. Existing Xbox artwork and saved tokens are unchanged. Applies to Xbox, Custom Edition and MCC prompts. | +| `display.menu_button_glyphs` | `false` | `HALO_MENU_BUTTON_GLYPHS` | Use the selected keyboard or controller artwork in stock PC navigation and pause legends, including MCC pauses. Modern Interface calls this Stock Menu Glyphs; classic Button Appearance calls it Menu Glyphs. Requires High-Res HUD. Modern prompts are separate; Xbox menus are unchanged. | +| `input.auto_button_detection` | `true` | `HALO_AUTO_BUTTON_DETECTION` | Follow active keyboard/mouse or controller input. Keyboard shows keycaps in modern menu footers and supported gameplay prompts; touch retains its native presentation. Automatic mode shows a read-only Keyboard style or the controller family's saved artwork. Off restores the saved manual style, including Keyboard. Unknown controllers use the manual style. Keyboard and controller glyphs require High-Res HUD in gameplay and menus; menus use text or native prompts when it is off. The removed `display.keyboard_glyphs` option no longer gates detection. | | `display.hud_bumper_style` | `original` | `HALO_HUD_BUMPER_STYLE` | Gamepads > Button Appearance: BUMPER STYLE offers `original` (Original Xbox black/white buttons) and `modern` (LB/RB), only for Xbox Classic, Xbox Gems and Xbox Dark Gems. Shared by local players and retained with automatic detection on. Requires High-Res HUD; other styles keep their own bumpers. | -| `input.controller_p1` | `""` | `HALO_CONTROLLER_P1` | P1 custom controller layout, including D-pad, communication, debug camera and unbound actions; empty uses the profile preset. Debug includes Cycle Camera (hold RB/Black for one second by default) to enter and leave flying view. Edit in Gamepad Setup > Button Remapping. See [format and behavior](../../docs/reading/controller_remapping.md). | +| `input.controller_p1` | `""` | `HALO_CONTROLLER_P1` | P1 custom controller layout, including D-pad, communication, debug camera, camera perspective and unbound actions; empty uses the profile preset. Debug includes Cycle Camera (hold RB/Black for one second by default) to enter and leave flying view. Camera Perspective offers Third Person On / Off and Swap Shoulder, both unbound by default and subject to host rules. Edit in Gamepad Setup > Button Remapping. See [format and behavior](../../docs/reading/controller_remapping.md). | | `input.controller_p2` | `""` | `HALO_CONTROLLER_P2` | P2 custom controller layout; empty uses the profile preset. Edit in Gamepad Setup > Button Remapping. See [format and behavior](../../docs/reading/controller_remapping.md). | | `input.controller_p3` | `""` | `HALO_CONTROLLER_P3` | P3 custom controller layout; empty uses the profile preset. Edit in Gamepad Setup > Button Remapping. See [format and behavior](../../docs/reading/controller_remapping.md). | | `input.controller_p4` | `""` | `HALO_CONTROLLER_P4` | P4 custom controller layout; empty uses the profile preset. Edit in Gamepad Setup > Button Remapping. See [format and behavior](../../docs/reading/controller_remapping.md). | @@ -516,9 +556,11 @@ the setting for one start of the game. It has priority over the file. | `display.hud_button_style_ps` | `ps_classic` | `HALO_HUD_BUTTON_STYLE_PS` | PlayStation preference while automatic detection is on: `ps_classic`, `ps_gems`, `ps_dark_gems`, `ps_modern`. | | `display.hud_button_style_switch` | `switch_classic` | `HALO_HUD_BUTTON_STYLE_SWITCH` | Switch preference while automatic detection is on: `switch_classic`, `switch_gems`, `switch_modern`. Preferences are per family; each split-screen viewport resolves its own assigned controller. See the [controller walkthrough](../../docs/reading/controller_buttons.md). | | `display.high_res_text` | `true` | `HALO_HIGH_RES_TEXT` | `true`: the menus' and HUD's text is drawn with the fonts in `port/assets/fonts` (Overpass, in place of the maps' Interstate) at the resolution the game draws at, laid out as before; the menus' titles are drawn from the high-res pictures in `port/assets/titles`, and the controller button icons from those in `port/assets/buttons`. `false`: the maps' bitmap fonts, titles and button icons. | -| `display.widescreen_loading` | `true` | `HALO_WIDESCREEN_LOADING` | Widen the original loading screen, keeping its stock mask, sweep, blur and glow trails. Off keeps the central 4:3 framing. PC Settings > Video > Graphics, including from the PC-style pause menu. See [loading presentation](../../docs/loading_presentation.md). | +| `display.widescreen_loading` | `true` | `HALO_WIDESCREEN_LOADING` | Widen the original loading screen, keeping its stock sweep, blur and glow trails. Includes MCC loading; off keeps the central 4:3 framing. See [loading presentation](../../docs/reading/loading_presentation.md). | | `display.shadow_resolution` | `128` | `HALO_SHADOW_RESOLUTION` | The size of the maps that the shadows of the objects are drawn in, in pixels each way: `128`, `256`, `512` or `1024` (other values go down to one of these). The game draws the shadow of each object into a map of 128x128 pixels, blurs it and projects it onto the ground. On a large screen, the edges of these shadows show steps that move when the object moves. A larger map makes the edges smooth; the blur is made wider to match, so the shadows are as soft as on the Xbox. Each doubling adds two passes of the blur. `128`: as on the Xbox. | | `display.menus` | `"pc"` | `HALO_MENUS` | `"pc"`: the PC version's menus, from the files in `port/assets/menus` and a `menus` folder next to `config.toml`. Refer to "Menus". `"xbox"`: the Xbox's menus. | +| `display.menu_frontend` | `"modern"` | `HALO_MENU_FRONTEND` | Settings/submenu style: Modern (default), `"pc"`, `"xbox"`, or `"off"` to preserve `display.menus`. Explicit saved choices are retained. Change it in Modern Interface or stock/Xbox Video Setup > Graphics, including Settings opened from pause on Xbox, CE and MCC maps. In-game changes apply only on return to the main menu; the current style persists across gameplay map changes. Pause roots still use their established policy and the starting menu retains its layout. Crossing Off rebuilds the UI only at the main-menu boundary. Modern Campaign and multiplayer map choosers, difficulty, hosting and lobby screens use the new presentation; the server browser remains native. Tab/Y opens Modern Settings from the starting menu. Its six tabs have scrolling lists, pending edits, widescreen layout, plasma panels and device-aware prompts. See [the frontend guide](../../docs/reading/menu_redesign.md). | +| `display.changelog` | `true` | `HALO_CHANGELOG` | Show CHANGELOG beneath the build labels in the PC main menu, with the build's recorded player notes. Restart after changing. The Xbox menus are unchanged. | | `display.menu_language` | `"maps"` | `HALO_MENU_LANGUAGE` | The PC menus' language. `"maps"`: the language of the Custom Edition whose `loc.map` is in `custom_maps` (English without one). `"english"`: English. The port's own lines are English. | | `display.player_names` | `"all"` | `HALO_PLAYER_NAMES` | In multiplayer, whose names are drawn above their heads: `"all"`, `"allies"`, `"enemies"` or `"none"`. An ally's name is drawn above the triangle the game shows over teammates. An enemy's name shows only within the motion sensor's reach, while the enemy is in sight and not camouflaged, so it never shows where an enemy hides. The gametype's motion tracker setting also applies: no names if it shows no players, only allies' if it shows only friends. | | `display.player_name_scale` | `1.0` | `HALO_PLAYER_NAME_SCALE` | How large the players' names are drawn: `1.0` is three quarters of the size of the HUD's text, from `0.25` to `4`. With high-res text, larger names are rasterized at their size, so they stay sharp. | @@ -531,15 +573,30 @@ the setting for one start of the game. It has priority over the file. | `display.anisotropic_filtering` | `0` | `HALO_ANISOTROPIC_FILTERING` | Textures seen at a grazing angle (floors, walls, terrain) are sampled along the angle from finer mip levels, so they stay sharp; the Xbox game asks for none. `0` or `1`: as on the Xbox. `2`, `4`, `8` or `16`: at most that many samples (at most the GPU's); `4` keeps most of `16`'s sharpness at less cost on slower GPUs. TEXTURE FILTERING in Video Setup > Graphics. It applies to the textures of the map that have mip levels and are filtered linearly (base, detail, bump and environment maps; lightmaps have no mip levels), not to what the game renders, such as the water's ripples. On Android and the web, only where the GPU has `GL_EXT_texture_filter_anisotropic`. | | `display.latency_meter` | `false` | `HALO_LATENCY_METER` | `true`: in a network game, your round trip to the host in milliseconds at the top right of the screen, "Ping 45 ms" with four bars: green below 80 ms, yellow below 150, red from 150. The host shows "Max ping", its slowest player's. A player's machine that has heard nothing from the host for two seconds shows "Connection problem". The round trip includes each machine's wait for its next tick, so a LAN reads 15 to 35 ms. Not shown in the menus, after the game, in a co-op cutscene or when the host plays alone. The scoreboard's pings take the same colours, and show the round trips this machine times itself (the host: each player's; a player: their own), so they agree with the meter. Nothing more is sent. Only in config.toml, not in the menus. | | `display.shader_cache` | `true` | `HALO_SHADER_CACHE` | Windows and Linux: keep the GPU programs that the game links in `shader_cache/` in the save root, and load each from there the next time instead of linking it again, which stops the game for a frame on some drivers. `false`: link each program every time. Refer to "Files and folders". | -| `display.mcc_texture_prepare_mb` | `0` | `HALO_MCC_TEXTURE_PREPARE_MB` | Windows and Linux, MCC only: prepare large non-paletted textures during loading within this estimated GPU-storage budget in MiB, capped at 512. Zero disables it. Quality, palette behavior, and Xbox/CE texture caches are unchanged. Prepared textures remain owned by the MCC texture bridge until map unload. | +| `display.shader_prepare` | `false` | `HALO_SHADER_PREPARE` | Windows and Linux: prepare observed shader pairs and bounded opaque/transparent material variants during loading. Records GLSL recipes in `shader_cache/`, including when the driver binary cache is unavailable. Effects outside the pass still prepare on first use. See [renderer preparation](../../docs/render_preparation.md). | +| `display.texture_prepare_mb` | `0` | `HALO_TEXTURE_PREPARE_MB` | Windows and Linux, Xbox/CE maps: load non-paletted textures through the existing cache before gameplay. Conservative budget in MiB, at most 128; zero disables. Does not change texture quality. | +| `display.mcc_texture_prepare_mb` | `0` | `HALO_MCC_TEXTURE_PREPARE_MB` | Windows and Linux, MCC only: prepare large non-paletted textures during loading within this estimated GPU-storage budget in MiB, capped at 512. Zero disables it. Quality, palette behavior, and Xbox/CE texture caches are unchanged. See [renderer preparation](../../docs/render_preparation.md). | | `display.stats_log` | `false` | `HALO_STATS_LOG` | `true`: a line a second in the log with the frame rate, the mode, the map, the renderer and the size of the 3D view (`STATS fps=120.2 mode=Slayer map=bloodgulch gpu="Adreno (TM) 735" res=1068x480`), so a graphics bug's report or two builds compared say which of them was running and at what frame rate. Nothing is drawn and nothing is sent. | | `display.per_pixel_lighting` | `false` | `HALO_PER_PIXEL_LIGHTING` | `false`: the models (characters, weapons, vehicles, scenery) are lit at each vertex and the light is blended between them, as on the Xbox. The light across a curved surface then shows facets, and a point light that passes close lights only the vertices it reaches. `true`: the models are lit at each pixel by the same lights (the ambient light, two distant lights and two point lights), which changes their look. | +| `display.muzzle_lighting` | `false` | `HALO_MUZZLE_LIGHTING` | Optional muzzle illumination for recognized handheld weapons and the stock Warthog and Scorpion guns (wider warm pulses, with independent Scorpion triggers). Up to eight render-owned pulses follow muzzle markers, fade smoothly and use soft world/model falloff with approximate collision occlusion. Independent of projectile lighting; stock flash effects remain unchanged. See `docs/muzzle_lighting.md`. Unavailable on Android; saved values are ignored there. | +| `display.plasma_lighting` | `false` | `HALO_PLASMA_LIGHTING` | Optional projectile lighting for plasma-rifle/pistol bolts, armed plasma grenades, supported Covenant shots, flame streams and rocket flight: authored plasma attachments and up to eight feature-owned rocket flight lights follow the rendered pose and illuminate world surfaces with a feathered diffuse falloff. Lens-flare-only lights become dynamic only during rendering. Up to 128 authored attachments plus eight owned rocket lights and eight owned Covenant lights; excess projectiles retain stock lighting. Flame projectiles are combined per firing owner into the shared eight-slot emitter pool. Requires render interpolation for smooth motion. Preserves authored plasma colours and stock explosion effects; the exact Grunt/Hunter fuel-rod exhaust casts greener flight illumination. Soft-light radius scales are 1.75 for rifle bolts, 2.25 for pistol bolts, 2.75 for charged bolts and 1.75 for authored rocket lights; rockets without authored lights gain a warm radius-1.75 flight light. Model point lights and authored omnidirectional world specular highlights use the same soft falloff (the charged bolt retains its no-specular flag); material reflections and spotlight gels stay stock. No shadows. See `docs/plasma_lighting.md` and `docs/covenant_lighting.md`. Unavailable on Android; saved values are ignored there. | +| `display.jackal_shield_lighting` | `false` | `HALO_JACKAL_SHIELD_LIGHTING` | Soft illumination from visible stock Jackal shields, using their authored colour and rendered shield marker. Damage colours follow the shield animation; smooth activation/collapse. See `docs/covenant_emitter_lighting.md`. Unavailable on Android; saved values are ignored there. | +| `display.fuel_rod_lighting` | `false` | `HALO_FUEL_ROD_LIGHTING` | Green illumination from exposed rods on the stock fuel-rod weapon, held or dropped, and the Hunter's animated cannon. Stock weapon effects remain unchanged. See `docs/covenant_emitter_lighting.md`. Unavailable on Android; saved values are ignored there. | +| `display.ammo_counter_lighting` | `false` | `HALO_AMMO_COUNTER_LIGHTING` | Cool-blue spill and masked screen emission from held Assault Rifle ammo counters in first and third person, including other players and Marines. Both screens share the stronger material emission; the separate first-person spill remains brighter and third-person spill is unchanged. Shares the bounded emitter pool. See `docs/covenant_emitter_lighting.md`. Unavailable on Android; saved values are ignored there. | +| `display.dynamic_lighting_reset` | `true` | `HALO_DYNAMIC_LIGHTING_RESET` | Migration marker, not a menu control. Old configurations reset optional dynamic lighting to OFF and glow intensity to Default once; leave true to preserve subsequent player choices. | +| `display.weapon_glow` | `false` | `HALO_WEAPON_GLOW` | Authored energy-sword and plasma-pistol charge lights use the enhanced falloff, rendered attachment poses and optional occlusion. Stock animation, colours and effects remain authoritative. The menu's Weapon Glow group also controls the existing fuel-rod, AR-counter and Needler settings; the group displays ON if any member is enabled. Old saved dynamic-lighting preferences reset to OFF once. Unavailable on Android. See [emitter additions](../../docs/reading/emitter_expansion.md). | +| `display.plasma_prong_lighting` | `false` | `HALO_PLASMA_PRONG_LIGHTING` | Independent Plasma Prong Lighting toggle. Adds a short, soft forward spill to Plasma Rifle and Plasma Pistol prongs, fading with viewing distance. Shares the eight-light occlusion budget; Weapon Glow does not enable it. Stock flares remain intact. Unavailable on Android. | +| `display.vehicle_lighting` | `false` | `HALO_VEHICLE_LIGHTING` | Enhanced authored Warthog/Scorpion headlights and Covenant running lights, with bounded fallbacks for multiplayer Ghosts and Covenant dropship thrusters. Vehicle collision blocking is always used; stock beam cones remain intact. Exact supported tags and missing-marker limits are described in [emitter additions](../../docs/reading/emitter_expansion.md). Unavailable on Android. | +| `display.world_lighting` | `false` | `HALO_WORLD_LIGHTING` | Soft light from visible overshield/active-camouflage pickups and the authored green teleporter surface. Shares the eight-slot emitter pool. Unlit teleporter bases and netgame flags do not create a light. Unavailable on Android. See [emitter additions](../../docs/reading/emitter_expansion.md). | +| `display.needler_lighting` | `false` | `HALO_NEEDLER_LIGHTING` | Soft pink-purple radial spill from held Needler crystals in first and third person, with enhanced masked needle emission. Nearby hands and housing receive light in every direction; farther downward spill fades to avoid a floor pool. Shares the bounded emitter pool; disabled by default. Unavailable on Android; saved values are ignored there. | +| `display.covenant_shield_lighting` | `false` | `HALO_COVENANT_SHIELD_LIGHTING` | Violet illumination from the stock stationary Covenant shield emitter while its shield is visible. Shares eight bounded render-owned lights with Jackal shields and fuel rods. See `docs/covenant_emitter_lighting.md`. Unavailable on Android; saved values are ignored there. | +| `display.plasma_occlusion` | `false` | `HALO_PLASMA_OCCLUSION` | Optional collision-based visibility for supported projectile, Covenant emitter and Shield Glow lighting; requires one of those lighting options. Up to eight lights use a filtered local visibility grid for world diffuse/specular and model lighting. Structure, scenery and machines block light; coarse edges can leak. Excess lights retain unoccluded soft lighting and fade into occlusion if admitted later. See `docs/plasma_lighting.md`. Unavailable on Android; saved values are ignored there. | | `display.structure_culling` | `31` | `HALO_STRUCTURE_CULLING` | Which tests skip the triangles of the level (its walls, floors and terrain) that the camera cannot see before they are drawn, as bits added together: `1`, triangles outside the view; `2`, groups of triangles that all face away from the camera; `4`, single triangles that face away; `8`, smaller groups, so that more of them are skipped whole; `16`, the rooms nearest the camera first. Each test is conservative: the picture is the same, with fewer triangles drawn. `0`: the original walk, which draws every triangle of each visible room. The console's `structure_culling ` changes it until the game quits, and `debug_structure_culling true` shows what was skipped (red: outside the view, blue: facing away). | -| `display.shield_glow` | `false` | `HALO_SHIELD_GLOW` | `true`: as a unit's energy shield flares (hit, charging, falling), it lights what is around it and itself, as a plasma bolt does, in the shield shader's own color (a Spartan's gold, an Elite's blue), rising and falling with the flare seen on the body. An ordinary dynamic light of the game's, drawn with a light definition the map has (`shield_glow.c`). Up to 8 units near the camera. Video Setup's Extra Effects screen sets it. In a network game, the host's `network.shield_effects` decides, unless it is `players` (each player's own) or the game is co-op (always each player's own). | -| `display.shield_glow_intensity` | `default` | `HALO_SHIELD_GLOW_INTENSITY` | The shield glow's reach and brightness: `default`, or `light_show` (three times as far, and at full strength from a third of the flare: a light is no brighter than full). The units glowing are those near any local player's camera, so each of a split screen's views has the same. Video Setup's Extra Effects screen sets it. In a network game, the host's `network.shield_effects` decides, unless it is `players` (each player's own) or the game is co-op (always each player's own). | -| `display.overshield_effect` | `false` | `HALO_OVERSHIELD_EFFECT` | `true`: the overshield's flare rises up the body from the feet as it charges, with a soft edge (2 seconds, the charge's time from a full shield; 3 from a shield that was down; 2 from any other), then stays lit, whole, for as long as the overshield lasts, its energy moving at 30% of its speed, in its own color (the powerup's, 253, 78, 116), whatever shield color its player chose; the shield's own flares are not drawn over it, and its glow (`display.shield_glow`) rises and stays with it. With `display.viewmodel_shield` it comes up on the first-person arms as the rise reaches them. A hit on it plays what the projectile plays on an Elite's shield (its sound, sparks and light), when the map has that effect and it only shows and sounds. `false`: the overshield as the stock game draws it. Only this machine's drawing and sounds change (`overshield_effect.c`; the rise is a fade in the vertex shader, `d3d8_gl_set_height_fade`). Video Setup's Extra Effects screen sets it. In a network game, the host's `network.shield_effects` decides, unless it is `players` (each player's own) or the game is co-op (always each player's own). | +| `display.shield_glow` | `false` | `HALO_SHIELD_GLOW` | Soft radial light from unit shields, matching the selected Shield Look, authored colour channels and animated overshield layer (green above 200%, pink below). Eight render-owned lights use stable contribution/distance selection, interpolated body poses and smooth release. Shares world/model falloff, coloured specular and optional Light Occlusion. Video Setup > Dynamic Lighting. Online, `network.shield_effects` remains authoritative unless `players` or the game is co-op. See [shield lighting](../../docs/reading/shield_lighting.md). Unavailable on Android; saved values are ignored there. | +| `display.shield_glow_intensity` | `default` | `HALO_SHIELD_GLOW_INTENSITY` | The shield glow's reach and brightness: `default`, or `light_show` (three times as far, and at full strength from a third of the flare: a light is no brighter than full). The units glowing are those near any local player's camera, so each of a split screen's views has the same. Video Setup's Dynamic Lighting screen sets it. In a network game, the host's `network.shield_effects` decides, unless it is `players` or the game is co-op (each player's own). Unavailable on Android; saved values are ignored there. | +| `display.overshield_effect` | `false` | `HALO_OVERSHIELD_EFFECT` | `true`: the overshield's flare rises up the body from the feet as it charges, with a soft edge (2 seconds, the charge's time from a full shield; 3 from a shield that was down; 2 from any other), then stays lit, whole, for as long as the overshield lasts, its energy moving at 30% of its speed, green above 200% total shields (78, 253, 116), reddish-pink through 200% (253, 78, 116); the shield's own flares are not drawn over it. A hit on it plays what the projectile plays on an Elite's shield (its sound, sparks and light), when the map has that effect and it only shows and sounds. `false`: the overshield as the stock game draws it. Only this machine's drawing and sounds change (`overshield_effect.c`; the rise is a fade in the vertex shader, `d3d8_gl_set_height_fade`). Video Setup's Extra Effects screen sets it. Online, the host's `network.shield_effects` decides, unless it is `players` or the game is co-op (each player's own). | | `display.model_detail` | `"stock"` | `HALO_MODEL_DETAIL` | Which level of detail (of up to five) each model is drawn at. The game measures a model by its size in the lines of its 480-line screen, at any resolution, so at 1440 lines a model three times larger than the levels were made for is drawn as the Xbox drew it. `"stock"`: as on the Xbox. `"native"`: measured in the lines of the display (not supersampling's), so more detail is kept at a distance at high resolutions, and small far models that the Xbox left out are drawn. `"highest"`: measured as `"native"` for which models are drawn, and those drawn at their most detailed level. With either, a part that has no geometry at the level chosen draws its most detailed level below that has some, and a level made for a model's inside (one for a size over 1000 pixels, as the top level of a10's cryotubes) is drawn only while the camera is inside the model. Models whose map gives one level (the trees and rocks of b30) do not change. On Android, which draws 480 lines, `"native"` is `"stock"`. | -| `display.reversed_depth` | `true` | `HALO_REVERSED_DEPTH` | Not on Android or in a browser. `true`: the depth buffers hold 32-bit floats, reversed (1 at the near plane, 0 at the far), so that depth is about as precise far away as near. With the Xbox's 24 bits and its near plane of 0.0625 world units, surfaces a few millimetres apart (the light strips on Blood Gulch's base, 0.0016 to 0.013 world units in front of their walls, with no depth bias) are run together past some tens of world units and flicker through each other, which the Xbox's 480 lines hid. The renderer turns the game's depth around (its tests, clears, depth range and polygon offsets), and the vertex programs take the reversed depth from their projection's rows (w's row less z's), not from w - z, which would lose the precision at a distance. A z bias (decals, and lights drawn on a model, such as the Pelican's) keeps the Xbox's 24-bit depth units, added by the vertex programs: a floating-point buffer's polygon offset measures its units by the depth itself, a hundredth of the Xbox's at ten world units, and those lights sank into the hull. With either setting, a z bias's slope term is taken across the game's 480-line pixels, as on the Xbox, not across the display's smaller ones. `false`: 24 bits, as the Xbox's. Read at start. | +| `display.reversed_depth` | `true` | `HALO_REVERSED_DEPTH` | Not on Android or in a browser. `true`: the depth buffers hold 32-bit floats, reversed (1 at the near plane, 0 at the far), improving depth precision at a distance. With the Xbox's 24 bits and its near plane of 0.0625 world units, surfaces a few millimetres apart (the light strips on Blood Gulch's base, 0.0016 to 0.013 world units in front of their walls, with no depth bias) are run together past some tens of world units and flicker through each other, which the Xbox's 480 lines hid. The renderer turns the game's depth around (its tests, clears, depth range and polygon offsets), and the vertex programs take the reversed depth from their projection's rows (w's row less z's), not from w - z, which would lose the precision at a distance. A z bias (decals, and lights drawn on a model, such as the Pelican's) keeps the Xbox's 24-bit depth units, added by the vertex programs: a floating-point buffer's polygon offset measures its units by the depth itself, a hundredth of the Xbox's at ten world units, and those lights sank into the hull. With either setting, a z bias's slope term is taken across the game's 480-line pixels, as on the Xbox, not across the display's smaller ones. `false`: 24 bits, as the Xbox's. Read at start. | | `display.hdr` | `false` | `HALO_HDR` | `true`: the back buffer that the 3D view is drawn into holds half floats (`GL_RGBA16F`) in place of 8 bits a channel, so that the light the game adds up (blended lights, glows, fog, particles) is kept past white in place of being clipped. Before the HUD and the menus, a tone mapping pass brings it back into the display's range (`display.hdr_tone_mapping`). The HUD and the menus do not change. On Android, only with a GPU that draws into half floats (OpenGL ES 3.2, `GL_EXT_color_buffer_half_float` or `GL_EXT_color_buffer_float`); otherwise off, with a line in the log. A change applies from the next frame. Video Setup's GRAPHICS screen sets it (HDR) and `display.hdr_output` (HDR DISPLAY). Refer to "HDR" in "What operates". | | `display.hdr_exposure` | `1.0` | `HALO_HDR_EXPOSURE` | With `display.hdr`, the light of the 3D view is multiplied by this before the tone mapping, from `0.25` to `4.0`. | | `display.hdr_tone_mapping` | `"gt7"` | `HALO_HDR_TONE_MAPPING` | With `display.hdr`, the curve that brings the light into the display's range. `"gt7"`: Polyphony Digital's Gran Turismo 7 tone mapping (`port/third_party/gt7_tone_mapping`, MIT), in Rec.2020 at the light's brightness in nits: each channel along its curve to the display's peak, blended with that curve's brightness at the colour's own hue (ICtCp), whose chroma fades out as the light nears the peak, so that the brightest light goes to white, as on film and as the Xbox's 8 bits clipped it, in place of staying saturated. Without an HDR display, as GT7's SDR (white at 250 nits). Video Setup's Extra Effects screen sets it (TONE CURVE), taking effect from the next frame. `"neutral"`: the picture is as without HDR up to 80% of white, and the light past it rolls off to white in place of being clipped. `"aces"`: the ACES filmic curve (Narkowicz's fit), with more contrast and darker shadows. `"reinhard"`: the extended Reinhard curve on luminance, softer and darker. | @@ -560,8 +617,16 @@ the setting for one start of the game. It has priority over the file. | `audio.voice_volume` | `1.0` | `HALO_VOICE_VOLUME` | The volume of the voices of the other players, `0` to `2`. | | `audio.output_device`, `audio.input_device` | `"default"` | `HALO_AUDIO_OUTPUT_DEVICE`, `HALO_AUDIO_INPUT_DEVICE` | The speakers and the microphone, by the name that Settings > Audio shows, or `"default"` for the device of the system. If the device is not found, the game uses the device of the system. Not on Android. | | `input.mouse_sensitivity` | `1.0` | `HALO_MOUSE_SENSITIVITY` | The multiplier for the mouse aim. | +| `input.gyro_aim` | `"legacy"` | `HALO_GYRO_AIM` | Android: keep saved touch gyro behavior; `"false"` off, `"true"` on, `"zoom"` while zoomed only. | +| `input.gyro_sensitivity_horizontal` | `1.0` | `HALO_GYRO_SENSITIVITY_HORIZONTAL` | Android: gyro yaw multiplier, 0.25–10, in on/zoom mode; independent of swipe. | +| `input.gyro_sensitivity_vertical` | `1.0` | `HALO_GYRO_SENSITIVITY_VERTICAL` | Android: gyro pitch multiplier, 0.25–10, in on/zoom mode. | +| `input.gyro_invert_horizontal` | `false` | `HALO_GYRO_INVERT_HORIZONTAL` | Android: invert gyro yaw in on/zoom mode. | +| `input.gyro_invert_vertical` | `false` | `HALO_GYRO_INVERT_VERTICAL` | Android: invert gyro pitch in on/zoom mode. | | `input.mouse_vertical_sensitivity` | `0.0` | `HALO_MOUSE_VERTICAL_SENSITIVITY` | The multiplier for the vertical mouse aim. `0`: the same as `input.mouse_sensitivity`. | | `input.playstation_kernel_driver` | `false` | `HALO_PLAYSTATION_KERNEL_DRIVER` | Linux: `true` drives a PlayStation controller (DualSense, DualShock 4) through the kernel's driver of it (`hid-playstation` since Linux 5.12, `hid-sony`): its buttons, sticks, triggers and rumble, with no setup, but not its lightbar. `false`: SDL's own driver, which needs access to the controller's `/dev/hidraw` device, as Steam's udev rules give it (`steam-devices`, or Steam installed). Read at start-up. | +| `input.adaptive_triggers` | `false` | `HALO_ADAPTIVE_TRIGGERS` | `true`: a PS5 DualSense's (or DualSense Edge's) triggers feel like the weapon: the physical trigger mapped to fire (R2 by default) has a hold and a click for each kind of weapon (the pistol, the shotgun, the assault rifle, the sniper rifle, the plasma weapons), a kick at each shot, and is free while you reload or switch; it clicks dry when the weapon is empty and locks while a plasma weapon is overheated. The grenade trigger (L2 by default) is light while you zoom and a hair trigger while you have grenades. A trigger mapped to zoom has resistance while zoomed. Only L2/R2 have actuators; other actions leave them free, and firing on another button produces no trigger kick. Pause, menus, death and map/checkpoint changes clear feedback history. Other controllers are never touched. SDL's own driver sends the effects; with `input.playstation_kernel_driver` on Linux they are written to the controller's `/dev/hidraw` device, which needs the same access as SDL's driver (Steam's udev rules), and `debug.txt` says if it is not there. The triggers are let go at exit and when the setting is turned off; after a crash they stay set until the controller reconnects. | +| `input.trigger_strength` | `"normal"` | `HALO_TRIGGER_STRENGTH` | How strong the DualSense's trigger effects are, with `input.adaptive_triggers`: `"light"`, a hair trigger on both triggers (a tiny tick early in the pull and nothing after it); `"normal"`; `"strong"`, every hold and click two steps firmer (never past a full pull that tires) and every kick and buzz too. | +| `input.lightbar` | `"off"` | `HALO_LIGHTBAR` | `"player_color"`: a DualSense's lightbar is your color (your team's in a team game, your armor's otherwise) and its player lights show your split-screen player number. `"off"`: they are left alone; turned off or leaving a player context, the hidraw backend restores blue and clears player lights; SDL restores the original player index and its default lightbar color. SDL cannot recover another application's custom color. | | `input.left_stick_dead_zone` | `-1` | `HALO_LEFT_STICK_DEAD_ZONE` | How far the controller's left stick moves before it moves the player, in percent of its travel (`0` to `50`). Lower for finer control, higher for a worn stick that drifts. `-1`: the game's own (9000 of 32767, about 27%). On Android, the touch controls' stick too. Settings > Gamepads > Stick Dead Zones sets it. | | `input.right_stick_dead_zone` | `-1` | `HALO_RIGHT_STICK_DEAD_ZONE` | The same for the right stick, which turns the view. | | `input.invert_mouse` | `false` | `HALO_MOUSE_INVERT=1` sets `true` | `true`: the vertical mouse aim is inverted. | @@ -572,17 +637,25 @@ the setting for one start of the game. It has priority over the file. | `game.language` | `""` | `HALO_LANGUAGE` | The language of the menus: `ja`, `de`, `fr`, `es` or `it`. Empty: English. | | `game.enhanced_animations` | `true` | `HALO_ENHANCED_ANIMATIONS` | `true`: the player bipeds' grenade throws keep their legs moving, blended by speed and direction (crouched throws stay crouched, throws in the air use the jump's legs), Warthog and Scorpion riders stay seated to throw and let go of the grips to throw and reload, and a player turns with the aim while throwing, as while meleeing, and in the air, as while running (the original froze the body in a jump and kept the aim within its aiming screen about it, so a shot after turning in the air went between the jump's facing and the crosshair). `false`: the original animations, which freeze the legs during a throw and stand a rider up and the body in the air. The turning with the aim (throwing, in the air) moves where shots go, so in a network game every player turns so whatever this says; `false` turns it off only in a game of one machine. Only in config.toml, not in the menus. | | `game.unlock_all_levels` | `false` | `HALO_UNLOCK_ALL_LEVELS` | `true`: a profile created afterward starts with all the campaign levels finished on all the difficulties. `false`: a new profile starts at The Pillar of Autumn, and each level opens when you finish the level before it, as on the Xbox. Existing profiles keep their progress. To start a profile over, type `profile_reset_campaign` in the console. | -| `bots.count` | `0` | `HALO_BOTS` | Computer players (bots) in a local (split screen) Slayer game: `0` to `15` join its lobby with the players, as far as the game has room. Not in system link or internet games. `0`: none, as in the stock game. Refer to "Bots". | -| `bots.skill` | `"normal"` | `HALO_BOT_SKILL` | How well the bots play: `"recruit"`, `"easy"`, `"normal"`, `"heroic"`, `"veteran"` or `"legendary"`: how soon they react, how far and how wide they see, how large their aim error is and how fast it settles, how fast they turn, and how they fight. `"easy"`, `"normal"`, `"heroic"` and `"legendary"` keep their numbers; `"recruit"` is below `"easy"`, and `"veteran"` halfway from `"heroic"` to `"legendary"`. Refer to "Bots". | +| `bots.enhanced` | `false` | `HALO_BOTS_ENHANCED` | Independent enhanced controller, goals, roles, navigation and powerup choices. Read at map load. | +| `bots.network` | `false` | `HALO_BOTS_NETWORK` | Host bots through ordinary player replication. Read when creating the host or applying lobby Bots settings. Enabling reserves 63 free machine IDs until that host closes. | +| `bots.routes` | `"direct"` | `HALO_BOT_ROUTES` | Enhanced bot routes: `direct`, `lanes` or `mixed`; unreadable/unreachable routes fall back to the base pathfinder. | +| `bots.vehicles` | `false` | `HALO_BOT_VEHICLES` | Enhanced ground vehicles, turrets, aircraft and friendly-player boarding through ordinary controls; requires usable authored seats and physics. | +| `bots.thread` | `false` | `HALO_BOT_THREAD` | Optional snapshot path worker for enhanced bots. Read at map load; fixed-tick benchmarks remain synchronous. | +| `android.cheat_menu` | `false` | `HALO_ANDROID_CHEAT_MENU` | Android: show a CHEATS touch button and Options entry during offline gameplay or while hosting co-op/multiplayer. Joining clients cannot use cheats. | +| `bots.count` | `0` | `HALO_BOTS` | Initial computer players: `0` to `63`, subject to capacity. Network hosts automatically replace bots with joining humans and restore them on departures, maintaining the session population target. Local Slayer by default; `bots.enhanced` adds CTF/King. Refer to "Bots". | +| `bots.skill` | `"normal"` | `HALO_BOT_SKILL` | How well the bots play: `"recruit"`, `"easy"`, `"normal"`, `"heroic"`, `"veteran"` or `"legendary"`: how soon they react, how far and how wide they see, how large their aim error is and how fast it settles, how fast they turn. | | `bots.teams` | `"even"` | `HALO_BOT_TEAMS` | In a team game: `"even"` puts the bots on both teams, evening them with the players; `"against"` puts them all on the team the players are not on. | | `paths.data` | `""` | `HALO_DATA_ROOT` | The data root. Refer to "Start the game". | | `paths.saves` | `""` | `HALO_SAVE_ROOT` | The save root. Refer to "Files and folders". | | `paths.logs` | `""` | `HALO_LOG_ROOT` | The folder of `debug.txt`, `bans.txt` and `cheaters.txt`. Empty: the data root. With it, the data root can be read-only (a dedicated server's maps mounted so). | | `paths.custom_maps` | `""` | `HALO_CUSTOM_MAPS_ROOT` | The `custom_maps` folder (Custom Edition maps, with their `bitmaps.map`, `sounds.map` and `loc.map`). Empty: the one in the data root. | -| `game.mcc_campaigns` | `true` | `HALO_MCC_CAMPAIGNS` | Use explicit MCC campaign metadata for discovery, mission titles, authored ordering and progression. In co-op only the host chooses the next mission. Reopen the map list after changing this. | -| `game.mcc_collections` | `true` | `HALO_MCC_COLLECTIONS` | Group MCC packages by the bundled Workshop collection list, including imported packages identified by a sidecar. Reopen the map list after changing this. | -| `game.workshop_maps` | `true` | `HALO_WORKSHOP_MAPS` | Discover installed Halo CE Steam Workshop maps on desktop. Local MCC packages take precedence. Android and web use local packages. | | `paths.steam` | `""` | `HALO_STEAM_ROOT` | A Steam folder or library to check first for subscribed Halo CE Workshop items. Automatic discovery also checks Windows registry installations; Linux's `STEAM_COMPAT_CLIENT_INSTALL_PATH`, `$XDG_DATA_HOME/Steam` and home-folder locations; and their library lists. Empty: automatic discovery only. | +| `game.workshop_maps` | `false` | `HALO_WORKSHOP_MAPS` | Discover installed Halo CE Steam Workshop maps on desktop. Local MCC packages take precedence. Android and web use local packages. | +| `game.mcc_collections` | `false` | `HALO_MCC_COLLECTIONS` | Group MCC packages by the bundled Workshop collection list, including imported packages identified by a sidecar. Reopen the map list after changing this. | +| `game.mcc_campaigns` | `false` | `HALO_MCC_CAMPAIGNS` | Use explicit MCC campaign metadata for discovery, mission titles, authored ordering and progression. In co-op only the host chooses the next mission. Reopen the map list after changing this. | +| `network.session_compatibility` | `"opence_crossplay"` | `HALO_SESSION_COMPATIBILITY` | Host mode: CROSSPLAY uses OpenCE protocol 43 for Xbox, Custom Edition and MCC maps, with multiplayer third-person disabled. GULCHCE ONLY (`gulchce_third_person`) enables the camera policy and requires GulchCE camera protocol 32744. Fixed when the lobby opens. | +| `network.camera_policy` | `"player_choice"` | `HALO_CAMERA_POLICY` | Host rule for new matches: Create Game > Server Setup > Session Options > CAMERA POLICY offers PLAYER CHOICE, FORCED ON and FORCED OFF. Applies to local matches, LAN/system link, internet multiplayer and co-op, including late joiners. Forced On retains scoping, collision and stock vehicle/death/cinematic overrides. Locked matches block N and show CONTROLLED BY HOST in Video Setup; personal preferences return after leaving. The policy stays fixed during play and carries across rounds and co-op levels. Available in GulchCE-only sessions (camera protocol 32744); Crossplay forces this feature off. | | `network.address` | `""` | `HALO_NET_ADDRESS` | The IPv4 address of this machine for system link. Refer to "Play on one computer". | | `network.broadcast` | `""` | `HALO_NET_BROADCAST` | IPv4 addresses, with commas between them, that get the broadcasts of the game. Empty: 255.255.255.255. | | `network.online` | `true` | `HALO_NET_ONLINE` | `true`: internet play. `false`: system link on the local network only. | @@ -621,6 +694,7 @@ the setting for one start of the game. It has priority over the file. | `network.map_seed` | `true` | `HALO_NET_MAP_SEED` | When you play in the game of another machine: help send its map to players who join without it. HELP SEND MAPS in Settings > Network Setup > Map Sharing. | | `network.map_seed_upload` | `256` | `HALO_NET_MAP_SEED_UPLOAD` | When you play in the game of another machine: the most kilobytes per second that the game sends of maps to other players (`16` to `10240`, 10 MB/s). UPLOAD LIMIT in Settings > Network Setup > Map Sharing. | | `network.map_download` | `true` | `HALO_NET_MAP_DOWNLOAD` | DOWNLOAD MAPS in Settings > Network Setup > Map Sharing. CE downloads from players as before; MCC permits a host offer and asks before transferring files. Off: CE leaves a missing-map game; MCC offers manual/Workshop installation and cancellation. | +| `network.mcc_map_share` | `false` | `HALO_NET_MCC_MAP_SHARE` | SHARE MCC PACKAGES in Settings > Network Setup > Map Sharing. Host-only, explicit-list sharing of eligible local or Workshop packages; requires a gameplay fingerprint and maker in `mcc_share.txt`. Includes used package resources and recognized metadata/previews. The joiner needs Download Maps enabled and must accept the offer. See "MCC package sharing" for implementation status and limits. | | `network.coop_public` | `false` | `HALO_NET_COOP_PUBLIC` | `true`: an online co-op game (Create Game > Internet, a SINGLEPLAYER map) starts as PUBLIC. `false`: it starts as PRIVATE. LISTING in co-op's Server Setup writes its choice here. Refer to "Server browser". | | `network.coop_team_wipe` | `"auto"` | `HALO_NET_COOP_TEAM_WIPE` | TEAM WIPE in Server Setup > Co-op Options: `"auto"` reverts the checkpoint in a PRIVATE game and only respawns the team in a PUBLIC game (a dedicated server's: `server.public` with internet play). `"revert"` or `"respawn"` overrides visibility; a password does not make a PUBLIC game private. Changed players/machine assignments fall back to position-only respawn with a host diagnostic. A missing checkpoint also uses position-only respawn. Scripted mission failures keep their existing revert behavior. | | `network.brokers_file` | `"brokers.txt"` | `HALO_NET_BROKERS_FILE` | The file of the public MQTT brokers that let the machines of an invite find each other, and that carry the listings of the server browser: next to `config.toml`, unless a full path. One `host:port` on each line, up to 4; `#` starts a comment. | @@ -708,7 +782,7 @@ the setting for one start of the game. It has priority over the file. | `debug.gpu_stats`, `debug.gpu_trace_frame`, `debug.gpu_trace_constants`, `debug.gpu_dump_shaders`, `debug.texture_dump_directory`, `debug.texture_log`, `debug.gl_debug`, `debug.texture_no_cache` | off | `HALO_GPU_STATS`, `HALO_GPU_TRACE`, `HALO_GPU_TRACE_CONSTANTS`, `HALO_GPU_DUMP_SHADERS`, `HALO_TEXTURE_DUMP`, `HALO_TEXTURE_LOG`, `HALO_GL_DEBUG`, `HALO_TEXTURE_NO_CACHE` | Tools to find problems in the graphics: counts for each frame, all the GL state of one frame, the GLSL code, the textures. | | `debug.menu_open` | `""` | `HALO_MENU_OPEN` | Start on this screen of the menus (`main_menu/settings_select/...`, as `port/assets/menus` names it), a player profile being edited, to look at it. | | `debug.gpu_skip_vertex_shaders`, `debug.gpu_debug_expression`, `debug.gpu_debug_flat`, `debug.gpu_debug_texture0` | off | `HALO_GPU_SKIP_VS`, `HALO_GPU_DEBUG_EXPR`, `HALO_GPU_DEBUG_FLAT`, `HALO_GPU_DEBUG_T0` | Tools to find problems in the graphics: skip the draws of a vertex shader, or replace the output of all pixel shaders with a GLSL expression (for example `t0.rgb`). | -| `debug.network_test`, `debug.network_test_start`, `debug.network_test_kill`, `debug.network_test_score`, `debug.network_test_shoot`, `debug.network_test_vehicle`, `debug.network_test_pickup`, `debug.network_test_pickup_weapon`, `debug.network_test_chat`, `debug.network_test_name`, `debug.network_test_public`, `debug.test_input` | off | `HALO_NETWORK_TEST`, `HALO_NETWORK_TEST_START`, `HALO_NETWORK_TEST_KILL`, `HALO_NETWORK_TEST_SCORE`, `HALO_NETWORK_TEST_SHOOT`, `HALO_NETWORK_TEST_VEHICLE`, `HALO_NETWORK_TEST_PICKUP`, `HALO_NETWORK_TEST_PICKUP_WEAPON`, `HALO_NETWORK_TEST_CHAT`, `HALO_NETWORK_TEST_NAME`, `HALO_NETWORK_TEST_PUBLIC`, `HALO_TEST_INPUT` | Automatic tests of system link, or (`log`) a log of the game one machine plays (`game/network_test.c`). Refer to `NETCODE.md`. `debug.test_input = "menu:a down down a"` presses menu buttons one a second (`a`, `b`, `x`, `y`, `up`, `down`, `left`, `right`, `start`, `back` or `wait`), for testing the menus. | +| `debug.network_test`, `debug.network_test_start`, `debug.network_test_kill`, `debug.network_test_score`, `debug.network_test_shoot`, `debug.network_test_vehicle`, `debug.network_test_pickup`, `debug.network_test_pickup_weapon`, `debug.network_test_chat`, `debug.network_test_name`, `debug.network_test_public`, `debug.test_input` | off | `HALO_NETWORK_TEST`, `HALO_NETWORK_TEST_START`, `HALO_NETWORK_TEST_KILL`, `HALO_NETWORK_TEST_SCORE`, `HALO_NETWORK_TEST_SHOOT`, `HALO_NETWORK_TEST_VEHICLE`, `HALO_NETWORK_TEST_PICKUP`, `HALO_NETWORK_TEST_PICKUP_WEAPON`, `HALO_NETWORK_TEST_CHAT`, `HALO_NETWORK_TEST_NAME`, `HALO_NETWORK_TEST_PUBLIC`, `HALO_TEST_INPUT` | Automatic tests of system link, or (`log`) a log of the game one machine plays (`game/network_test.c`). Refer to `NETCODE.md`. `debug.test_input = "menu:a down down a"` presses menu buttons one a second (`a`, `b`, `x`, `y`, `up`, `down`, `left`, `right`, `start`, `back` or `wait`), for testing the menus. `debug.test_input = "legs:0"` repeats a 32-second downward-looking sequence of standing, forward/backward walking, strafing, crouch-walking, jumping and turning for mesh inspection. | | `debug.virtual_gamepads`, `debug.virtual_gamepad_script` | `0`, empty | `HALO_VIRTUAL_GAMEPADS`, `HALO_VIRTUAL_GAMEPAD_SCRIPT` | Desktop: attach this many SDL virtual gamepads (`0` to `4`), which the game takes for gamepads plugged in, and press their buttons from a script of ` ` entries separated by semicolons: the seconds from when the network lobby first opens, the pad `1` to `4` (`0`: the keyboard, whose `a` is SPACE and `start` Enter), and a button (`a`, `b`, `x`, `y`, `start`, `back`, `up`, `down`, `left`, `right`, `lb`, `rb`, `lt`, `rt`), `walk` (the sticks move from then on) or `still`. For testing split screen without four controllers, for example `"3 2 start; 6 2 a; 8 0 a; 10 1 a; 11 1 a; 14 0 start"` with `debug.network_test = "host:bloodgulch"`. | | `debug.network_test_cues`, `debug.network_test_cue_players` | none, `1` | `HALO_NETWORK_TEST_CUES`, `HALO_NETWORK_TEST_CUE_PLAYERS` | Console lines a test runs at their seconds, from the first tick that many players are in (`" \|..."`; not on the web). | | `debug.bot_trace` | `0` | `HALO_BOT_TRACE` | Every this many seconds, each bot's state is written to the log: where it is and where it goes, its path, its target and its weapon. `0`: never. | @@ -719,7 +793,7 @@ the setting for one start of the game. It has priority over the file. | `debug.riding_enclosure_grace_ticks` | `4` | `HALO_RIDING_ENCLOSURE_GRACE_TICKS` | Calibration of `network.vehicle_riding`: how many player ticks in a row a player standing inside an enclosed vehicle (a ceiling within a jump and the vehicle's own floor under them) may miss that test while sliding about before the vehicle counts as open again, `0` to `30`; a fraction is cut off, a value that is not a number is `4`. Taken when a map or a saved game loads; in a network game a client uses the host's value. | | `debug.voice_test` | `false` | `HALO_VOICE_TEST` | Automatic tests of voice chat: a tone replaces the microphone, and each voice that the game hears is written to the log once each second. | | `debug.telnet_console`, `debug.telnet_console_port` | `false`, `2323` | `HALO_TELNET_CONSOLE`, `HALO_TELNET_CONSOLE_PORT` | The game listens on 127.0.0.1, on this port, for a script console (connect with telnet). The console has no password, so only this computer can reach it. | -| `debug.profile_record`, `debug.profile_record_when`, `debug.profile_memory` | `false`, `"start"`, `256` | `HALO_PROFILE_RECORD`, `HALO_PROFILE_RECORD_WHEN`, `HALO_PROFILE_MEMORY` | Profiling builds only (`configure.py --profile`). Record without a command; `"start"` records from the first frame until the first map change, `"game"` records each game outside the main menu. Memory is 4–1024 MB. Numbered `profile__.part.json` files remain in `profiles/` after recording. Refer to "Profiling builds" in the main README. | +| `debug.profile_record`, `debug.profile_record_when`, `debug.profile_memory` | `false`, `"start"`, `256` | `HALO_PROFILE_RECORD`, `HALO_PROFILE_RECORD_WHEN`, `HALO_PROFILE_MEMORY` | Profiling builds only (`configure.py --profile`). Record without a command; `"start"` records from the first frame until the first map change, `"game"` records each game outside the main menu. Memory is 4–1024 MB. Numbered `profile__.part.json` files remain in `profiles/` after recording. Refer to "Profiling builds" in the main README. | With Mesa drivers, the game sends its GL calls through the GL thread of @@ -742,9 +816,12 @@ see [the network agreement](NETCODE.md#opence-network-agreement). ## Updates -The builds from GitHub Actions (refer to the main [README](../../README.md#download)) -can update themselves. At start-up, the game asks GitHub for the latest -release. The game does not wait for the answer. If the latest release is not +The builds from GitHub Actions (refer to the main [README](../../README.md#how-do-i-download-a-build)) +can update themselves. GulchCE checks only releases from +[`chestahh/GulchCE`](https://github.com/chestahh/GulchCE/releases), using its +own Build workflow run numbers and `build-` tags. OpenCE release +numbers are not compared and OpenCE builds are not downloaded. At start-up, +the game asks GitHub for the latest GulchCE release. The game does not wait for the answer. If the latest release is not newer, the game does nothing. If the latest release is newer, the game asks: "Do you want to update?" @@ -827,6 +904,23 @@ the world (such as `rasterizer_wireframe`). Refer to `NETCODE.md`. The frame rate shows at the bottom right of the screen. It is the mean over half a second. +## Dynamic lighting + +Video Setup's DYNAMIC LIGHTING submenu controls projectile lights, muzzle-flash +lights, Jackal shields, Covenant stationary shields, held fuel rod glow, AR +counter glow, Needler glow, light occlusion, Shield Glow and its intensity. +All lighting toggles default to OFF; Glow Intensity defaults to DEFAULT. +OK saves and applies this screen's changes; Cancel leaves them unchanged. +Defaults restores those values, applied when you choose OK. +Light occlusion affects enabled projectile and emitter lights; it does not +enable them. Muzzle lights always use collision blocking, including the +Warthog and Scorpion chassis, independently of the Light Occlusion toggle. +Projectile, weapon and Covenant-emitter settings are local visual choices. +Shield Glow and its intensity retain the host's `network.shield_effects` policy; +their saved local choices apply offline or when the host selects PLAYERS' OWN. +Animated Overshield remains independent in Extra Effects and follows the same +host policy. + ## Field of view Video Setup's FOV AND VIEWMODELS screen sets the field of view of the @@ -847,16 +941,6 @@ keeps the stock view. `config.toml` takes any angle from 20 to 150. - By default the weapon keeps its stock view when the world is wider: arms and a gun right against the camera stretch at a wide angle. -LEGS (`display.first_person_legs`) draws your own body in first person -from the waist down, so you see your legs when you look down, walking, -running and crouching as everyone else sees them. It is the body others -see, posed as they see it: the upper body is folded away, and the body is -set back behind the eye as far as keeps the open waist below the view -(the way Halo 2 keeps its first-person body's open top out of sight), more -the further down you look. It is drawn with the world's camera, so it keeps -its place and size at any field of view. Hit boxes, markers and everything -the game does with the body are unchanged. - Only this machine's view changes. Nothing the machines send each other changes, so players with different settings play together. @@ -1486,7 +1570,7 @@ Only machines with the invite can find the game: leaving. So that every player can be named, the host trims the spaces around a name and removes characters that draw as nothing. A - letter with a mark is typed as the plain letter (`ban jose` for "José"). + letter with a mark is typed as the plain letter (`ban jose` for "José"). A name with nothing left to type becomes "Player", and a name that another player already has gets a number ("Player 2"). The game refuses a profile name that is blank, and a multiplayer game refuses a profile whose name was @@ -1514,8 +1598,9 @@ The game can ask the router to forward the port (UPnP, other machine. - The forward has a duration of one hour. The game makes it longer while it operates. When the game stops normally, it removes the forward. It - does not remove the forward after a crash, or if a request to the router - is still under way 3 seconds after the game starts to stop. Some routers only make forwards without a duration. + waits for its request worker before removing the forward; a router request + already in progress can delay exit. It does not remove the forward after + a crash. Some routers only make forwards without a duration. - When the game finds the router, it removes the forwards to this machine that have the description "Halo internet play" and that no copy of the game uses now (forwards that a copy of the game did not remove). @@ -1829,7 +1914,7 @@ saved with their syntax is not taken; the one before it is kept. | High-res text | The menus' and HUD's text is drawn with Overpass (`port/assets/fonts`, SIL Open Font License) in place of the maps' bitmap fonts, which are Interstate. `src/text_hires.c` rasterizes each glyph with stb_truetype (`port/third_party/stb`) at the resolution the game draws at, into an atlas that a placeholder bitmap of the game stands for. The game lays the text out from its font tags as before: each font is as tall as its tag's capitals, and narrowed where the tag's letters are narrower than the Xbox maps' (the fonts of a Custom Edition `loc.map`), so that its letters do not run into each other. The menus' titles (the screens' headers and the main menu's items) are pictures of text in the maps, so they are drawn as the high-res HUD is: `tools/title_assets.py` sets each one again in OpenCE, Roger White's public-domain Newtown respaced to match the maps' commercial title typeface (`tools/title_font.py`), at 4x the bitmap's size over its own plate or glow, each letter placed where the map's letter is, in `port/assets/titles`. The postgame carnage report's title is set over a hand-made SVG redraw of its panel (`port/assets/titles/svg`) instead. The A, B, X and Y button icons beside the menus' key labels and in their text ("Press A to Join") are drawn from hand-made SVG redraws at 8x the size of the maps' bitmaps (`port/assets/buttons`, made by `tools/button_assets.py`), in the same sizes and places. `display.high_res_text = false` turns it off. | | Anti-aliasing | Off unless `display.anti_aliasing` is set (`src/d3d8_gl.c`, `src/xgpu_post.c`). FXAA (written in the port) and SMAA (`port/third_party/smaa`, MIT licensed, at its HIGH preset, compiled as GLSL) are passes over the 3D view of each window, after the lens flares and before the HUD and the menus (`render/render.c`). Their programs are built when the setting is chosen. Supersampling draws the render targets the size of the screen at two times the resolution in each direction, and the display blit scales them down. Multisampling draws the back buffer and its depth buffer into multisampled renderbuffers, and with them any target that is drawn together with one of them (a mirror's view, in the secondary target with the back buffer's depth buffer), so that the attachments of a framebuffer are all multisampled or none is. A target's pixels are resolved into its texture before something reads the texture (as a texture, or at the display blit). Visibility tests count samples, divided by the samples of a pixel. An alpha-tested surface (foliage, grates) covers the samples of a pixel in proportion to its alpha past the reference (`gl_SampleMask`, not on Android). | | HDR | Off unless `display.hdr` is set (`src/d3d8_gl.c`, `src/xgpu_post.c`). The back buffer's texture, and its multisampled renderbuffer, is `GL_RGBA16F` (`GL_HALF_FLOAT` on Android), with the same `GL_DEPTH24_STENCIL8` depth buffer. The game's pixel shaders give colours from 0 to 1, as the NV2A's register combiners did, so the light past white comes from blending, which a floating-point target does not clamp. The tone mapping pass is a pass over the 3D view of each window, before the anti-aliasing (`render/render.c`): it takes each pixel from gamma 2.2 to linear light, multiplies it by `display.hdr_exposure`, applies the curve, and returns to gamma 2.2. It writes the colour only, since the game keeps its own data in the alpha. The display blit becomes a draw that clamps to 1, or, in a floating-point window, gives scRGB (linear light, 1 at the display's SDR white, which SDL reports with the headroom). The settings are read between frames; a change of `display.hdr` makes the back buffer again in the other format. Extra Effects' HDR CALIBRATION, there with a floating-point window on an HDR display, sets the peak and paper white by eye (`game/menu_functions.c`'s "port hdr calibration"): while its screen is drawn, the display takes the values its rows show, and after the display blit a program fills rectangles and rings of the window in scRGB, over its menus. For the peak, a square at the peak shown with a ring in it at 10000 nits, which disappears into the square once the square is as bright as the display goes; for paper white, a grey scale up to white, beside a white square with a ring at the peak. OK writes the values, Cancel goes back to the settings' own. | -| Sound | Xbox DirectSound on SDL3 audio (`src/dsound_sdl.c`): PCM and Xbox ADPCM, mixed at 48 kHz in stereo or 5.1, with volume, pitch, mix bins, distance, pan, occlusion and obstruction, and the Doppler effect of the velocities that the game gives the sounds (a Banshee's pitch falls as it passes), optionally including positioned stereo sources (`audio.stereo_doppler`, off by default). A sound the game cuts off (each shot of a rapid-fire weapon cuts off the last) fades out over 5 ms rather than stopping dead, which clicked. The [Xbox audio walkthrough](../../docs/reading/xbox_audio.md) explains the measured HRTF, 24 kHz reverb, level handling and remaining differences (including unimplemented cones). On 5.1 the game gets the AC-3 speaker setting of the Xbox and sends its 2D sounds to the center and back speakers, 3D sounds use HRTF and share the front and back pairs, and the reverb plays from the front and back pairs. The game sends nothing to the LFE channel. | +| Sound | Xbox DirectSound on SDL3 audio (`src/dsound_sdl.c`): PCM and Xbox ADPCM, mixed at 48 kHz in stereo or 5.1, with volume, pitch, mix bins, distance, pan, occlusion and obstruction, and the Doppler effect of the velocities that the game gives the sounds (a Banshee's pitch falls as it passes), optionally including positioned stereo sources (`audio.stereo_doppler`, off by default). The loading screen's four pitched monk-chant buffers play through the front pair under `audio.volume` and `audio.effects_volume`, and stop when loading ends. A sound the game cuts off (each shot of a rapid-fire weapon cuts off the last) fades out over 5 ms rather than stopping dead, which clicked. The [Xbox audio walkthrough](../../docs/reading/xbox_audio.md) explains the measured HRTF, 24 kHz reverb, level handling and remaining differences (including unimplemented cones). On 5.1 the game gets the AC-3 speaker setting of the Xbox and sends its 2D sounds to the center and back speakers, 3D sounds use HRTF and share the front and back pairs, and the reverb plays from the front and back pairs. The game sends nothing to the LFE channel. | | Input | XInput on SDL3 (`src/xinput_sdl.c`): keyboard, mouse, gamepads with rumble, and the debug keyboard for the console. | | Files | The Win32 file functions and the MSVC file functions on POSIX, with the translation of Xbox paths. | | Threads | Threads, events, mutexes, critical sections, interlocked operations and alertable waits. | @@ -1931,10 +2016,11 @@ Other changes: | `scenario/scenario.c` | The BSP connection tables have names, not MSVC offsets. | | `rasterizer/xbox/rasterizer_xbox_environment_fog.c` | A local pointer gets its value from the file-scope array with the same name. | | `game/player_control.c` | The mouse aims the player on controller 1 directly. | +| `game/player_control.c` | `dualsense_game_update` (`game/dualsense_game.c`) runs after local input, including menus and dead players, and requests feedback from the weapon, physical action mapping and gameplay state. Map initialization/unload calls `dualsense_game_reset`; the saved-game before-load callback resets checkpoint history too. See the [DualSense walkthrough](../../docs/reading/dualsense.md). | | `sound/game_sound.c` | The game calculates the obstruction of each sound one time for each tick, not for each frame. | | `effects/player_effects.c` | A camera shake or impulse is drawn as the first frame after a tick made it by every frame until the next tick, as the Xbox drew it for the tick: its full scale showed only on that first frame, an eighth of the tick at 240 frames a second, so firing shook the view a fraction as much, and the assault rifle's short kick hardly at all. | -| `sound/sound_manager.c`, `camera/observer.c`, `camera/director.c` | The listener's velocity, which the Doppler effect takes, is the game's velocity for the camera's position as if it were fixed to the unit the camera follows (`director_get_followed_unit`, `object_get_point_velocity`), as the sounds on that unit get theirs, so that they cancel exactly, from a chase camera too, even through a network client's corrections and a turret's swing, and swinging the camera round adds nothing. With no such unit (a cinematic's camera, a flying one) it is measured from how far the focus moves from one tick to the next (`listener_measure_velocity`, `observer_get_focus_position`), and none across a jump of more than 10 world units a tick. The observer's velocity, which the game gave, is a tick's motion divided by a frame's time on the native ports, several times too fast at a high frame rate, and zero while a cinematic forces the camera, so that sounds moving with the camera rose in pitch. | -| `sound/sound_manager.c`, `sound/sound_dsound_xbox.c` | A stereo sound in the world, panned towards where it is, is shifted by the Doppler effect as a mono one is: the game gives the mixer how fast it comes towards the listener (`dsound_port_set_channel_stereo_position`). The Xbox played stereo sounds flat; panned, without it, a Pelican's wind held its pitch while its engines' changed. The mixer applies it only with `audio.stereo_doppler`, off by default. | +| `sound/sound_manager.c`, `camera/observer.c`, `camera/director.c` | The listener's velocity, which the Doppler effect takes, is the game's velocity for the camera's position as if it were fixed to the unit the camera follows (`director_get_followed_unit`, `object_get_point_velocity`), as the sounds on that unit get theirs, so that they cancel exactly, from a chase camera too, even through a network client's corrections and a turret's swing, and swinging the camera round adds nothing. With no such unit (a cinematic's camera, a flying one) it is measured from how far the focus moves from one tick to the next (`listener_measure_velocity`, `observer_get_focus_position`), with explicit resets on camera cuts, map changes and saved-game restoration, listener loss or reuse, and a fallback for jumps of 10 world units a tick or more. The observer's velocity, which the game gave, is a tick's motion divided by a frame's time on the native ports, several times too fast at a high frame rate, and zero while a cinematic forces the camera, so that sounds moving with the camera rose in pitch. | +| `sound/sound_manager.c`, `sound/sound_dsound_xbox.c` | With `audio.stereo_doppler` enabled (off by default), a positioned stereo source is shifted by Doppler: the game gives the mixer how fast it comes towards the listener (`dsound_port_set_channel_stereo_position`). The reconstructed Xbox build routes stereo sources through 2D channels without motion Doppler; authored pitch still applies. See [Doppler audio](../../docs/reading/audio_doppler.md) for the evidence and reading route. | | `sound/game_sound.c`, `objects/objects.c` | A sound on an object moves as the point it is attached to does, with the spin of the object it rides (`object_get_point_velocity`), not only as the object's centre does, for the Doppler effect. The listener's velocity has the spin in it: without the sounds' too, a vehicle's own engine rose and fell in pitch for whoever rode it as it turned. | | `sound/sound_manager.c` | A track of a looping sound that is gone stops, even in the millisecond it started (`refresh_sound`). The Xbox never drew three frames in one millisecond; the port can (the null renderer, no frame limit), and then read the deleted looping sound and crashed. | | `cseries/errors.c` | `debug.txt` stays open between lines. A line that is the same as the line before it is counted, not written again (`last line repeated N times`). At 64 MB, `debug.txt` becomes `debug.old.txt` and a new `debug.txt` starts. | @@ -1961,15 +2047,13 @@ Other changes: | `models/models.c` | A model's size, which chooses its level of detail and whether it is drawn, is scaled as `display.model_detail` says (`halo_model_detail_scale`, `src/d3d8_gl.c`), and each permutation draws the level `game/model_detail.c` chooses from the model's (stock: the model's). | | `interface/hud.c` | In multiplayer, players' names are drawn above their heads (`display.player_names`, `display.player_name_scale`). | | `text/draw_string.c`, `interface/terminal.c`, `interface/virtual_keyboard.c` | Streamer mode's words are hidden in every string drawn or measured (`game/text_filter.c`), but in the console's line and the virtual keyboard's text being typed. | -| `objects/widgets/lightning.c` | A lightning's bolt keeps its shape through the frames of a tick and takes a new one with the next, as on the Xbox, which drew a frame a tick: its random offsets (its markers', its points' jitter, its texture's) were drawn each frame, so at high frame rates it took a new shape every frame and flickered several times as fast (the light bridges' lightning in Assault on the Control Room, 343 Guilty Spark's tendrils). The later frames of a tick draw it from the local random seed the tick's first started from, in each window of a split screen, and leave the seed as they found it. | -| `objects/widgets/flags.c` | A flag's cloth steps a tick at a time, as on the Xbox, not every frame (eight steps a tick at 240 frames a second held it eight times as stiff), and is drawn as far from where the frame that stepped it hung it as its first attachment marker has moved since, so that it stays on a running carrier's pole. | +| `objects/widgets/lightning.c` | A lightning's bolt keeps its shape through the frames of a tick and takes a new one with the next, as on the Xbox, which drew a frame a tick: its random offsets (its markers', its points' jitter, its texture's) were drawn each frame, so at high frame rates it took a new shape every frame and flickered several times as fast (the light bridges' lightning in Assault on the Control Room, 343 Guilty Spark's tendrils). The later frames of a tick draw it from the local random seed the tick's first started from, in each window of a split screen, and leave the seed as they found it. Seeds are cleared on map initialization, unload and saved-state restoration. | | `rasterizer/rasterizer_text.c`, `text/draw_string.c` | Text is drawn from an atlas of the fonts' glyphs, rasterized at the resolution the game draws at (`src/text_hires.c`), when the font has every character of the string. Text can be drawn scaled about a point (`rasterizer_text_set_scale`), as the players' names are. Each glyph's advance is centred on the font tag character's, so the layout is the same, and a glyph is cut at a text box only where the font tag's character visibly was. | -| `interface/first_person_weapons.c` | The first-person hands are drawn with the unit's shield modifier shader, as its body is (`display.viewmodel_shield`). | -| `render/render_objects.c`, `objects/objects.c` | In first person, your own body is drawn from the waist down with the pose `first_person_legs.c` makes (`display.first_person_legs`); the waist it found and the mesh `object_mesh.c` read are forgotten on a new map. | +| `render/render_objects.c`, `rasterizer/xbox/rasterizer_xbox_plasma_energy.c`, `items/projectiles.c` | An overshield as `overshield_effect.c` draws it (`display.overshield_effect`): in its own color, its intensity full, its energy slower, faded above the height it has risen to; a hit on it plays the projectile's effect for an Elite's energy shield in place of its own (only the effect: the projectile's response is its own). | +| `interface/first_person_weapons.c`, `rasterizer/xbox/rasterizer_xbox_plasma_energy.c` | The hands are drawn with the unit's shield flare (`display.viewmodel_shield`, `viewmodel_shield.c`), which stands off them by at most a share of the view: the plasma offset of a flare drawn with the hands' values is limited, any other its own. | +| `render/render_objects.c`, `objects/objects.c`, `models/models.c` | The local player's own body is drawn in its first-person view with the legs' pose and feature-owned triangle buffers (`display.first_person_legs`, `first_person_legs.c`), without its widgets and children; a map's load and unload forget the legs found. | +| `objects/widgets/flags.c` | A flag's cloth steps a tick at a time, as on the Xbox, not every frame (eight steps a tick at 240 frames a second held it eight times as stiff), and is drawn as far from where the frame that stepped it hung it as its first attachment marker has moved since, so that it stays on a running carrier's pole. | | `render/render_objects.c` | An object's shadow map is centered where the frame draws the object between the ticks (`display.interpolation`, `render_interpolation_object_point`), as its model is drawn into the map, not where the tick left it: a fast vehicle (a Ghost) stood up to a tick's travel off its map's center, and the map's edge and corner fade cut its shadow's trailing side, flickering. | -| `objects/object_lights.c` | Glows the port lights itself (`shield_glow.c`): dynamic lights attached to an object's node, colored and sized each frame by their maker, drawn with a light definition the map has. | -| `render/render_objects.c`, `interface/first_person_weapons.c`, `rasterizer/xbox/rasterizer_xbox_plasma_energy.c`, `items/projectiles.c` | An overshield as `overshield_effect.c` draws it (`display.overshield_effect`): in its own color, its intensity full, its energy slower, faded above the height it has risen to; a hit on it plays the projectile's effect for an Elite's energy shield in place of its own (only the effect: the projectile's response is its own). | -| `render/render_objects.c`, `interface/first_person_weapons.c`, `rasterizer/xbox/rasterizer_xbox_plasma_energy.c` | A local player's shield plasma is drawn in the chosen armor color (`display.shield_color`, `shield_color.c`), on the body and on the first-person arms. | | `rasterizer/xbox/rasterizer_xbox_text.c`, `rasterizer/rasterizer_text.c` | The characters of a string are one draw, not a draw each (and a second for the drop shadow). The batch is drawn early before a character is cached and before the high-res glyph atlas starts over (`src/text_hires.c`). | | `rasterizer/xbox/rasterizer_xbox_decals.c` | Decals drawn one after another with the same blend function and bitmap are one draw, with each decal's color in its vertices, not a draw each: a long fight leaves hundreds in view. Within a run of decals whose blend functions commute (multiply, add, min, max, reverse subtract), they are drawn by bitmap, so more of them share a draw. | | `rasterizer/xbox/rasterizer_xbox_widgets.c`, `objects/widgets/light_volumes.c` | A light volume's sprites (a plasma bolt's glow, a couple of hundred) are one draw. | @@ -1977,9 +2061,10 @@ Other changes: | `objects/object_lights.c` | A flashlight not on a first-person weapon (your own with no weapon in hand, as another player's in a match) shines from the marker on the pose the frame draws (`render_interpolation.c`), not from where the tick left it, which stepped at 30 a second. | | `structures/structure_render.c` | The structure's visible surfaces are put in order by a radix sort, not `qsort_4byte`: the same order. | | `cache/cache_files.c`, `networking/network_client_manager.c`, `networking/network_server_manager.c`, `networking/network_server_message_handler.c`, `main/main.c`, `interface/interface.c` | Map sharing (`game/map_share.c`): a client that does not have the game's Custom Edition map asks the host for it instead of leaving, is not given time to precache it until it has it, and adds its players to a game in progress only then; the host gives the game's map its own name and its version (its hash's start), takes the requests from any machine in the game, lobby too, and does not drop a machine that downloads; the transfers run each frame, and their progress is drawn over the screen. | +| `cache/cache_files.c`, `cache/cache_files_windows.c`, `networking/network_server_message_handler.c` | MCC package sharing (`game/mcc_share.c`): a package being fetched from the host is taken as present and not precached until it is there, and the host's lobby takes the sharing requests of the machines that joined (from their streams alone, as map sharing's). Everything else of it is in the MCC modules and in four one-line hooks in `game/map_share.c`'s counters (the players held, the machine downloading) and per-frame and render calls, so that the existing holds apply. | | `cutscene/cinematics.c` | A scenario's titles (some Custom Edition maps show their name for the whole game) are not drawn over a menu, as the letterbox is not: the screen's overlays are drawn after the players' menus. On a screen wider than 640 columns, a title is moved so the edge it is justified to (its middle, if centered) keeps its place relative to the screen's sides, as on the Xbox's 4:3 screen: a right-justified chapter title ends near the right side, not short of it. | | `tag_files/tag_groups.h` | `TAG_BLOCK_GET_ELEMENT` returns an element in the block without a call, and calls `tag_block_get_element_with_size` for anything else. | -| `game/players.c`, `networking/network_server_manager.c` | Bots (`game/bots.c`, `bots.count`): the lobby of a local Slayer game takes the bot players, each the one player of a machine of its own that no real machine is, and every tick their actions come from `game/bots.c` instead of their empty queues. Nothing changes in a system link or internet game. | +| `game/players.c`, `networking/network_server_manager.c` | Bots (`game/bots.c`, `bots.count`): the lobby of a local Slayer game takes the bot players, each the one player of a machine of its own that no real machine is, and every tick their actions come from `game/bots.c` instead of their empty queues. System link and internet bots remain off unless explicitly enabled before host creation; live controls use the same ordinary player messages. | | `input/input_xbox.c`, `physics/collision_usage.c` | The clock is read only for a button held, and for collision tests only when their times are shown: a read of the clock is slow in a browser. | | `main/main.c`, `interface/hud.c`, `interface/hud_unit.c`, `interface/hud_draw.c`, `game/game_engine.c` | The text chat of network games (`game/network_chat.c`): its keys are read each frame, and the debug keys are not while a line is typed; each view's HUD draws its lines, above the motion sensor, whose place the HUD notes (the left of the last picture drawn); the scoreboard's menu has Mute voice and chat, and the host's Mute for everyone. | @@ -2008,5 +2093,18 @@ each of the browser's frames, the cache thread starts at a function of declarations given their definitions' types, which WebAssembly needs, are listed in "Game source changes" in [../web/README.md](../web/README.md). +### Shoulder camera controls + +N toggles perspective; B swaps shoulders. Left Alt holds free look. +Hold Left Alt and scroll to adjust camera distance (0.3 to 2.0 world units); +scroll up brings it closer. Ordinary scrolling still switches weapons. +These defaults are rebindable under Controls Setup > Camera. Existing saved +bindings are preserved; choose Reset or rebind them to use the new defaults. + +| Setting | Default | Environment | Meaning | +| --- | --- | --- | --- | +| `controls.camera_height` | `"Left Shift, Right Shift"` | `HALO_KEY_CAMERA_HEIGHT` | Hold either Shift and scroll to adjust camera height during shoulder view; up raises it. | +| `controls.camera_offset` | `"CapsLock"` | `HALO_KEY_CAMERA_OFFSET` | Hold Caps Lock and scroll to move left or right across either shoulder; up moves right. Uses the physical key, not its typing-toggle state. | +| `controls.camera_distance` | `"Left Alt"` | `HALO_KEY_CAMERA_DISTANCE` | Hold with the wheel to change `display.third_person_distance` during shoulder view. In first person, scopes, menus, text chat and the console the wheel keeps its existing behavior. | The [Doppler audio walkthrough](../../docs/reading/audio_doppler.md) explains listener motion, camera-cut resets and pitch limits. diff --git a/port/linux/game/ambient_emitter_lighting.c b/port/linux/game/ambient_emitter_lighting.c new file mode 100644 index 0000000000..a4e456e84b --- /dev/null +++ b/port/linux/game/ambient_emitter_lighting.c @@ -0,0 +1,173 @@ +/* Cosmetic samples only: no equipment, vehicle controls or projectile state + is written. Missing authored markers leave that source unlit. */ +#include "cseries.h" +#include "objects/objects.h" +#include "objects/object_definitions.h" +#include "tag_files/tag_files.h" +#include "ambient_emitter_lighting.h" +#include + +#include "lighting_config.h" +void render_interpolation_object_point(long object, real_point3d *point); + +static const struct ambient_profile +{ + long group; + const char *name; + int kind; + real radius; + real_rgb_color color; + const char *marker; + int function, second_marker; + real idle; +} ambient_profiles[] = { + {'vehi', "vehicles\\c_dropship\\c_dropship", EMITTER_VEHICLE, 3.5f, {0.25f, 0.45f, 1.0f}, "hover thrusters", 2, 4, 0.35f}, + {'eqip', "powerups\\over shield", EMITTER_WORLD, 1.6f, {1.0f, 0.18f, 0.08f}, NULL, 0, 0, 0.0f}, + {'eqip', "powerups\\active camouflage", EMITTER_WORLD, 1.6f, {0.15f, 0.35f, 1.0f}, NULL, 0, 0, 0.0f}, + {'scen', "scenery\\teleporter_shield\\teleporter", EMITTER_WORLD, 2.4f, {0.2f, 1.0f, 0.35f}, NULL, 0, 0, 0.0f}, + {'vehi', "vehicles\\ghost\\ghost_mp", EMITTER_VEHICLE, 1.8f, {0.15f, 0.35f, 1.0f}, "running lights", 0, 1, 0.0f}, +}; +static long ambient_identities[NUMBEROF(ambient_profiles)], flame_definition; +static int ambient_ready; + +/* One centroid per live firing owner, not a light per flame projectile. + This bounds both allocation and occlusion work independently of fire rate. */ +enum { FLAME_STREAMS = 8 }; +static struct flame_stream +{ + long owner; + int count; + real_point3d sum; +} flames[FLAME_STREAMS]; +static int flame_count; + +int ambient_emitter_lighting_enabled(void) +{ + return lighting_config_boolean("display.vehicle_lighting") || lighting_config_boolean("display.world_lighting") || + (lighting_config_boolean("display.plasma_lighting") && (!ambient_ready || flame_definition != NONE)); +} + +void ambient_emitter_lighting_forget(void) +{ + ambient_ready = FALSE; + flame_count = 0; +} + +unsigned long ambient_emitter_lighting_begin(void) +{ + struct object_iterator iterator; + struct object_datum *object; + unsigned long mask = 0; + int i; + flame_count = 0; + if (!ambient_emitter_lighting_enabled()) + return 0; + if (!ambient_ready) + { + for (i = 0; i < NUMBEROF(ambient_profiles); i++) + ambient_identities[i] = tag_loaded(ambient_profiles[i].group, ambient_profiles[i].name); + flame_definition = tag_loaded('proj', "weapons\\flamethrower\\flame"); + ambient_ready = TRUE; + } + if (lighting_config_boolean("display.vehicle_lighting")) mask |= _object_mask_vehicle; + if (lighting_config_boolean("display.world_lighting")) mask |= _object_mask_equipment | _object_mask_scenery; + if (!lighting_config_boolean("display.plasma_lighting") || flame_definition == NONE) + return mask; + object_iterator_new(&iterator, _object_mask_projectile, 0); + while ((object = object_iterator_next(&iterator)) != NULL) + { + real_point3d point; + /* Model-less flame projectiles are marked invisible by the object + renderer; their stock particle stream is nevertheless visible. */ + if (object->definition_index != flame_definition || + (TEST_FLAG(object->object.flags, _object_invisible_bit) && + object_definition_get(object->definition_index)->object.model.index != NONE) || + object->object.owner_object_index == NONE || !object_try_and_get(object->object.owner_object_index)) + continue; + for (i = 0; i < flame_count; i++) + if (flames[i].owner == object->object.owner_object_index) + break; + if (i == flame_count) + { + if (flame_count == FLAME_STREAMS) + continue; + memset(&flames[i], 0, sizeof(flames[i])); + flames[i].owner = object->object.owner_object_index; + flame_count++; + } + point = object->object.position; + render_interpolation_object_point(iterator.index, &point); + flames[i].sum.x += point.x; + flames[i].sum.y += point.y; + flames[i].sum.z += point.z; + flames[i].count++; + } + if (flame_count) mask |= _object_mask_biped | _object_mask_vehicle | _object_mask_weapon; + return mask; +} + +int ambient_emitter_lighting_sample(long index, int component, struct emitter_sample *sample) +{ + struct object_datum *object = object_try_and_get(index); + struct object_marker markers[8]; + int i, marker; + if (!object || TEST_FLAG(object->object.flags, _object_invisible_bit)) + return FALSE; + if (!component && lighting_config_boolean("display.plasma_lighting")) + for (i = 0; i < flame_count; i++) + if (flames[i].owner == index) + { + sample->kind = EMITTER_FLAME; + sample->position.x = flames[i].sum.x / flames[i].count; + sample->position.y = flames[i].sum.y / flames[i].count; + sample->position.z = flames[i].sum.z / flames[i].count; + sample->color.red = 1.0f; + sample->color.green = 0.38f; + sample->color.blue = 0.06f; + sample->radius = 2.8f; + sample->strength = MIN(1.0f, flames[i].count * 0.2f); + return TRUE; + } + if (!ambient_ready || object->object.parent_object_index != NONE || + object->object.node_matrices.size < sizeof(real_matrix4x3)) + return FALSE; + for (i = 0; i < NUMBEROF(ambient_profiles); i++) + { + const struct ambient_profile *profile = &ambient_profiles[i]; + if (ambient_identities[i] == NONE || object->definition_index != ambient_identities[i] || + !lighting_config_boolean(profile->kind == EMITTER_VEHICLE ? "display.vehicle_lighting" : "display.world_lighting")) + continue; + sample->kind = profile->kind; + sample->radius = profile->radius; + sample->color = profile->color; + sample->strength = 0.8f; + if (profile->kind == EMITTER_VEHICLE) + { + /* Two separated thruster sources, attached to the authored model. + The output follows the authored light/engine function. */ + marker = component ? profile->second_marker : 0; + if (object_get_marker_by_name(index, profile->marker, markers, NUMBEROF(markers)) <= marker) + return FALSE; + sample->position = markers[marker].matrix.position; + /* Dropship thruster surfaces stay luminous at idle; C-out + adds throttle intensity. Destroyed vehicles remain dark. */ + sample->strength *= profile->idle + (1.0f - profile->idle) * + PIN(object->object.outgoing_function_values[profile->function], 0.0f, 1.0f); + if (object->object.maximum_body_vitality > 0.0f && object->object.body_vitality <= 0.0f) + sample->strength = 0.0f; + } + else + { + if (component) + return FALSE; + object_get_origin(index, &sample->position); + render_interpolation_object_point(index, &sample->position); + /* The luminous portal surface is separate from its unlit base. + Do not infer portals from netgame flags or illuminate every pad. */ + if (profile->group == 'scen') + sample->position.z += 0.35f; + } + return TRUE; + } + return FALSE; +} diff --git a/port/linux/game/ambient_emitter_lighting.h b/port/linux/game/ambient_emitter_lighting.h new file mode 100644 index 0000000000..80cf22a109 --- /dev/null +++ b/port/linux/game/ambient_emitter_lighting.h @@ -0,0 +1,20 @@ +#ifndef AMBIENT_EMITTER_LIGHTING_H +#define AMBIENT_EMITTER_LIGHTING_H + +/* Render samples share the existing bounded emitter pool. */ +struct emitter_sample +{ + int kind; + real strength, radius, view_gain; + real_rgb_color color; + real_point3d position; + real_vector3d direction; +}; +enum { EMITTER_VEHICLE = 5, EMITTER_WORLD, EMITTER_FLAME }; +int ambient_emitter_lighting_enabled(void); +/* Build bounded stream samples and return only the object types worth scanning. */ +unsigned long ambient_emitter_lighting_begin(void); +void ambient_emitter_lighting_forget(void); +int ambient_emitter_lighting_sample(long object, int component, struct emitter_sample *sample); + +#endif diff --git a/port/linux/game/ammo_counter_falloff.c b/port/linux/game/ammo_counter_falloff.c new file mode 100644 index 0000000000..ea7be32d1e --- /dev/null +++ b/port/linux/game/ammo_counter_falloff.c @@ -0,0 +1,146 @@ +/* A screen emits into its forward hemisphere. Keep this mask independent of + the optional collision field and its admission budget. */ +#include "cseries.h" +#include +#include "rasterizer/rasterizer_swizzle.h" +#include "covenant_emitter_lighting.h" +#include "ammo_counter_falloff.h" +#include "plasma_occlusion.h" +#include "plasma_lighting.h" +#include +#include + +enum { COUNTER_SIZE = 16, COUNTER_COUNT = 4096, COUNTER_LIGHTS = 8 }; +static struct counter_texture +{ + long rasterizer; + int used, mask, profile; + float axis[3]; + float specular_scale; + IDirect3DVolumeTexture8 *texture[3]; +} counters[COUNTER_LIGHTS]; + +float ammo_counter_falloff_factor(const float axis[3], float x, float y, float z) +{ + float length = sqrtf(x*x + y*y + z*z); + float t; + if (length < 0.00001f) + return 0.0f; + t = PIN((axis[0]*x + axis[1]*y + axis[2]*z) / (length * 0.6f), 0.0f, 1.0f); + return t*t*(3.0f - 2.0f*t); +} + +/* Exposed needles have radial spill, including immediately below the source. + Fade only farther down in world space to keep hands/housing lit without a + floor pool. End the fade before the next lower volume-texture slice: its + linear filtering otherwise carries spill down to crouched/short holders' + feet, especially with the larger specular radius. Height is relative to + the source, divided by the light radius. */ +float needler_falloff_factor(float height) +{ + float t = PIN((-height - 0.06f) / 0.06f, 0.0f, 1.0f); + return 1.0f - t*t*(3.0f - 2.0f*t); +} + +/* Exposed prongs illuminate a broad forward lobe, with a soft transition + just behind the emitter plane rather than the counter's focused mask. */ +float plasma_prong_falloff_factor(const float axis[3], float x, float y, float z) +{ + float length = sqrtf(x*x + y*y + z*z); + float t; + if (length < 0.00001f) return 0.0f; + t = PIN(((axis[0]*x + axis[1]*y + axis[2]*z) / length + 0.2f) / 0.7f, 0.0f, 1.0f); + return t*t*(3.0f - 2.0f*t); +} + +void *ammo_counter_falloff_texture(long rasterizer, int radial, float transform[4]) +{ + float axis[3], origin[3], radius, scale = 1.0f; + struct counter_texture *counter = NULL; + D3DLOCKED_BOX box; + unsigned long pixels[COUNTER_COUNT]; + int i, x, y, z; + int profile = covenant_emitter_lighting_cone(rasterizer, axis, origin, &radius); + if (!profile) profile = plasma_lighting_prong_cone(rasterizer, axis, origin, &radius); + if (!profile || radius <= 0.0f) + return NULL; + if (transform) + { + for (i = 0; i < 3; i++) transform[i] = origin[i]; + transform[3] = 0.5f / radius; + } + for (i = 0; i < COUNTER_LIGHTS; i++) + if (counters[i].used && counters[i].rasterizer == rasterizer) + counter = &counters[i]; + if (!counter) + for (i = 0; i < COUNTER_LIGHTS; i++) + if (!counters[i].used) + { + counter = &counters[i]; + counter->used = TRUE; + counter->rasterizer = rasterizer; + break; + } + if (!counter) + return NULL; + /* Translation and radius change the transform, not the normalized mask. */ + if (counter->profile != profile || (profile != 2 && (counter->axis[0] != axis[0] || + counter->axis[1] != axis[1] || counter->axis[2] != axis[2]))) + { + counter->mask = 0; + counter->profile = profile; + memcpy(counter->axis, axis, sizeof(axis)); + } + /* Angular AR masks are scale-independent. The radial Needler's lower fade + needs a separate variant when specular receivers use another radius. */ + if (profile == 2 && radial == 2) + scale = plasma_occlusion_specular_scale(rasterizer); + radial = scale != 1.0f ? 2 : radial != 0; + if (radial == 2 && counter->specular_scale != scale) + { + counter->mask &= ~(1 << 2); + counter->specular_scale = scale; + } + if (counter->mask & (1 << radial)) + return counter->texture[radial]; + if (!counter->texture[radial] && D3DDevice_CreateVolumeTexture(COUNTER_SIZE, COUNTER_SIZE, + COUNTER_SIZE, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, &counter->texture[radial]) < 0) + return NULL; + if (IDirect3DVolumeTexture8_LockBox(counter->texture[radial], 0, &box, NULL, 0) < 0 || !box.pBits) + return NULL; + for (z = 0; z < COUNTER_SIZE; z++) + for (y = 0; y < COUNTER_SIZE; y++) + for (x = 0; x < COUNTER_SIZE; x++) + { + float dx = 2.0f*(x+0.5f)/COUNTER_SIZE - 1.0f; + float dy = 2.0f*(y+0.5f)/COUNTER_SIZE - 1.0f; + float dz = 2.0f*(z+0.5f)/COUNTER_SIZE - 1.0f; + float value = profile == 3 ? plasma_prong_falloff_factor(axis, dx, dy, dz) : profile == 2 ? needler_falloff_factor(dz * scale) : + ammo_counter_falloff_factor(axis, dx, dy, dz); + float remaining = MAX(0.0f, 1.0f - dx*dx - dy*dy - dz*dz); + if (radial) value *= remaining*remaining; + pixels[(z*COUNTER_SIZE+y)*COUNTER_SIZE+x] = (unsigned long)(255.0f*value+0.5f)*0x01010101UL; + } + rasterizer_xbox_bitmap_swizzle3d_long(box.pBits, pixels, COUNTER_SIZE, COUNTER_SIZE, COUNTER_SIZE); + if (IDirect3DVolumeTexture8_UnlockBox(counter->texture[radial], 0) < 0) + return NULL; + counter->mask |= 1 << radial; + return counter->texture[radial]; +} + +void ammo_counter_falloff_window(void) +{ + int i; + for (i = 0; i < COUNTER_LIGHTS; i++) + counters[i].used = 0; +} + +void ammo_counter_falloff_dispose(void) +{ + int i, j; + for (i = 0; i < COUNTER_LIGHTS; i++) + for (j = 0; j < 3; j++) + if (counters[i].texture[j]) + D3DResource_Release((D3DResource *)counters[i].texture[j]); + memset(counters, 0, sizeof(counters)); +} diff --git a/port/linux/game/ammo_counter_falloff.h b/port/linux/game/ammo_counter_falloff.h new file mode 100644 index 0000000000..7c645ed434 --- /dev/null +++ b/port/linux/game/ammo_counter_falloff.h @@ -0,0 +1,11 @@ +#ifndef AMMO_COUNTER_FALLOFF_H +#define AMMO_COUNTER_FALLOFF_H + +float ammo_counter_falloff_factor(const float axis[3], float x, float y, float z); +float needler_falloff_factor(float height); +float plasma_prong_falloff_factor(const float axis[3], float x, float y, float z); +void *ammo_counter_falloff_texture(long rasterizer, int radial, float transform[4]); +void ammo_counter_falloff_window(void); +void ammo_counter_falloff_dispose(void); + +#endif diff --git a/port/linux/game/ammo_counter_lighting.c b/port/linux/game/ammo_counter_lighting.c new file mode 100644 index 0000000000..7d29a67167 --- /dev/null +++ b/port/linux/game/ammo_counter_lighting.c @@ -0,0 +1,124 @@ +/* The AR display's rendered pose and optional material emission. + The emitter module owns light allocation, fading and frame cleanup. */ +#include "cseries.h" +#include +#include "objects/objects.h" +#include "items/weapons.h" +#include "units/units.h" +#include "interface/first_person_weapons.h" +#include "ammo_counter_lighting.h" +#include "shaders/shader_definitions.h" +#include "rasterizer/xbox/rasterizer_xbox.h" +#include + +#include "lighting_config.h" + +int ammo_counter_lighting_position(long index, real_point3d *position, real_vector3d *direction) +{ + struct weapon_datum *weapon; + struct unit_datum *unit; + struct object_marker marker; + real_vector3d forward, up; + real height; + int pose = 1; + const char *name; + if (!lighting_config_boolean("display.ammo_counter_lighting")) + return FALSE; + weapon = weapon_try_and_get(index); + if (!weapon || TEST_FLAG(weapon->object.flags, _object_invisible_bit)) + return FALSE; + name = tag_get_name(weapon->definition_index); + if (!name || strcmp(name, "weapons\\assault rifle\\assault rifle")) + return FALSE; + unit = unit_try_and_get(weapon->object.parent_object_index); + if (!unit || TEST_FLAG(unit->object.flags, _object_invisible_bit) || + unit->unit.current_weapon_index < 0 || unit->unit.current_weapon_index >= MAXIMUM_WEAPONS_PER_UNIT || + unit_inventory_get_weapon(weapon->object.parent_object_index, unit->unit.current_weapon_index) != index) + return FALSE; + /* Both stock displays lie near x=.047, z=.069 in model space. Place the + light just behind/above that surface, using the identity-oriented muzzle + marker. The FP muzzle is .002744 units higher than the world muzzle. */ + if (first_person_weapon_adjust_light(index, "primary trigger", position, &forward, &up)) + { + height = 0.025f; + pose = 2; + } + else + { + if (weapon->object.node_matrices.size < sizeof(real_matrix4x3) || + !object_get_marker_by_name(index, "primary trigger", &marker, 1)) + return FALSE; + *position = marker.matrix.position; + forward = marker.matrix.forward; + up = marker.matrix.up; + height = 0.027744f; + } + /* Broad rear/up-facing emission approximates the sloped display surface. + Derive it from the rendered weapon basis, never world up. */ + direction->i = -0.8f * forward.i + 0.6f * up.i; + direction->j = -0.8f * forward.j + 0.6f * up.j; + direction->k = -0.8f * forward.k + 0.6f * up.k; + position->x += -0.18f * forward.i + height * up.i; + position->y += -0.18f * forward.j + height * up.j; + position->z += -0.18f * forward.k + height * up.k; + return pose; +} + +/* Cache only within a loaded map; the emitter lifecycle clears this pointer. */ +static struct shader *ammo_counter_screen; +static int ammo_counter_screen_checked; +static int ammo_counter_draw_active; +static unsigned long ammo_counter_draw_output; + +void ammo_counter_lighting_forget(void) +{ + ammo_counter_screen = NULL; + ammo_counter_screen_checked = FALSE; + ammo_counter_draw_active = FALSE; +} + +static int ammo_counter_is_screen(struct shader *shader) +{ + long index; + if (!lighting_config_boolean("display.ammo_counter_lighting")) + return FALSE; + if (!ammo_counter_screen_checked) + { + index = tag_loaded('soso', "weapons\\assault rifle\\fp\\shaders\\display"); + ammo_counter_screen = index == NONE ? NULL : shader_definition_get(index); + ammo_counter_screen_checked = TRUE; + } + return shader && shader == ammo_counter_screen; +} + +void ammo_counter_lighting_screen(struct shader *shader, real_rgb_color *color) +{ + if (!ammo_counter_is_screen(shader)) + return; + /* The authored multipurpose-map mask confines emission to the screen. + Both stock AR models share this shader; retain any brighter animation. */ + color->red = MAX(color->red, 0.45f); + color->green = MAX(color->green, 1.0f); + color->blue = MAX(color->blue, 1.0f); +} + +/* Colour constants are already saturated. Boost the completed display RGB + before fog, confined to this material in either model. Restore the exact + output after drawing so other materials and views remain unchanged. */ +void ammo_counter_lighting_draw_begin(struct shader *shader, unsigned long output) +{ + if (!ammo_counter_is_screen(shader) || (output & 0x38000UL)) + return; + ammo_counter_draw_output = output; + ammo_counter_draw_active = TRUE; + IDirect3DDevice8_SetRenderState(global_d3d_device, D3DRS_PSRGBOUTPUTS7, output | 0x10000UL); +} + +void ammo_counter_lighting_draw_end(void) +{ + if (ammo_counter_draw_active) + { + IDirect3DDevice8_SetRenderState(global_d3d_device, D3DRS_PSRGBOUTPUTS7, ammo_counter_draw_output); + ammo_counter_draw_active = FALSE; + } +} diff --git a/port/linux/game/ammo_counter_lighting.h b/port/linux/game/ammo_counter_lighting.h new file mode 100644 index 0000000000..0533974bdd --- /dev/null +++ b/port/linux/game/ammo_counter_lighting.h @@ -0,0 +1,14 @@ +#ifndef AMMO_COUNTER_LIGHTING_H +#define AMMO_COUNTER_LIGHTING_H + +/* Pose result: 0 unavailable, 1 world model, 2 first-person model. */ +int ammo_counter_lighting_position(long weapon, real_point3d *position, real_vector3d *direction); + +struct shader; +void ammo_counter_lighting_screen(struct shader *shader, real_rgb_color *color); +/* Balanced around one model material draw, before any following fog pass. */ +void ammo_counter_lighting_draw_begin(struct shader *shader, unsigned long output); +void ammo_counter_lighting_draw_end(void); +void ammo_counter_lighting_forget(void); + +#endif diff --git a/port/linux/game/android_cheats.c b/port/linux/game/android_cheats.c new file mode 100644 index 0000000000..a3fd132557 --- /dev/null +++ b/port/linux/game/android_cheats.c @@ -0,0 +1,82 @@ +/* Android cheat menu inspired by thelinkin3000/halo-ce-universal's overlay +(406f793f4c08751f854a3615ed244ea3b1f90b88), which credits hardran3's +OpenCE-Ultrahand and HaloDrones packages. The fork's general console and +renderer overlay are not imported; these requests use existing cheat APIs. +See docs/reading/bots_and_android_features.md for credits and constraints. */ +#include "cseries.h" +#include "android_cheats.h" + +#ifdef HALO_ANDROID +#include "game/cheats.h" +#include "networking/network_game_globals.h" + +int config_boolean(char const *name); +int touch_game_playing(void); +int touch_game_cinematic_playing(void); +void host_android_cheats_state(int state); +int host_android_cheats_read(void); + +/* IDs 0..8 are switches; 9..12 are one-shot actions. The Android UI and +host queue use the same IDs. Bit 8 carries the requested switch value. */ +extern boolean rider_ejection; +static boolean *const switches[] = +{ + &cheat.deathless_player, &cheat.infinite_ammo, &cheat.bottomless_clip, &cheat.super_jump, + &cheat.omnipotent, &cheat.jetpack, &cheat.medusa, &cheat.bump_possession, &rider_ejection +}; +static boolean previous[NUMBEROF(switches)], applied[NUMBEROF(switches)]; +static unsigned long owned; + +void android_cheats_reset(void) +{ + long index; + for (index = 0; index < (long)NUMBEROF(switches); index++) + { + /* Leave a subsequent console/script change alone. */ + if (TEST_FLAG(owned, index) && *switches[index] == applied[index]) + *switches[index] = previous[index]; + } + owned = 0; + host_android_cheats_state(0); +} + +void android_cheats_update(void) +{ + int enabled = config_boolean("android.cheat_menu"); + /* Match the desktop console: a joined client never changes the game, + including the lobby before distributed-client simulation begins. */ + int allowed = enabled && touch_game_playing() && + !network_game_distributed_client() && + (!global_network_game_client_get() || global_network_game_server_get()); + int request, count, state = enabled ? 1 : 0; + long index; + if (!allowed) + { + android_cheats_reset(); + host_android_cheats_state(state); + return; + } + /* Four requests at most per input poll; the host queue is bounded too. */ + for (count = 0; !touch_game_cinematic_playing() && count < 4 && (request = host_android_cheats_read()) >= 0; count++) + { + index = request & 0xFF; + if ((request & ~0x10F) != 0 || index > 12 || (index >= 9 && (request & 0x100))) continue; + if (index < (long)NUMBEROF(switches)) + { + if (!TEST_FLAG(owned, index)) previous[index] = *switches[index]; + SET_FLAG(owned, index, TRUE); + /* Easy Rider is on when the engine's rider ejection is off. */ + applied[index] = ((request & 0x100) != 0) != (index == 8); + *switches[index] = applied[index]; + } + else if (index == 9) cheat_all_weapons(); + else if (index == 10) cheat_all_powerups(); + else if (index == 11) cheat_active_camouflage_local_player(0); + else if (index == 12) cheat_all_vehicles(); + } + if (!touch_game_cinematic_playing()) state |= 2; + for (index = 0; index < (long)NUMBEROF(switches); index++) + if ((*switches[index] != FALSE) != (index == 8)) state |= 1 << (8 + index); + host_android_cheats_state(state); +} +#endif diff --git a/port/linux/game/android_cheats.h b/port/linux/game/android_cheats.h new file mode 100644 index 0000000000..adef1139c9 --- /dev/null +++ b/port/linux/game/android_cheats.h @@ -0,0 +1,6 @@ +/* Android's optional menu uses typed requests, never console command text. */ +#ifndef HALO_ANDROID_CHEATS_H +#define HALO_ANDROID_CHEATS_H +void android_cheats_update(void); +void android_cheats_reset(void); +#endif diff --git a/port/linux/game/authored_emitter_lighting.c b/port/linux/game/authored_emitter_lighting.c new file mode 100644 index 0000000000..047a7b6ff4 --- /dev/null +++ b/port/linux/game/authored_emitter_lighting.c @@ -0,0 +1,106 @@ +/* Reuse authored attachment timing, colours, cones and render poses. Never + add a second light beside an existing source or change its simulation. */ +#include "cseries.h" +#include "objects/objects.h" +#include "tag_files/tag_files.h" +#include "authored_emitter_lighting.h" +#include "camera/observer.h" +#include "game/players.h" + +#include "lighting_config.h" + +static const struct authored_emitter_profile +{ + long group; + const char *object, *light; + float scale; + int category; +} profiles[] = { + {'weap', "weapons\\energy sword\\energy sword", "weapons\\energy sword\\energy sword dynamic", 2.5f, 1}, + {'proj', "weapons\\plasma grenade\\plasma grenade", "weapons\\plasma grenade\\plasma grenade", 1.5f, 3}, + {'weap', "weapons\\plasma pistol\\plasma pistol", "weapons\\plasma rifle\\overcharge", 1.5f, 1}, + /* Prong flares have a short, broad forward spill (category 4). The + authored pistol radius is 1.5, the rifle's 0.1: both reach 0.3 here. */ + {'weap', "weapons\\plasma pistol\\plasma pistol", "weapons\\plasma pistol\\plasma pistol flare", 0.2f, 4}, + {'weap', "weapons\\plasma rifle\\plasma rifle", "weapons\\plasma rifle\\plasma rifle flare", 3.0f, 4}, + {'vehi', "vehicles\\ghost\\ghost", "vehicles\\ghost\\ghost running", 2.2f, 2}, + {'vehi', "vehicles\\banshee\\banshee", "vehicles\\banshee\\banshee wing", 2.2f, 2}, + {'vehi', "vehicles\\banshee\\banshee_mp", "vehicles\\banshee\\banshee wing", 2.2f, 2}, + {'vehi', "vehicles\\warthog\\mp_warthog", "vehicles\\warthog\\headlights light", 1.0f, 2}, + {'vehi', "vehicles\\rwarthog\\rwarthog", "vehicles\\warthog\\headlights light", 1.0f, 2}, + {'vehi', "vehicles\\scorpion\\scorpion_mp", "vehicles\\scorpion\\headlight scorpion", 1.0f, 2}, + {'vehi', "vehicles\\warthog\\warthog", "vehicles\\warthog\\headlights light", 1.0f, 2}, + {'vehi', "vehicles\\scorpion\\scorpion", "vehicles\\scorpion\\headlight scorpion", 1.0f, 2}, +}; +static struct { long object, light; } identities[NUMBEROF(profiles)]; +static int identities_ready; + +/* Tiny prong spill is a close-range detail. Fade its radius continuously + from three to six world units, considering every local player's view. + The authored luminous surface/flare is not changed at any distance. */ +static float prong_reach(struct object_datum const *object) +{ + int i, count = local_player_count(); + float nearest = 36.0f; + if (!count) return 1.0f; + for (i = 0; i < count; i++) + { + struct observer_result const *camera = observer_get_camera((short)i); + float x = camera->position.x - object->object.bounding_sphere_center.x; + float y = camera->position.y - object->object.bounding_sphere_center.y; + float z = camera->position.z - object->object.bounding_sphere_center.z; + float distance = x*x + y*y + z*z; + nearest = MIN(nearest, distance); + } + nearest = PIN((36.0f - nearest) / 27.0f, 0.0f, 1.0f); + return nearest * nearest * (3.0f - 2.0f * nearest); +} + +int authored_emitter_lighting_category_enabled(int category) +{ + return lighting_config_boolean(category == 4 ? "display.plasma_prong_lighting" : category == 1 ? "display.weapon_glow" : + category == 2 ? "display.vehicle_lighting" : "display.plasma_lighting"); +} + +int authored_emitter_lighting_enabled(void) +{ + return lighting_config_boolean("display.weapon_glow") || lighting_config_boolean("display.plasma_prong_lighting") || lighting_config_boolean("display.vehicle_lighting"); +} + +void authored_emitter_lighting_forget(void) +{ + identities_ready = FALSE; +} + +int authored_emitter_lighting_profile(long object_index, long definition, float *scale) +{ + struct object_datum *object; + int i; + if (!authored_emitter_lighting_enabled() && !lighting_config_boolean("display.plasma_lighting")) + return 0; + object = object_try_and_get(object_index); + if (!object || definition == NONE) + return 0; + if (!identities_ready) + { + for (i = 0; i < NUMBEROF(profiles); i++) + { + identities[i].object = tag_loaded(profiles[i].group, profiles[i].object); + identities[i].light = tag_loaded('ligh', profiles[i].light); + } + identities_ready = TRUE; + } + for (i = 0; i < NUMBEROF(profiles); i++) + if (identities[i].object != NONE && object->definition_index == identities[i].object && + definition == identities[i].light && authored_emitter_lighting_category_enabled(profiles[i].category)) + { + *scale = profiles[i].scale; + if (profiles[i].category == 4) + { + *scale *= prong_reach(object); + if (*scale <= 0.0001f) return 0; + } + return profiles[i].category; + } + return 0; +} diff --git a/port/linux/game/authored_emitter_lighting.h b/port/linux/game/authored_emitter_lighting.h new file mode 100644 index 0000000000..ebee353b7a --- /dev/null +++ b/port/linux/game/authored_emitter_lighting.h @@ -0,0 +1,10 @@ +#ifndef AUTHORED_EMITTER_LIGHTING_H +#define AUTHORED_EMITTER_LIGHTING_H + +/* Exact object/light pairs; zero means the stock submission is untouched. */ +int authored_emitter_lighting_enabled(void); +int authored_emitter_lighting_category_enabled(int category); +int authored_emitter_lighting_profile(long object, long definition, float *scale); +void authored_emitter_lighting_forget(void); + +#endif diff --git a/port/linux/game/bots.c b/port/linux/game/bots.c index ebb1ce3372..c28699ceb3 100644 --- a/port/linux/game/bots.c +++ b/port/linux/game/bots.c @@ -65,11 +65,11 @@ fight's counts. The simulation: a bot decides from the game state at the tick and its own random numbers (seeded per bot and game), and its path searches run in the -tick, so the bots do the same in two runs of the same input. Nothing of a -bot is in the game state: multiplayer games are never saved. Bots are in -local games only, which no other machine sees: no message of the network -protocol changes, and bots_update_actions does nothing unless a local game -runs. halo.log has the map's preparation and each minute of play's bots +tick, so the bots do the same in two runs of the same input. Only the +selected controller runs; enhanced mode owns its state separately. No bot +state is saved. Network admission and publication use bots_network.c; the +host decides and clients replay ordinary player actions. halo.log has the +map's preparation and each minute of play's bots line: the searches and how many failed, the times a bot stood stuck, shots and each bot's kills and deaths; debug.bot_trace logs each bot's state. */ @@ -99,6 +99,7 @@ and each bot's kills and deaths; debug.bot_trace logs each bot's state. #include "tag_files/tag_files.h" #include "bots.h" +#include "enhanced_bots_controller.h" #include "bots_combat.h" #include @@ -109,8 +110,23 @@ and each bot's kills and deaths; debug.bot_trace logs each bot's state. /* port/linux/src/port_config.c */ const char *config_string(char const *name); long config_integer(char const *name); +int config_boolean(char const *name); void platform_log(char const *format, ...); +static int bots_enhanced_running; + +int bots_gametype_active(long engine) +{ + return engine == game_engine_slayer || (bots_enhanced_running && + (engine == game_engine_ctf || engine == game_engine_king)); +} + +int bots_gametype_allowed(long engine) +{ + return engine == game_engine_slayer || (config_boolean("bots.enhanced") && + (engine == game_engine_ctf || engine == game_engine_king)); +} + /* ---------- constants */ #define BOTS_PI 3.14159265f @@ -418,18 +434,25 @@ int bots_machine_is_bot(long machine_index) void bots_network_player(long bot_index, struct network_player *player) { - /* (the Marines of Halo's campaign; eleven characters at most) */ - static char const *const names[BOTS_MAXIMUM] = + /* The Marines of Halo's campaign, identified as bots in player displays. */ + static char const *const names[] = { "Johnson", "Jenkins", "Mendoza", "Bisenti", "Stacker", "Polaski", "Chips", "Kojo", "Rawley", "Riley", "Wellsley", "Hall", "Fitzgerald", "Locklear", "Mitchell", }; - char const *name = names[bot_index % BOTS_MAXIMUM]; + char const *name = names[bot_index % NUMBEROF(names)]; + char display_name[NUMBEROF(player->name)]; long index; + /* The wire name has eleven visible characters: four for the prefix, + seven for a name, or five and a unique two-digit suffix for additional bots. */ + if (bot_index >= (long)NUMBEROF(names)) + snprintf(display_name, sizeof(display_name), "BOT %.5s%02ld", name, bot_index + 1); + else + snprintf(display_name, sizeof(display_name), "BOT %.7s", name); csmemset(player, 0, sizeof(*player)); - for (index = 0; index < (long)NUMBEROF(player->name) - 1 && name[index]; index++) - player->name[index] = (wchar_t)name[index]; + for (index = 0; index < (long)NUMBEROF(player->name) - 1 && display_name[index]; index++) + player->name[index] = (wchar_t)display_name[index]; player->name[index] = 0; player->primary_color_index = NONE; player->icon_index = 0; @@ -1297,6 +1320,14 @@ void bots_initialize_for_new_map(void) { long index; + bots_management_reset(); + bots_enhanced_running = config_boolean("bots.enhanced"); + if (bots_enhanced_running) + { + enhanced_controller_initialize(); + return; + } + csmemset(bots_globals.bots, 0, sizeof(bots_globals.bots)); for (index = 0; index < BOTS_MAXIMUM; index++) bots_globals.bots[index].player_index = NONE; @@ -1320,6 +1351,13 @@ void bots_initialize_for_new_map(void) void bots_dispose_from_old_map(void) { + bots_management_reset(); + if (bots_enhanced_running) + { + enhanced_controller_dispose(); + bots_enhanced_running = FALSE; + return; + } bots_paths_release(); bots_globals.map_ready = FALSE; } @@ -3005,8 +3043,14 @@ void bots_update_actions(struct player_action *actions) struct player_datum *player; long count = 0; - /* (local games alone: no other machine sees a bot) */ - if (!game_engine_running() || !network_game_is_splitscreen_local()) + if (bots_enhanced_running) + { + enhanced_controller_update(actions); + return; + } + + /* Common admission and authority; stock decisions stay here. */ + if (!game_engine_running() || !bots_session_allowed()) return; data_iterator_new(&iterator, player_data); while ((player = (struct player_datum *)data_iterator_next(&iterator)) != NULL) @@ -3015,7 +3059,7 @@ void bots_update_actions(struct player_action *actions) long absolute_index = DATUM_INDEX_TO_ABSOLUTE_INDEX(iterator.datum_index); struct bots_bot *bot; - if (player->local_player_index != NONE || !bots_machine_is_bot(player->network_player_data.machine_index)) + if (player->local_player_index != NONE || !bots_player_owned(player->network_player_data.machine_index)) continue; /* (the roaming places and the walkable surfaces once a game has bots; the skill once a tick) */ @@ -3040,4 +3084,5 @@ void bots_update_actions(struct player_action *actions) bots_globals.ticks++; bots_report(); } + bots_network_record_actions(actions); } diff --git a/port/linux/game/bots.h b/port/linux/game/bots.h index 8d6bca6f4b..5630956e2b 100644 --- a/port/linux/game/bots.h +++ b/port/linux/game/bots.h @@ -1,20 +1,22 @@ -/* bots.h: computer players for local multiplayer games (port/linux/game/bots.c) +/* bots.h: host-controlled computer players (port/linux/game/bots.c) -A bot is a player of a local (split screen) game whose controls come from +A bot is a player whose controls come from code instead of a controller: it is in the lobby, the scores and the game's rules as any player is, spawns, respawns and scores. Each bot is the one player of a machine of its own at the top of the machine indices -(BOTS_FIRST_MACHINE up), which no real machine takes: a split screen game has -only its own machine. The bots have no view and no controller: nothing is +(BOTS_FIRST_MACHINE up). Local games have only their own real machine; +opted-in network hosts reserve this range. Ownership is tracked separately. The bots have no view and no controller: nothing is drawn for them. */ #ifndef HALO_BOTS_H #define HALO_BOTS_H struct player_action; struct network_player; +struct network_game; +struct network_game_server; -/* the most bots in one game (with one player, the Xbox's 16) */ -#define BOTS_MAXIMUM 15 +/* Optional host bots: 63 plus one human, within the existing 128 slots. */ +#define BOTS_MAXIMUM 63 /* the first bot's machine index (the last machine indices of the session) */ #define BOTS_FIRST_MACHINE (HALO_PORT_MAXIMUM_NETWORK_MACHINES - BOTS_MAXIMUM) @@ -30,16 +32,41 @@ enum long bots_wanted_count(void); short bots_skill(void); short bots_teams(void); +/* The inherited Slayer bots, plus CTF/King when enhanced bots are enabled. */ +int bots_gametype_allowed(long engine); +int bots_gametype_active(long engine); +/* Host controls use existing player joins/quits; team is NONE, red 0 or blue 1. */ +int bots_manage(int add, int team, char *status, long size); +void bots_management_reset(void); +/* -1 for an unrelated command, otherwise the host action's success. */ +int bots_console_command(char const *expression); +/* Host policy is read at creation and may be applied from the pregame menu. */ +void bots_network_session_begin(void); +void bots_network_session_end(void); +int bots_network_reserved(void); +void bots_network_lobby_enable(int enabled); +int bots_lobby_settings_apply(char *status, long size); +int bots_session_allowed(void); +void bots_player_ownership(long machine_index, int present); +int bots_player_owned(long machine_index); +/* Browser population excludes host-owned bots; the gameplay roster does not. */ +long bots_human_count(struct network_game *game); +long bots_population_wanted(struct network_game *game); +long bots_population_after_join(struct network_game *game); +void bots_population_changed(struct network_game *game, int change); +int bots_population_can_join(struct network_game_server *server); +/* One human machine with owned bots can start the ordinary lobby countdown. */ +int bots_lobby_can_start(struct network_game *game); +void bots_network_record_actions(struct player_action *actions); -/* a machine is a bot's */ +/* Whether a machine ID falls in the reserved range; not an ownership check. */ int bots_machine_is_bot(long machine_index); /* the network player for bot number `bot_index` (0 up): its machine, controller, name and no team or colour yet */ void bots_network_player(long bot_index, struct network_player *player); /* the game tick (players_update_before_game): every bot's controls this -tick, into the actions of the players by their index; nothing outside a -local game */ +tick, into the actions of the players by their index; host only */ void bots_update_actions(struct player_action *actions); /* a map's start and end (players.c) */ diff --git a/port/linux/game/bots_infection.inl b/port/linux/game/bots_infection.inl new file mode 100644 index 0000000000..de83719a7a --- /dev/null +++ b/port/linux/game/bots_infection.inl @@ -0,0 +1,70 @@ +/* Infection goals from thelinkin3000/halo-ce-universal 18a94774, +using its inherited BirchWoodGod bot tactics (GPL-3.0-only). Included by +enhanced_bots.c. The role snapshot is shared, bounded and refreshed once +a second, rather than rescanning every player for every candidate place. */ +static struct +{ + long next_scan, count; + struct { long player; boolean zombie; real_point3d point; } players[128]; +} bots_infection; + +static boolean bots_infection_goal(struct bots_bot *bot, struct player_datum *player, real_point3d const *position) +{ + long now = game_time_get(), index, humans = 0; + boolean zombie = infection_unit_is_zombie(player->unit_index); + real_point3d center = { 0.0f, 0.0f, 0.0f }, target; + real nearest = REAL_MAX, best_score = REAL_MAX; + boolean found = FALSE; + if (now >= bots_infection.next_scan) + { + struct data_iterator iterator; + struct player_datum *other; + bots_infection.count = 0; + bots_infection.next_scan = now + TICKS_PER_SECOND; + data_iterator_new(&iterator, player_data); + while ((other = (struct player_datum *)data_iterator_next(&iterator)) != NULL && + bots_infection.count < (long)NUMBEROF(bots_infection.players)) + { + struct object_datum *unit = object_try_and_get(other->unit_index); + if (!unit || TEST_FLAG(unit->object.damage_flags, _object_dead_bit)) continue; + index = bots_infection.count++; + bots_infection.players[index].player = iterator.datum_index; + bots_infection.players[index].zombie = infection_unit_is_zombie(other->unit_index); + bots_infection.players[index].point = unit->object.position; + } + } + for (index = 0; index < bots_infection.count; index++) + { + real distance; + real_point3d const *point = &bots_infection.players[index].point; + if (bots_infection.players[index].player == bot->player_index || bots_infection.players[index].zombie) continue; + center.x += point->x; center.y += point->y; center.z += point->z; + humans++; + distance = bots_distance3d(position, point); + if (distance < nearest) { nearest = distance; target = *point; found = TRUE; } + } + if (zombie) return found && bots_ctf_set_goal(bot, &target, 3.0f); + if (bot->goal_kind == _bots_goal_objective && now < bot->guard_until_tick) return TRUE; + found = FALSE; + if (humans) { center.x /= humans; center.y /= humans; center.z /= humans; } + for (index = 0; index < bots_globals.roam_point_count; index++) + { + real_point3d const *point = &bots_globals.roam_points[index]; + real score; + if (humans) score = bots_distance3d(point, ¢er); + else + { + long other; + real danger = REAL_MAX; + for (other = 0; other < bots_infection.count; other++) + if (bots_infection.players[other].zombie) + danger = MIN(danger, bots_distance3d(point, &bots_infection.players[other].point)); + score = -danger; + } + score += bots_random_real(bot) * 4.0f; + if (score < best_score) { best_score = score; target = *point; found = TRUE; } + } + if (!found || !bots_ctf_set_goal(bot, &target, 1.0f)) return FALSE; + bot->guard_until_tick = now + TICKS_PER_SECOND * (8 + bots_random(bot) % 6); + return TRUE; +} diff --git a/port/linux/game/bots_management.inl b/port/linux/game/bots_management.inl new file mode 100644 index 0000000000..901efb15ef --- /dev/null +++ b/port/linux/game/bots_management.inl @@ -0,0 +1,173 @@ +/* Host bot controls, adapted from thelinkin3000/halo-ce-universal +d92cc933's add/drop commands, built on BirchWoodGod's OpenCE bots. +Included by network_server_manager.c because the server record and its +join/quit dispatch are private there. Clients use ordinary player messages. */ +static long bots_reuse_after[BOTS_MAXIMUM]; +static void bots_population_map_reset(void); + +void bots_management_reset(void) +{ + csmemset(bots_reuse_after, 0, sizeof(bots_reuse_after)); + bots_population_map_reset(); +} + +static boolean bots_lobby_slots_available(struct network_game_server *server) +{ + long index; + /* Include connected machines that have not admitted a player yet. */ + for (index = 0; index < MAXIMUM_NETWORK_MACHINE_COUNT; index++) + if (bots_machine_is_bot(server->client_machines[index].machine_index)) + return FALSE; + for (index = 0; index < MAXIMUM_NETWORK_PLAYER_COUNT; index++) + { + struct network_player *player = &server->game.players[index]; + if (network_player_is_valid(player) && bots_machine_is_bot(player->machine_index) && + !bots_player_owned(player->machine_index)) + return FALSE; + } + return TRUE; +} + +int bots_lobby_settings_apply(char *status, long size) +{ + struct network_game_server *server = global_network_game_server_get(); + int enabled = config_boolean("bots.network"); + + /* Network policy saved outside pregame remains for the next host. Never change the + bot policy after peers have been told to load, or reset live ownership. */ + if (!server || server->state != _network_game_server_state_pregame || server->sent_start_game_message) + return TRUE; + if (!network_game_is_splitscreen_local()) + { + if (enabled && !bots_network_reserved() && !bots_lobby_slots_available(server)) + { + snprintf(status, size, "A player connection holds a bot slot. Re-host with Network Bots enabled."); + return FALSE; + } + bots_network_lobby_enable(enabled); + } + network_game_server_port_bots(server); + return TRUE; +} + +static int bots_manage_change(int add, int team, char *status, long size) +{ + struct network_game_server *server = global_network_game_server_get(); + long index, slot, chosen = NONE; + long teams[2] = { 0, 0 }; + boolean occupied[BOTS_MAXIMUM] = { FALSE }; + struct network_player player; + + if (!server) + { + snprintf(status, size, "Only the host can manage bots."); + return FALSE; + } + if (server->state != _network_game_server_state_ingame) + { + snprintf(status, size, "During a match, add or remove bots here. In the lobby, set Bot Count."); + return FALSE; + } + if (!bots_session_allowed()) + { + snprintf(status, size, "Enable Network Bots in the lobby before starting the match."); + return FALSE; + } + if (!bots_gametype_active(server->game.variant.game_engine_index)) + { + snprintf(status, size, "Bots support Slayer, plus CTF/King with Enhanced Bots enabled before loading."); + return FALSE; + } + if (team < NONE || team > 1 || (team != NONE && !game_engine_has_teams())) + { + snprintf(status, size, "Choose Any Team in a game without teams."); + return FALSE; + } + for (slot = 0; slot < MAXIMUM_NETWORK_PLAYER_COUNT; slot++) + { + struct network_player *entry = &server->game.players[slot]; + if (!network_player_is_valid(entry)) continue; + if (entry->team_index >= 0 && entry->team_index < 2) teams[entry->team_index]++; + if (bots_machine_is_bot(entry->machine_index)) + occupied[entry->machine_index - BOTS_FIRST_MACHINE] = TRUE; + if (bots_player_owned(entry->machine_index) && (team == NONE || entry->team_index == team) && + (chosen == NONE || entry->machine_index > server->game.players[chosen].machine_index)) + chosen = slot; + } + if (add) + { + void *message; + for (index = 0; index < BOTS_MAXIMUM; index++) + if (!occupied[index] && game_time_get() >= bots_reuse_after[index]) break; + if (index == BOTS_MAXIMUM || server->game.player_count >= server->game.maximum_players) + { + snprintf(status, size, "No free bot slot. A departing bot needs a moment to leave."); + return FALSE; + } + bots_network_player(index, &player); + player.team_index = (char)(team != NONE ? team : game_engine_has_teams() && teams[1] < teams[0] ? 1 : 0); + get_unique_random_color(server, &player); + if (!network_game_add_player(&server->game, &player)) + { + snprintf(status, size, "The game is full."); + return FALSE; + } + /* Admission chooses the authoritative player slot. Encode that slot, + then publish; failed encoding can still undo this unannounced record. */ + message = create_network_game_message(_message_server_add_player_ingame, &player, sizeof(player)); + if (!message) + { + network_game_remove_player(&server->game, &player); + snprintf(status, size, "Could not prepare the bot's join."); + return FALSE; + } + bots_player_ownership(player.machine_index, TRUE); + if (!network_game_server_send_message_to_all_machines(server, message)) + network_event("bots: could not send a player's join to every machine"); + snprintf(status, size, "Bot %ld added.", index + 1); + } + else + { + struct message_server_remove_player_ingame removal; + void *message; + if (chosen == NONE) + { + snprintf(status, size, "No bot on the selected team."); + return FALSE; + } + player = server->game.players[chosen]; + removal.player = player; + removal.reason = game_time_get() + NETWORK_GAME_PLAYER_QUIT_DELAY; + message = create_network_game_message(_message_server_remove_player_ingame, &removal, sizeof(removal)); + if (!message) + { + snprintf(status, size, "Could not prepare the bot's departure."); + return FALSE; + } + if (!network_game_remove_player(&server->game, &player)) + { + snprintf(status, size, "The bot could not leave."); + return FALSE; + } + index = player.machine_index - BOTS_FIRST_MACHINE; + /* Existing quit messages take effect at a future tick. Do not assign + that identity to a replacement while peers still have its old player. */ + bots_reuse_after[index] = removal.reason + 1; + bots_player_ownership(player.machine_index, FALSE); + if (!network_game_server_send_message_to_all_machines(server, message)) + network_event("bots: could not send a player's departure to every machine"); + snprintf(status, size, "Bot %ld removed.", index + 1); + } + network_event("bots: %s", status); + return TRUE; +} + +int bots_manage(int add, int team, char *status, long size) +{ + struct network_game_server *server = global_network_game_server_get(); + int result; + if (server) bots_population_wanted(&server->game); + result = bots_manage_change(add, team, status, size); + if (result) bots_population_changed(&server->game, add ? 1 : -1); + return result; +} diff --git a/port/linux/game/bots_menu.inl b/port/linux/game/bots_menu.inl new file mode 100644 index 0000000000..8638435eff --- /dev/null +++ b/port/linux/game/bots_menu.inl @@ -0,0 +1,54 @@ +/* CE-style bot controls. Bot settings apply host policy only on OK; +ordinary settings keep the existing load/save and cancellation behavior. */ +#include "bots.h" + +static boolean bots_menu_event(struct widget_instance *widget, char const *event) +{ + static char const *const names[] = { "op_add_any", "op_add_red", "op_add_blue", + "op_drop_any", "op_drop_red", "op_drop_blue" }; + /* Deferred error dialogs retain the pointer until the next UI update. */ + static wchar_t error_message[180]; + char status[180]; + wchar_t message[180]; + long index, character; + struct widget_instance *list; + + if (!strcmp(event, "port bots settings save")) + { + settings_each(screen_of(widget), setting_changed_save); + if (!bots_lobby_settings_apply(status, sizeof(status))) + { + for (character = 0; status[character] && character < (long)NUMBEROF(error_message) - 1; character++) + error_message[character] = (wchar_t)(unsigned char)status[character]; + error_message[character] = 0; + display_error_text_deferred(error_message, NONE); + } + return TRUE; + } + + if (!strcmp(event, "port bots init")) + { + /* This description has no string list: rendering must retain its + owned text buffer rather than replacing it with a static caption. */ + text_set(widget, L"Host only. Add/remove during a match;\nuse Bot Count in the lobby."); + return TRUE; + } + if (!strcmp(event, "port bots host entry")) + { + widget->visible = global_network_game_server_get() != NULL; + return TRUE; + } + for (index = 0; index < (long)NUMBEROF(names); index++) + if (!strcmp(widget->name, names[index])) + { + bots_manage(index < 3, index % 3 - 1, status, sizeof(status)); + for (character = 0; status[character] && character < (long)NUMBEROF(message) - 1; character++) + message[character] = (wchar_t)(unsigned char)status[character]; + message[character] = 0; + /* A column list owns its description separately from its children. */ + list = named(screen_of(widget), "options_menu", 0); + text_set(list ? list->parameters.list.extended_description : NULL, message); + return TRUE; + } + return FALSE; +} diff --git a/port/linux/game/bots_navigation.inl b/port/linux/game/bots_navigation.inl new file mode 100644 index 0000000000..7b6775de8a --- /dev/null +++ b/port/linux/game/bots_navigation.inl @@ -0,0 +1,548 @@ +/* Enhanced navigation adapted from BirchWoodGod/halo-ce-vita, via +thelinkin3000/halo-ce-universal 18a94774a73ca275e9c0ab4f281e492ad8bb656e. +Derived navigation retains GPL-3.0-only; see the provenance guide. + +Included by enhanced_bots_controller.c to share its bounded path search and geometry readers. +Links belong to this map, reservations to a bot's life. Only ordinary player +controls traverse them; neither the level's graph nor teleport rules change. */ +#define BOTS_NAV_LINKS 64 +enum { _bots_nav_none, _bots_nav_exit, _bots_nav_entry, _bots_nav_going }; +struct bots_nav_link +{ + real_point3d entrance, exit; + long entrance_surface, exit_surface; + boolean ladder; + real climb_direction, top; + long failures, successes, rest_until; +}; +static struct +{ + long count; + struct bots_nav_link links[BOTS_NAV_LINKS]; + byte *vehicle_walkable; + struct structure_bsp vehicle_structure; + long obstacle_tick; + struct bots_nav_route + { + short phase, link; + real_point3d goal; + real walk, entrance_cost, exit_cost; + long next_weigh, deadline, on_link, climb_tick, top_tick; + } routes[BOTS_MAXIMUM]; +} bots_navigation; + +static void bots_navigation_reset(void) +{ + if (bots_navigation.vehicle_walkable) free(bots_navigation.vehicle_walkable - 1); + csmemset(&bots_navigation, 0, sizeof(bots_navigation)); +} + +static void bots_navigation_close_surface(long surface) +{ + if (bots_navigation.vehicle_walkable && surface >= 0 && + surface < bots_navigation.vehicle_structure.pathfinding_surfaces.count) + bots_navigation.vehicle_walkable[surface] &= (byte)~FLAG(BOTS_PATHFINDING_WALKABLE_BIT); +} + +static struct structure_bsp *bots_navigation_vehicle_structure(void) +{ + long count; + if (!bots_paths_copy()) return NULL; + if (!bots_navigation.vehicle_walkable) + { + count = bots_paths.structure.pathfinding_surfaces.count; + bots_navigation.vehicle_walkable = (byte *)malloc((size_t)count + 1); + if (!bots_navigation.vehicle_walkable) return NULL; + /* path.c reads surface NONE at open edges. Supply a closed sentinel. */ + *bots_navigation.vehicle_walkable++ = 0; + csmemcpy(bots_navigation.vehicle_walkable, bots_paths.walkable, (size_t)count); + bots_navigation.vehicle_structure = bots_paths.structure; + bots_navigation.vehicle_structure.pathfinding_surfaces.address = bots_navigation.vehicle_walkable; + } + return &bots_navigation.vehicle_structure; +} + +void bots_vehicle_obstacle(long vehicle_index, real_point3d const *goal) +{ + struct object_datum *vehicle = object_try_and_get_and_verify_type(vehicle_index, _object_mask_vehicle); + struct collision_result hit; + real_vector3d vector; + real_point3d start; + real reach; + long now = game_time_get(), index; + unsigned long flags = FLAG(_collision_test_structure_bit) | FLAG(_collision_test_front_facing_surfaces_bit) | + FLAG(_collision_test_objects_bit) | FLAG(_collision_test_objects_scenery_bit) | FLAG(_collision_test_objects_machines_bit); + if (!vehicle || bots_navigation.obstacle_tick == now) return; + bots_navigation.obstacle_tick = now; + reach = MAX(2.5f, vehicle->object.bounding_sphere_radius + 0.6f); + vector.i = vehicle->object.forward.i * reach; + vector.j = vehicle->object.forward.j * reach; + vector.k = vehicle->object.forward.k * reach; + start = vehicle->object.position; + start.z += 0.25f; + if (!collision_test_vector(flags, &vehicle->object.bounding_sphere_center, &vector, vehicle_index, &hit) && + !collision_test_vector(flags, &start, &vector, vehicle_index, &hit)) return; + /* Completed and in-flight routes through this obstruction are stale. */ + for (index = 0; index < BOTS_MAXIMUM; index++) + if (bots_globals.bots[index].navigation_parent == vehicle_index) + { + bots_globals.bots[index].path.valid = FALSE; + bots_globals.bots[index].path_tick = now - TICKS_PER_SECOND; + bots_globals.bots[index].goal_serial++; + } + if (hit.type == _collision_result_object) + bots_paths_learn(&vehicle->object.position, goal); + else if (hit.type == _collision_result_structure && bots_navigation_vehicle_structure()) + { + struct collision_bsp const *bsp = TAG_BLOCK_GET_ELEMENT(&bots_paths.structure.collision_bsp, 0, struct collision_bsp); + long surface, closed = 0; + real about = MAX(1.5f, vehicle->object.bounding_sphere_radius); + for (surface = 0; surface < bsp->surfaces.count; surface++) + { + real_point3d corners[BOTS_SURFACE_CORNERS], middle; + real radius; + long count; + if (!bots_paths_walkable_surface(bsp, surface, corners, &count, &middle, &radius) || + !TEST_FLAG(bots_navigation.vehicle_walkable[surface], BOTS_PATHFINDING_WALKABLE_BIT)) continue; + if (bots_distance2d(&middle, &hit.point) < about && fabs(middle.z - hit.point.z) < 2.5f && + bots_distance2d(&middle, &vehicle->object.position) > 1.2f && bots_distance2d(&middle, goal) > 3.0f) + { + bots_navigation_close_surface(surface); + closed++; + } + } + if (closed) platform_log("bots: learned %ld blocked surfaces for vehicles", closed); + } +} + +static void bots_navigation_reset_bot(long index) +{ + csmemset(&bots_navigation.routes[index], 0, sizeof(bots_navigation.routes[index])); +} + +static boolean bots_navigation_climbing(struct bots_bot *bot) +{ + struct bots_nav_route *route = &bots_navigation.routes[bot - bots_globals.bots]; + return route->phase == _bots_nav_going && route->climb_tick != 0; +} + +static boolean bots_navigation_pays(real walk, real through) +{ + return through <= walk * 0.8f && walk - through >= 15.0f; +} + +static real bots_navigation_cost(struct path_state *state, long surface, real_point3d const *point) +{ + short node = surface == NONE ? NONE : path_node_from_hash_table(state, surface); + if (node < 0 || node >= state->node_count) return -1.0f; + return state->node_list[node].path_distance_from_origin + + bots_distance3d(&state->node_list[node].entry_point, point); +} + +static real bots_navigation_remaining(struct path_state *state) +{ + long node = state->closest_node_index; + if (node < 0 || node >= state->node_count) return -1.0f; + return state->node_list[node].path_distance_from_origin + state->closest_distance; +} + +static void bots_navigation_drop(struct bots_bot *bot, boolean failed) +{ + struct bots_nav_route *route = &bots_navigation.routes[bot - bots_globals.bots]; + if (route->phase == _bots_nav_none) return; + if (failed) + { + struct bots_nav_link *link = &bots_navigation.links[route->link]; + link->failures++; + link->rest_until = game_time_get() + 30 * TICKS_PER_SECOND; + platform_log("bots: navigation link %d failed; resting for 30 seconds", route->link + 1); + } + route->phase = _bots_nav_none; + route->next_weigh = game_time_get() + 5 * TICKS_PER_SECOND; + bot->path.valid = FALSE; + bot->path_tick = game_time_get() - TICKS_PER_SECOND; +} + +static long bots_navigation_claimers(long link) +{ + long index, count = 0; + for (index = 0; index < BOTS_MAXIMUM; index++) + if (bots_navigation.routes[index].phase != _bots_nav_none && bots_navigation.routes[index].link == link) + count++; + return count; +} + +/* Keep a goal's normal path while measuring the exit. Every measurement +uses the same per-tick budget as a normal search, including failed ones. */ +static boolean bots_navigation_query(struct bots_bot *bot, real_point3d *start, long *start_surface, + real_point3d *goal, long *goal_surface) +{ + struct bots_nav_route *route = &bots_navigation.routes[bot - bots_globals.bots]; + struct bots_nav_link *link; + if (route->phase == _bots_nav_none) return FALSE; + if (bots_distance3d(&route->goal, &bot->goal_point) > 8.0f) + { + bots_navigation_drop(bot, FALSE); + return FALSE; + } + link = &bots_navigation.links[route->link]; + if (route->phase == _bots_nav_exit) + { + *start = link->exit; + *start_surface = link->exit_surface; + } + else + { + *goal = link->entrance; + *goal_surface = link->entrance_surface; + } + return TRUE; +} + +/* TRUE consumes a measuring answer without replacing the bot's current +path. An accepted entrance answer becomes its path through the usual code. */ +static boolean bots_navigation_answer(struct bots_bot *bot, struct path_state *state, + real_point3d const *start, boolean reached, boolean waypoint, real radius) +{ + long bot_index = (long)(bot - bots_globals.bots), now = game_time_get(); + struct bots_nav_route *route = &bots_navigation.routes[bot_index]; + struct bots_tactics_bot const *tactics = &bots_tactics_bots[bot_index]; + long index, best = NONE; + real walk, best_cost = REAL_MAX, best_entrance = 0.0f; + boolean exhausted = state->node_count < PATH_NODE_LIST_SIZE && state->heap_count <= 1; + if (route->phase == _bots_nav_exit) + { + real beyond = bots_navigation_cost(state, bot->goal_surface_index, &bot->goal_point); + if (beyond < 0.0f && !exhausted) beyond = bots_navigation_remaining(state); + if (beyond < 0.0f || !bots_navigation_pays(route->walk, route->entrance_cost + beyond)) + bots_navigation_drop(bot, FALSE); + else + { + route->exit_cost = beyond; + route->phase = _bots_nav_entry; + } + bot->path_tick = now - 4 * TICKS_PER_SECOND - 1; + return TRUE; + } + if (route->phase == _bots_nav_entry || route->phase == _bots_nav_going) + { + struct bots_nav_link *link = &bots_navigation.links[route->link]; + real entrance = bots_navigation_cost(state, link->entrance_surface, &link->entrance); + if ((!reached && exhausted) || (reached && route->walk >= 0.0f && + !bots_navigation_pays(route->walk, entrance + route->exit_cost))) + { + bots_navigation_drop(bot, !reached); + return TRUE; + } + if (route->phase == _bots_nav_entry) + { + route->phase = _bots_nav_going; + route->deadline = now + (long)((8.0f + MAX(entrance, route->entrance_cost) / 1.5f) * TICKS_PER_SECOND); + platform_log("bots: bot %ld taking %s %d", bot_index + 1, link->ladder ? "ladder" : "teleporter", route->link + 1); + } + return FALSE; + } + if (waypoint || radius > BOTS_PATH_RADIUS || now < route->next_weigh || + bot->goal_kind == _bots_goal_item || bot->goal_kind == _bots_goal_vehicle) return FALSE; + route->next_weigh = now + 5 * TICKS_PER_SECOND; + walk = bots_navigation_cost(state, bot->goal_surface_index, &bot->goal_point); + if (walk < 0.0f && !exhausted) walk = bots_navigation_remaining(state); + for (index = 0; index < bots_navigation.count; index++) + { + struct bots_nav_link *link = &bots_navigation.links[index]; + real entrance, beyond, through; + if (now < link->rest_until || (link->failures >= 3 && !link->successes) || + bots_navigation_claimers(index) >= 2 || bots_distance3d(start, &link->exit) < 2.0f) continue; + entrance = bots_navigation_cost(state, link->entrance_surface, &link->entrance); + beyond = bots_distance3d(&link->exit, &bot->goal_point); + if (walk < 0.0f) + { + /* A disconnected floor: take a reachable link that makes progress, + then search again on the other side (including chains of links). */ + if (entrance < 0.0f || beyond >= state->closest_distance - 2.0f) continue; + } + else if (link->ladder || tactics->role == _bots_role_defender || + (tactics->lane && !tactics->lane_given_up)) continue; + if (entrance < 0.0f) entrance = bots_distance3d(start, &link->entrance); + through = entrance + beyond; + if (walk >= 0.0f && !bots_navigation_pays(walk, through)) continue; + if (through < best_cost) { best = index; best_cost = through; best_entrance = entrance; } + } + if (best != NONE) + { + route->link = (short)best; + route->goal = bot->goal_point; + route->walk = walk; + route->entrance_cost = best_entrance; + route->phase = walk >= 0.0f ? _bots_nav_exit : _bots_nav_entry; + route->deadline = now + 10 * TICKS_PER_SECOND; + route->on_link = route->climb_tick = route->top_tick = 0; + } + return FALSE; +} + +static void bots_navigation_update(struct bots_bot *bot, real_point3d const *position, boolean riding) +{ + struct bots_nav_route *route = &bots_navigation.routes[bot - bots_globals.bots]; + struct bots_nav_link *link; + long now = game_time_get(); + if (route->phase == _bots_nav_none) return; + link = &bots_navigation.links[route->link]; + /* Fighting can hold a bot off its route. Charge only travel time to + the approach deadline; climbing itself still has a bounded timeout. */ + if (!route->climb_tick && bot->target_player_index != NONE && + now - bot->target_seen_tick <= TICKS_PER_SECOND / 2) + { + route->deadline++; + if (route->on_link) route->on_link++; + } + if (!link->ladder && bots_distance3d(position, &bot->last_position) > 3.0f && + bots_distance3d(position, &link->exit) < 4.0f) + { + link->successes++; + platform_log("bots: bot %ld completed teleporter %d", (long)(bot - bots_globals.bots) + 1, route->link + 1); + bots_navigation_drop(bot, FALSE); + return; + } + if (riding || bot->goal_kind == _bots_goal_none || bot->goal_kind == _bots_goal_item || + bot->goal_kind == _bots_goal_vehicle || bots_distance3d(&route->goal, &bot->goal_point) > 8.0f) + bots_navigation_drop(bot, FALSE); + else if (now > route->deadline) + bots_navigation_drop(bot, TRUE); +} + +/* At a link, finish the approach without asking the floor graph to cross +the gap. A ladder uses the biped's ordinary facing-and-forward climbing. */ +static boolean bots_navigation_follow(struct bots_bot *bot, real_point3d const *position, real *direction) +{ + struct bots_nav_route *route = &bots_navigation.routes[bot - bots_globals.bots]; + struct bots_nav_link *link; + long now = game_time_get(); + real_point3d const *target; + if (route->phase != _bots_nav_going) return FALSE; + link = &bots_navigation.links[route->link]; + if (bots_distance3d(position, &link->entrance) > 1.0f && !route->climb_tick) return FALSE; + bot->path.valid = FALSE; + bot->climb_until_tick = 0; + if (!route->on_link) route->on_link = now; + target = &link->entrance; + if (link->ladder) + { + /* Stock bipeds climbed about 0.48 units/second in Boarding Action. + Allow three seconds per unit, with bounded approach and landing slack. */ + long climb_ticks = (long)(MIN(60.0f, MAX(8.0f, 3.0f * (link->top - link->entrance.z))) * TICKS_PER_SECOND); + if (!route->climb_tick && bots_distance2d(position, target) < 0.35f) + { + route->climb_tick = now; + route->deadline = now + climb_ticks + 2 * TICKS_PER_SECOND; + } + if (route->climb_tick) + { + if (position->z < link->top - 0.25f && !route->top_tick) + { + if (now - route->climb_tick > climb_ticks) bots_navigation_drop(bot, TRUE); + *direction = link->climb_direction; + return route->phase != _bots_nav_none; + } + if (!route->top_tick) route->top_tick = now; + target = &link->exit; + if (bots_distance2d(position, target) < 0.4f) + { + link->successes++; + platform_log("bots: bot %ld completed ladder %d", (long)(bot - bots_globals.bots) + 1, route->link + 1); + bots_navigation_drop(bot, FALSE); + return FALSE; + } + if (now - route->top_tick > 2 * TICKS_PER_SECOND) + { + bots_navigation_drop(bot, TRUE); + return FALSE; + } + } + } + else if (now - route->on_link > 2 * TICKS_PER_SECOND) + { + bots_navigation_drop(bot, TRUE); + return FALSE; + } + *direction = (real)atan2(target->y - position->y, target->x - position->x); + return TRUE; +} + +static void bots_navigation_action(struct bots_bot *bot, struct player_action *action) +{ + struct bots_nav_route *route = &bots_navigation.routes[bot - bots_globals.bots]; + if (route->phase == _bots_nav_going && route->climb_tick && !route->top_tick) + { + action->desired_facing.yaw = bots_navigation.links[route->link].climb_direction; + action->desired_facing.pitch = 0.0f; + action->throttle.i = 1.0f; + action->throttle.j = 0.0f; + action->primary_trigger = 0.0f; + action->control_flags &= ~FLAG(_unit_control_weapon_primary_trigger_bit); + if ((game_time_get() - route->climb_tick) % 15 == 0) + action->control_flags |= FLAG(_unit_control_jump_bit); + } +} + +static void bots_navigation_ladders(struct collision_bsp const *bsp); + +static void bots_navigation_prepare(void) +{ + struct scenario *scenario = global_scenario_get(); + struct structure_bsp *structure = global_structure_bsp_get(); + long source_index; + bots_navigation_reset(); + if (!scenario || !structure) return; + for (source_index = 0; source_index < scenario->netgame_flags.count && bots_navigation.count < BOTS_NAV_LINKS; source_index++) + { + struct scenario_netgame_flag *source = TAG_BLOCK_GET_ELEMENT(&scenario->netgame_flags, source_index, struct scenario_netgame_flag); + long target_index; + if (source->type != _netgame_flag_teleporter_source) continue; + for (target_index = 0; target_index < scenario->netgame_flags.count; target_index++) + { + struct scenario_netgame_flag *target = TAG_BLOCK_GET_ELEMENT(&scenario->netgame_flags, target_index, struct scenario_netgame_flag); + struct bots_nav_link *link = &bots_navigation.links[bots_navigation.count]; + if (target->type != _netgame_flag_teleporter_target || target->team_index != source->team_index) continue; + link->entrance_surface = bots_surface_below(&source->position, &link->entrance); + link->exit_surface = bots_surface_below(&target->position, &link->exit); + if (link->entrance_surface != NONE && link->exit_surface != NONE) bots_navigation.count++; + /* Match game_engine_update_teleporter: the first exit on a channel wins. */ + break; + } + } + if (structure->collision_bsp.count > 0) + bots_navigation_ladders(TAG_BLOCK_GET_ELEMENT(&structure->collision_bsp, 0, struct collision_bsp)); + platform_log("bots: enhanced navigation prepared %ld teleporter/ladder links", bots_navigation.count); +} + +#define BOTS_MAXIMUM_LADDER_PIECES 128 +static void bots_navigation_ladders(struct collision_bsp const *bsp) +{ + struct + { + real_point3d middle; + real_vector3d normal; + real low, high; + } pieces[BOTS_MAXIMUM_LADDER_PIECES]; + long piece_count = 0, surface_index, index; + + for (surface_index = 0; surface_index < bsp->surfaces.count; surface_index++) + { + real_point3d corners[BOTS_SURFACE_CORNERS], middle = { 0.0f, 0.0f, 0.0f }; + real_vector3d a, b, normal; + real low = REAL_MAX, high = -REAL_MAX, length; + long corner, count; + + if (!TEST_FLAG(TAG_BLOCK_GET_ELEMENT(&bsp->surfaces, surface_index, struct collision_surface)->flags, + 2)) + { + continue; + } + count = bots_surface_corners(bsp, surface_index, corners); + if (count < 3) + continue; + for (corner = 0; corner < count; corner++) + { + middle.x += corners[corner].x / (real)count; + middle.y += corners[corner].y / (real)count; + middle.z += corners[corner].z / (real)count; + low = MIN(low, corners[corner].z); + high = MAX(high, corners[corner].z); + } + vector_from_points3d(&corners[0], &corners[1], &a); + vector_from_points3d(&corners[0], &corners[2], &b); + cross_product3d(&a, &b, &normal); + normal.k = 0.0f; + length = magnitude3d(&normal); + /* (upright, and a metre high at least) */ + if (length < 0.0001f || high - low < 0.3f) + continue; + normal.i /= length; + normal.j /= length; + /* (a piece over or under one, or its other face: the one ladder) */ + for (index = 0; index < piece_count; index++) + { + if (bots_distance2d(&pieces[index].middle, &middle) < 0.5f && + fabs(pieces[index].normal.i * normal.i + pieces[index].normal.j * normal.j) > 0.9f && + low <= pieces[index].high + 0.1f && high >= pieces[index].low - 0.1f) + { + pieces[index].low = MIN(pieces[index].low, low); + pieces[index].high = MAX(pieces[index].high, high); + break; + } + } + if (index < piece_count || piece_count >= BOTS_MAXIMUM_LADDER_PIECES) + continue; + pieces[piece_count].middle = middle; + pieces[piece_count].normal = normal; + pieces[piece_count].low = low; + pieces[piece_count].high = high; + piece_count++; + } + for (index = 0; index < piece_count && bots_navigation.count < BOTS_NAV_LINKS; index++) + { + long teleporter = bots_navigation.count; + real_point3d foot = { 0.0f, 0.0f, 0.0f }, landing = { 0.0f, 0.0f, 0.0f }, ground; + long foot_surface = NONE, landing_surface = NONE; + real side, foot_side = 0.0f; + + for (side = -1.0f; side <= 1.0f; side += 2.0f) + { + real_point3d point; + long surface; + + point.x = pieces[index].middle.x + pieces[index].normal.i * side * 0.4f; + point.y = pieces[index].middle.y + pieces[index].normal.j * side * 0.4f; + point.z = pieces[index].low + 0.3f; + surface = bots_surface_below(&point, &ground); + if (foot_surface == NONE && surface != NONE && fabs(ground.z - pieces[index].low) < 0.35f) + { + foot_surface = surface; + foot = ground; + foot_side = side; + } + } + /* (the landing beyond the top first, as a ladder up a wall's face + goes over it; else on the same side, a ladder up to a ledge) */ + for (side = -1.0f; side <= 1.0f && foot_surface != NONE; side += 2.0f) + { + real_point3d point; + long surface; + real way = side * foot_side; + + point.x = pieces[index].middle.x + pieces[index].normal.i * way * 0.6f; + point.y = pieces[index].middle.y + pieces[index].normal.j * way * 0.6f; + point.z = pieces[index].high + 0.5f; + surface = bots_surface_below(&point, &ground); + if (landing_surface == NONE && surface != NONE && fabs(ground.z - pieces[index].high) < 0.5f) + { + landing_surface = surface; + landing = ground; + } + } + if (bots_trace_enabled()) + { + platform_log("bots: trace ladder at (%.1f %.1f) z %.1f to %.1f normal (%.2f %.2f): foot %s (%.1f %.1f %.1f), " + "landing %s (%.1f %.1f %.1f)", pieces[index].middle.x, pieces[index].middle.y, pieces[index].low, + pieces[index].high, pieces[index].normal.i, pieces[index].normal.j, foot_surface != NONE ? "yes" : "no", + foot.x, foot.y, foot.z, landing_surface != NONE ? "yes" : "no", landing.x, landing.y, landing.z); + } + if (foot_surface == NONE || landing_surface == NONE) + continue; + /* Ladders bridge disconnected floors; they are not fast-travel shortcuts. */ + csmemset(&bots_navigation.links[teleporter], 0, sizeof(bots_navigation.links[teleporter])); + bots_navigation.links[teleporter].exit_surface = landing_surface; + bots_navigation.links[teleporter].entrance = foot; + bots_navigation.links[teleporter].entrance_surface = foot_surface; + bots_navigation.links[teleporter].exit = landing; + bots_navigation.links[teleporter].ladder = TRUE; + /* (facing it from its foot) */ + bots_navigation.links[teleporter].climb_direction = + (real)atan2(-pieces[index].normal.j * foot_side, -pieces[index].normal.i * foot_side); + bots_navigation.links[teleporter].top = pieces[index].high; + bots_navigation.links[teleporter].successes = 0; + bots_navigation.links[teleporter].failures = 0; + bots_navigation.count++; + } +} diff --git a/port/linux/game/bots_network.c b/port/linux/game/bots_network.c new file mode 100644 index 0000000000..509e2826c5 --- /dev/null +++ b/port/linux/game/bots_network.c @@ -0,0 +1,179 @@ +/* Host-owned bot admission and input replication. The session uses ordinary +player records and actions; unmodified OpenCE clients need no bot logic. +Once enabled, the machine reservation lasts until the host closes. */ +#include "cseries.h" +#include "game/game.h" +#include "game/game_engine.h" +#include "game/players.h" +#include "memory/data.h" +#include "game/player_queues_new.h" +#include "networking/network_game_globals.h" +#include "networking/network_game_manager.h" +#include "bots.h" +#include "main/console.h" +#include + +int config_boolean(const char *name); + +static int network_bots; +static int network_bots_enabled; +static byte owned[BOTS_MAXIMUM]; +static long population_target = -1; +static long population_configured = -1; +static long population_limit; + +int bots_console_command(char const *expression) +{ + static char const *const commands[] = { "add_bot", "add_bot_red", "add_bot_blue", + "drop_bot", "drop_bot_red", "drop_bot_blue" }; + char command[32], extra, status[180]; + long index; + int result; + if (sscanf(expression, " %31s %c", command, &extra) != 1) return -1; + for (index = 0; index < (long)NUMBEROF(commands); index++) + if (!strcmp(command, commands[index])) + { + result = bots_manage(index < 3, index % 3 - 1, status, sizeof(status)); + console_printf(TRUE, "%s", status); + return result; + } + return -1; +} + +void bots_network_session_begin(void) +{ + bots_management_reset(); + population_target = population_configured = -1; + network_bots = config_boolean("bots.network"); + network_bots_enabled = network_bots; + csmemset(owned, 0, sizeof(owned)); +} + +void bots_network_session_end(void) +{ + bots_management_reset(); + population_target = population_configured = -1; + network_bots = FALSE; + network_bots_enabled = FALSE; + csmemset(owned, 0, sizeof(owned)); +} + +void bots_player_ownership(long machine_index, int present) +{ + if (bots_machine_is_bot(machine_index)) + owned[machine_index - BOTS_FIRST_MACHINE] = present != 0; +} + +int bots_player_owned(long machine_index) +{ + return bots_machine_is_bot(machine_index) && owned[machine_index - BOTS_FIRST_MACHINE]; +} + +int bots_network_reserved(void) +{ + return network_bots; +} + +int bots_session_allowed(void) +{ + return global_network_game_server_get() && (network_game_is_splitscreen_local() || network_bots_enabled); +} + +/* Called only after the lobby has checked that no human holds a bot ID. +Keep the reservation when disabled: peers may still be processing removals. */ +void bots_network_lobby_enable(int enabled) +{ + if (network_bots_enabled != (enabled != 0)) + population_target = population_configured = -1; + network_bots_enabled = enabled != 0; + if (enabled) network_bots = TRUE; +} + +long bots_human_count(struct network_game *game) +{ + long index, count = 0; + for (index = 0; game && index < (long)NUMBEROF(game->players); index++) + if (network_player_is_valid(&game->players[index]) && + !bots_player_owned(game->players[index].machine_index)) + count++; + return count; +} + +/* The first admitted humans and the requested bots establish the session's +population. Later humans replace bots, including across successive maps. +Changing Bot Count deliberately establishes a new target from this lobby. */ +long bots_population_wanted(struct network_game *game) +{ + long humans = bots_human_count(game); + long configured = bots_wanted_count(); + if (network_game_is_splitscreen_local()) + return configured; + if (!bots_session_allowed()) + return 0; + if (humans > 0 && (population_target < 0 || population_configured != configured)) + { + population_configured = configured; + population_limit = configured; + population_target = MIN(game->maximum_players, humans + configured); + } + return population_target < 0 ? 0 : + MAX(0, MIN(population_limit, MIN(population_target, game->maximum_players) - humans)); +} + +void bots_population_changed(struct network_game *game, int change) +{ + if (network_game_is_splitscreen_local() || !bots_session_allowed()) + return; + bots_population_wanted(game); + /* Humans may have grown past the original target. An explicit addition + must retain the bot just admitted rather than immediately removing it. */ + population_target = PIN(MAX(population_target + change, game->player_count), 0, game->maximum_players); + population_limit = PIN(population_limit + change, 0, BOTS_MAXIMUM); +} + +long bots_population_after_join(struct network_game *game) +{ + bots_population_wanted(game); + return population_target < 0 ? 0 : MAX(0, + MIN(population_limit, MIN(population_target, game->maximum_players) - bots_human_count(game) - 1)); +} + +int bots_lobby_can_start(struct network_game *game) +{ + long index; + short human_machine = NONE; + int has_bot = FALSE; + if (!game || !bots_session_allowed()) return FALSE; + /* Synthetic players have distinct machine IDs, but no connections. Only + owned bots may extend the lone human machine's countdown permission. */ + for (index = 0; index < (long)NUMBEROF(game->players); index++) + { + struct network_player *player = &game->players[index]; + if (!network_player_is_valid(player)) continue; + if (bots_player_owned(player->machine_index)) + has_bot = TRUE; + else if (human_machine == NONE) + human_machine = player->machine_index; + else if (human_machine != player->machine_index) + return FALSE; + } + return has_bot && human_machine != NONE; +} + +void bots_network_record_actions(struct player_action *actions) +{ + struct data_iterator iterator; + struct player_datum *player; + if (!game_engine_running() || !bots_session_allowed() || network_game_is_splitscreen_local()) + return; + data_iterator_new(&iterator, player_data); + while ((player = (struct player_datum *)data_iterator_next(&iterator)) != NULL) + { + if (player->local_player_index == NONE && bots_player_owned(player->network_player_data.machine_index)) + { + long index = DATUM_INDEX_TO_ABSOLUTE_INDEX(iterator.datum_index); + if (index >= 0 && index < HALO_PORT_MAXIMUM_NETWORK_PLAYERS) + update_server_note_bot_action((short)index, &actions[index]); + } + } +} diff --git a/port/linux/game/bots_objectives.h b/port/linux/game/bots_objectives.h new file mode 100644 index 0000000000..12625efdfc --- /dev/null +++ b/port/linux/game/bots_objectives.h @@ -0,0 +1,12 @@ +/* Read-only engine queries needed by the optional enhanced bots. +The engine owns the flag and moving-hill state; bots never mutate it. */ +#ifndef HALO_BOTS_OBJECTIVES_H +#define HALO_BOTS_OBJECTIVES_H + +boolean game_engine_ctf_flag_state(long team_index, real_point3d *position, + long *carrier_player_index, boolean *at_home, real_point3d *home); +boolean game_engine_king_hill(real_point3d *points, long maximum, long *point_count, + real *bottom, real *top, real_point3d *center, long *hill_id); +boolean game_engine_king_point_on_hill(real_point3d const *position); + +#endif diff --git a/port/linux/game/bots_population.inl b/port/linux/game/bots_population.inl new file mode 100644 index 0000000000..a87ae9a52a --- /dev/null +++ b/port/linux/game/bots_population.inl @@ -0,0 +1,148 @@ +/* Host population policy. Included beside bots_management.inl because the +join queue and player message dispatch belong to the private server record. +The wire still carries ordinary player additions and departures. */ +static unsigned long bots_population_wait_started; +static long bots_population_wait_machine = NONE; +static long bots_population_wait_controller = NONE; +static long bots_population_retry_tick; + +static void bots_population_map_reset(void) +{ + bots_population_wait_machine = bots_population_wait_controller = NONE; + bots_population_wait_started = 0; + bots_population_retry_tick = 0; +} + +static boolean bots_population_enabled(struct network_game_server *server) +{ + return server && !network_game_is_splitscreen_local() && bots_session_allowed() && + (server->state == _network_game_server_state_ingame ? + bots_gametype_active(server->game.variant.game_engine_index) : + bots_gametype_allowed(server->game.variant.game_engine_index)); +} + +static long bots_population_count(struct network_game *game) +{ + return game->player_count - bots_human_count(game); +} + +int bots_population_can_join(struct network_game_server *server) +{ + return bots_population_enabled(server) && bots_population_count(&server->game) > 0 && + bots_human_count(&server->game) < server->game.maximum_players; +} + +/* Only a validated, new player can displace a bot. Repeated requests, malformed +controllers and connections that have not joined never reserve population. */ +static boolean bots_population_new_player(struct network_game_server *server, struct network_player *player) +{ + long index; + if (!network_player_is_valid(player) || bots_player_owned(player->machine_index) || + !network_game_server_client_machine_is_joined_to_game(server, + &server->client_machines[player->machine_index])) + return FALSE; + for (index = 0; index < MAXIMUM_NETWORK_PLAYER_COUNT; index++) + if (network_player_is_valid(&server->game.players[index]) && + server->game.players[index].machine_index == player->machine_index && + server->game.players[index].controller_index == player->controller_index) + return FALSE; + return TRUE; +} + +static int bots_population_team(struct network_game_server *server, boolean add) +{ + long index, teams[2] = { 0, 0 }; + if (!game_engine_has_teams()) return NONE; + for (index = 0; index < MAXIMUM_NETWORK_PLAYER_COUNT; index++) + { + struct network_player *player = &server->game.players[index]; + if (!network_player_is_valid(player) || !VALID_INDEX(player->team_index, 2)) continue; + if (bots_teams() == _bots_teams_against && !bots_player_owned(player->machine_index)) + return 1 - player->team_index; + teams[player->team_index]++; + } + return add ? (teams[1] < teams[0] ? 1 : 0) : (teams[1] > teams[0] ? 1 : 0); +} + +static boolean bots_population_remove(struct network_game_server *server) +{ + long index; + char status[180]; + if (server->state == _network_game_server_state_ingame) + { + /* Prefer the larger team, but still yield if its players are all human. */ + if (bots_manage_change(FALSE, bots_population_team(server, FALSE), status, sizeof(status))) + return TRUE; + return bots_manage_change(FALSE, NONE, status, sizeof(status)); + } + for (index = MAXIMUM_NETWORK_PLAYER_COUNT - 1; index >= 0; index--) + { + struct network_player player = server->game.players[index]; + if (network_player_is_valid(&player) && bots_player_owned(player.machine_index) && + network_game_remove_player(&server->game, &player)) + { + bots_player_ownership(player.machine_index, FALSE); + network_game_server_send_game_data_pregame(server); + return TRUE; + } + } + return FALSE; +} + +/* Pregame additions are synchronous; a full lobby can release a bot before +the existing allocator runs. Its next fill observes the admitted human. */ +static void bots_population_pregame_join(struct network_game_server *server, struct network_player *player) +{ + if (server->state == _network_game_server_state_pregame && bots_population_enabled(server) && + bots_population_new_player(server, player) && + bots_population_count(&server->game) > bots_population_after_join(&server->game)) + bots_population_remove(server); +} + +/* A live departure is scheduled at a future tick and its unit may still hold +the datum. Keep this real join queued, for at most ten seconds, until an +ordinary player slot is available. The existing queue handles split screen +and concurrent requests serially; a cancelled machine is checked each time. */ +static boolean bots_population_wait_for_slot(struct network_game_server *server, struct network_player *player) +{ + unsigned long now = system_milliseconds(); + boolean removed = FALSE; + if (!bots_population_enabled(server) || !bots_population_new_player(server, player) || + !network_game_server_machine_may_add_player_ingame(server, player->machine_index)) + return FALSE; + if (bots_population_wait_machine != player->machine_index || + bots_population_wait_controller != player->controller_index) + { + bots_population_wait_machine = player->machine_index; + bots_population_wait_controller = player->controller_index; + bots_population_wait_started = now; + } + if (now - bots_population_wait_started >= 10000UL) return FALSE; + if (bots_population_count(&server->game) > bots_population_after_join(&server->game)) + removed = bots_population_remove(server); + if (network_game_has_free_player_slot(&server->game)) return FALSE; + /* Do not delay an ordinary full-human refusal. A prior bot departure can +still hold its slot even after ownership has been released. */ + return (removed || server->game.player_count < server->game.maximum_players) && + bots_human_count(&server->game) < server->game.maximum_players; +} + +static void bots_population_update(struct network_game_server *server) +{ + long wanted, count, tick; + char status[180]; + if (server->state != _network_game_server_state_ingame || !bots_population_enabled(server)) return; + /* Pending requests take priority over restoration. Map downloaders remain +in the separate held list and do not displace bots until ready to enter. */ + if (server->queued_player_valid || server->waiting_player_count > 0) return; + bots_population_wait_machine = bots_population_wait_controller = NONE; + tick = game_time_get(); + if (tick < bots_population_retry_tick) return; + bots_population_retry_tick = tick + TICKS_PER_SECOND; + wanted = bots_population_wanted(&server->game); + count = bots_population_count(&server->game); + if (count > wanted) + bots_population_remove(server); + else if (count < wanted && network_game_has_free_player_slot(&server->game)) + bots_manage_change(TRUE, bots_population_team(server, TRUE), status, sizeof(status)); +} diff --git a/port/linux/game/bots_powerups.inl b/port/linux/game/bots_powerups.inl new file mode 100644 index 0000000000..881ceb3ecc --- /dev/null +++ b/port/linux/game/bots_powerups.inl @@ -0,0 +1,100 @@ +/* Powerup decisions adapted from BirchWoodGod/halo-ce-vita via +thelinkin3000/halo-ce-universal 18a94774 (GPL-3.0-only). Included by enhanced_bots_controller.c +to reuse its item ownership, unreachable-item memory and path lifecycle. */ +static struct +{ + long next_scan, count, items[32]; +} bots_powerups; + +static void bots_powerups_reset(void) +{ + csmemset(&bots_powerups, 0, sizeof(bots_powerups)); +} + +static boolean bots_powerup_claimed(struct bots_bot *bot, long item_index, real distance) +{ + long other, index = (long)(bot - bots_globals.bots); + for (other = 0; other < BOTS_MAXIMUM; other++) + { + struct bots_bot *claim = &bots_globals.bots[other]; + if (other != index && claim->unit_index != NONE && claim->goal_kind == _bots_goal_item && + claim->powerup_index == item_index && (claim->powerup_distance < distance || + (claim->powerup_distance == distance && other < index))) return TRUE; + } + return FALSE; +} + +static boolean bots_powerup_goal(struct bots_bot *bot, struct unit_datum *unit, + real_point3d const *position, boolean fighting) +{ + long now = game_time_get(), index, best = NONE; + real best_score = REAL_MAX; + long bot_index = (long)(bot - bots_globals.bots); + if (infection_enabled() && infection_unit_is_zombie(bot->unit_index)) return FALSE; + if (bot->powerup_index != NONE) + { + struct object_datum *item = object_try_and_get_and_verify_type(bot->powerup_index, _object_mask_equipment); + boolean still_goal = bot->goal_kind == _bots_goal_item && bot->item_index == bot->powerup_index; + real distance = item ? bots_distance3d(&item->object.position, position) : REAL_MAX; + boolean healthy = item && equipment_definition_get(item->definition_index)->equipment.powerup_type == + _equipment_powerup_health && unit->object.body_vitality >= 1.0f; + if (still_goal && bots_powerup_claimed(bot, bot->powerup_index, distance)) + { + bot->powerup_index = NONE; + bot->goal_kind = _bots_goal_none; + bot->powerup_check = now + TICKS_PER_SECOND; + return FALSE; + } + if (still_goal && item && item->object.parent_object_index == NONE && !healthy) + { + bot->powerup_distance = distance; + if (distance < 0.8f && !bot->powerup_arrived) bot->powerup_arrived = now; + if (now < bot->powerup_deadline && (!bot->powerup_arrived || now - bot->powerup_arrived < 2 * TICKS_PER_SECOND)) + return TRUE; + } + if (item && item->object.parent_object_index == NONE && !healthy && + (distance > 1.5f || still_goal)) bots_item_set_unreachable(bot, bot->powerup_index); + bot->powerup_index = NONE; + if (still_goal) bot->goal_kind = _bots_goal_none; + } + if (now < bot->powerup_check) return FALSE; + bot->powerup_check = now + TICKS_PER_SECOND; + if (now >= bots_powerups.next_scan) + { + struct object_iterator iterator; + struct object_datum *item; + bots_powerups.next_scan = now + TICKS_PER_SECOND; + bots_powerups.count = 0; + object_iterator_new(&iterator, _object_mask_equipment, 0); + while ((item = object_iterator_next(&iterator)) != NULL && bots_powerups.count < (long)NUMBEROF(bots_powerups.items)) + if (item->object.parent_object_index == NONE && TEST_FLAG(item->object.flags, _object_connected_to_map_bit)) + bots_powerups.items[bots_powerups.count++] = iterator.index; + } + for (index = 0; index < bots_powerups.count; index++) + { + long item_index = bots_powerups.items[index]; + struct object_datum *item = object_try_and_get_and_verify_type(item_index, _object_mask_equipment); + real distance, score; + if (!item || item->object.parent_object_index != NONE || bots_item_unreachable(bot, item_index)) continue; + distance = bots_distance3d(position, &item->object.position); + score = enhanced_bots_powerup_score(unit, item->definition_index, distance, bots_globals.skill, + fighting, bots_tactics_bots[bot_index].hold_tick != 0); + if (score >= best_score) continue; + if (bots_powerup_claimed(bot, item_index, distance)) continue; + best = item_index; + best_score = score; + } + if (best != NONE) + { + real_point3d ground; + long surface = bots_surface_below(&object_get(best)->object.position, &ground); + if (surface == NONE) { bots_item_set_unreachable(bot, best); return FALSE; } + bots_set_goal(bot, _bots_goal_item, &ground, surface); + bot->item_index = bot->powerup_index = best; + bot->powerup_distance = bots_distance3d(position, &ground); + bot->powerup_arrived = 0; + bot->powerup_deadline = now + 10 * TICKS_PER_SECOND + (long)(bot->powerup_distance * 0.75f * TICKS_PER_SECOND); + return TRUE; + } + return FALSE; +} diff --git a/port/linux/game/bots_roles.c b/port/linux/game/bots_roles.c new file mode 100644 index 0000000000..257c652bd0 --- /dev/null +++ b/port/linux/game/bots_roles.c @@ -0,0 +1,763 @@ +/* Source: thelinkin3000/halo-ce-universal, commit + * d92cc93385edf03d0a4a21cfe4c58dd578a3e786, port/linux/game/bots_roles.c. + * Derived from BirchWoodGod/halo-ce-vita (GPL-3.0-only). + * Used only by GulchCE's optional enhanced bots. + */ +/* Optional enhanced bots' team roles, lane assignment and precision-weapon +vantage points. CTF defenders follow enhanced_bots.c's objective policy; +King bots stay on the hill. Bots with suitable weapons may hold a vantage +point until hurt, low on ammunition, approached by an enemy, or needed for +an urgent objective. The original bots.c still owns combat and paths. + +Roles refresh once a second. Route and vantage preparation advances in +bounded steps from bots_tactics_update; diagnostics report its actual cost. +HALO_BOT_ROLES=0 disables roles and vantage choices for diagnostic runs. */ + +#include "cseries.h" +#include "game/game.h" +#include "game/game_engine.h" +#include "game/players.h" +#include "objects/objects.h" +#include "units/units.h" +#include "items/weapons.h" +#include "items/weapon_definitions.h" +#include "networking/network_game_globals.h" +#include "infection.h" +#include "tag_files/tag_groups.h" +#include "tag_files/tag_files.h" + +#include "bots.h" +#include "bots_tactics.h" +#include "bots_objectives.h" + +#include +#include +#include +#include + +/* enhanced_bots.c: the objective policy that assigns defenders. */ +boolean bots_quake_defender(long bot_index); +unsigned long system_milliseconds(void); + +/* ---------- constants */ + +#define BOTS_TACTICS_PI 3.14159265f +/* how near its vantage point a bot is there */ +#define BOTS_VANTAGE_ARRIVED 2.0f +/* an enemy this near: off the vantage point, to fight (a middle precision +weapon's bot: nearer) */ +#define BOTS_VANTAGE_ENEMY_NEAR 9.0f +#define BOTS_VANTAGE_ENEMY_NEAR_MID 6.0f +/* a middle precision weapon's bot: a vantage point this near it at most */ +#define BOTS_VANTAGE_MID_REACH 35.0f +/* how much further a bot sees through a long precision weapon's scope at +its vantage point */ +#define BOTS_VANTAGE_SCOPE_SIGHT 1.5f +/* the most teams the roles are counted by */ +#define BOTS_TACTICS_TEAMS 16 + +/* ---------- globals */ + +struct bots_tactics_bot bots_tactics_bots[BOTS_MAXIMUM]; +struct bots_tactics_counts bots_tactics_counts; + +static struct +{ + long game; + /* the map's lanes and vantage points made, since when, the work's time */ + boolean prepared; + long prepare_ticks; + unsigned long prepare_ms; + unsigned long prepare_most_ms; + /* when the roles are next given; their last line (halo.log's, when it + changes) */ + long roles_tick; + char roles_line[600]; + /* each team's bots */ + long team_bots[BOTS_TACTICS_TEAMS]; +} bots_tactics; + +/* ---------- small helpers */ + +boolean bots_tactics_enabled(void) +{ + static int enabled = -1; + + if (enabled < 0) + { + char const *setting = getenv("HALO_BOT_ROLES"); + + enabled = setting && setting[0] && !atoi(setting) ? 0 : 1; + } + return enabled != 0; +} + +long bots_tactics_game(void) +{ + return bots_tactics.game; +} + +unsigned long bots_tactics_random(struct bots_tactics_bot *state) +{ + /* (xorshift32) */ + unsigned long x = state->random ? state->random : 0x9E3779B9UL; + + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + x &= 0xFFFFFFFFUL; + state->random = x; + return x; +} + +/* seconds, from `low` to `high`, in ticks */ +static long bots_tactics_random_ticks(struct bots_tactics_bot *state, long low, long high) +{ + return TICKS_PER_SECOND * low + (long)(bots_tactics_random(state) % (unsigned long)(TICKS_PER_SECOND * (high - low) + 1)); +} + +static real bots_tactics_distance2d(real_point3d const *a, real_point3d const *b) +{ + real dx = a->x - b->x, dy = a->y - b->y; + + return (real)sqrt(dx * dx + dy * dy); +} + +static char const *bots_role_name(short role) +{ + static char const *const names[NUMBER_OF_BOTS_ROLES] = { "attacker", "defender", "roamer" }; + + return role >= 0 && role < NUMBER_OF_BOTS_ROLES ? names[role] : "?"; +} + +/* the unit's current weapon, NONE without one */ +static long bots_tactics_weapon(long unit_index) +{ + struct unit_datum *unit = (struct unit_datum *)object_try_and_get_and_verify_type(unit_index, _object_mask_unit); + + if (!unit || unit->unit.current_weapon_index < 0 || unit->unit.current_weapon_index >= MAXIMUM_WEAPONS_PER_UNIT) + return NONE; + return unit->unit.weapon_object_indices[unit->unit.current_weapon_index]; +} + +/* the precision of the unit's current weapon (bots.c's, from its tag) */ +static short bots_tactics_precision(long unit_index) +{ + return bots_weapon_precision(bots_tactics_weapon(unit_index)); +} + +/* whether the precision weapon held still keeps the bot at the vantage +point it went to for the precision `wanted`: a long or heavy one's for a +long or heavy one, a middle one's for any precision weapon */ +static boolean bots_tactics_still_precise(short wanted, short held) +{ + if (wanted == _bots_precision_mid) + return held == _bots_precision_mid || held == _bots_precision_long; + return held == _bots_precision_long || held == _bots_precision_heavy; +} + +/* the precision weapon the bot would hold a vantage point for, by its role +and the game: none when its part keeps it elsewhere (King's attackers in +the hill; a CTF defender but with a long one, over its stand; a middle one +a roamer's alone) */ +static short bots_tactics_weapon_wants(struct bots_tactics_bot const *state, short precision) +{ + if (precision == _bots_precision_none || bots_tactics.game == game_engine_king || infection_enabled()) + { + return _bots_precision_none; + } + switch (precision) + { + case _bots_precision_long: + return _bots_precision_long; + case _bots_precision_heavy: + return state->role != _bots_role_defender ? _bots_precision_heavy : _bots_precision_none; + case _bots_precision_mid: + return state->role == _bots_role_roamer ? _bots_precision_mid : _bots_precision_none; + } + return _bots_precision_none; +} + +static char const *bots_precision_name(short precision) +{ + return precision == _bots_precision_long ? "long precision" : precision == _bots_precision_mid ? "middle precision" : + precision == _bots_precision_heavy ? "heavy" : "none"; +} + +static char const *bots_vantage_left_name(short why) +{ + static char const *const names[NUMBER_OF_BOTS_VANTAGE_LEFT] = + { "time", "enemy near", "ammunition", "hurt", "weapon", "objective", "other" }; + + return why >= 0 && why < NUMBER_OF_BOTS_VANTAGE_LEFT ? names[why] : "?"; +} + +/* whether a weapon is nearly empty: what is left of it half a magazine at +most (one with a magazine that loads rounds) */ +static boolean bots_tactics_weapon_low(long weapon_index) +{ + struct weapon_datum *weapon; + struct weapon_definition *definition; + struct weapon_magazine_definition *magazine; + + if (weapon_index == NONE) + return FALSE; + weapon = weapon_get(weapon_index); + definition = weapon_definition_get(weapon->definition_index); + if (definition->weapon.magazines.count <= 0) + return FALSE; + magazine = TAG_BLOCK_GET_ELEMENT(&definition->weapon.magazines, 0, struct weapon_magazine_definition); + /* (a battery's weapon, the plasma pistol's, loads no rounds) */ + if (magazine->rounds_loaded_maximum <= 0) + return FALSE; + return weapon->weapon.magazines[0].rounds_loaded + weapon->weapon.magazines[0].rounds_total <= + MAX(1, magazine->rounds_loaded_maximum / 2); +} + +/* ---------- the roles */ + +/* every bot's role and lane, once a second; halo.log's roles line when they +change */ +static void bots_roles_assign(void) +{ + boolean teams = game_engine_has_teams(); + long attackers[BOTS_TACTICS_TEAMS]; + char line[600]; + int length = 0; + long index; + + csmemset(bots_tactics.team_bots, 0, sizeof(bots_tactics.team_bots)); + csmemset(attackers, 0, sizeof(attackers)); + for (index = 0; index < BOTS_MAXIMUM; index++) + { + struct bots_tactics_bot *state = &bots_tactics_bots[index]; + struct player_datum *player = state->player_index != NONE ? player_try_and_get(state->player_index) : NULL; + + state->team = NONE; + if (!player) + continue; + state->team = teams ? PIN(player->team_index, 0, BOTS_TACTICS_TEAMS - 1) : 0; + bots_tactics.team_bots[state->team]++; + } + for (index = 0; index < BOTS_MAXIMUM; index++) + { + struct bots_tactics_bot *state = &bots_tactics_bots[index]; + short role, lane = 0; + + if (state->team == NONE) + continue; + role = bots_tactics_enabled() && bots_quake_defender(index) ? _bots_role_defender : + bots_tactics.game == game_engine_slayer ? _bots_role_roamer : _bots_role_attacker; + if (role == _bots_role_attacker || role == _bots_role_roamer) + { + state->rank = (short)attackers[state->team]++; + lane = bots_routes_lane_for_rank(state->rank); + } + if (role != state->role) + { + bots_vantage_release(index); + state->role = role; + } + if (lane != state->lane) + { + state->lane = lane; + state->waypoint = NONE; + csmemset(state->passed, 0, sizeof(state->passed)); + state->lane_given_up = FALSE; + } + if (length < (int)sizeof(line) - 48) + { + length += snprintf(line + length, sizeof(line) - (size_t)length, "%sbot %ld team %ld %s", length ? ", " : "", + index + 1, state->team, bots_role_name(role)); + if (role == _bots_role_attacker || role == _bots_role_roamer) + length += snprintf(line + length, sizeof(line) - (size_t)length, " (%s)", bots_routes_lane_name(lane)); + } + } + line[length] = 0; + if (length && strcmp(line, bots_tactics.roles_line)) + { + strcpy(bots_tactics.roles_line, line); + platform_log("bots: roles (routes %s): %s", bots_routes_mode() == _bots_routes_lanes ? "lanes" : + bots_routes_mode() == _bots_routes_mixed ? "mixed" : "direct", line); + } +} + +/* ---------- what bots.c tells */ + +void bots_tactics_initialize_for_new_map(void) +{ + long index; + + bots_routes_reset(); + bots_vantage_dispose(); + csmemset(&bots_tactics_counts, 0, sizeof(bots_tactics_counts)); + bots_tactics.prepared = FALSE; + bots_tactics.prepare_ticks = 0; + bots_tactics.prepare_ms = 0; + bots_tactics.prepare_most_ms = 0; + bots_tactics.roles_tick = 0; + bots_tactics.roles_line[0] = 0; + for (index = 0; index < BOTS_MAXIMUM; index++) + { + csmemset(&bots_tactics_bots[index], 0, sizeof(bots_tactics_bots[index])); + bots_tactics_bots[index].player_index = NONE; + bots_tactics_bots[index].team = NONE; + bots_tactics_bots[index].vantage = NONE; + bots_tactics_bots[index].last_vantage = NONE; + bots_tactics_bots[index].waypoint = NONE; + } +} + +void bots_tactics_dispose_from_old_map(void) +{ + bots_routes_reset(); + bots_vantage_dispose(); + bots_tactics.prepared = FALSE; +} + +void bots_tactics_update(void) +{ + long now = game_time_get(); + + bots_tactics.game = game_engine_get_variant()->game_engine_index; + /* the map's lanes and vantage points, a bounded step a tick (the work a + tick fixed, not timed: the same ticks from run to run) */ + if (!bots_tactics.prepared) + { + unsigned long started = system_milliseconds(), spent; + + if (!bots_routes_map.ready) + bots_routes_step(); + else if (bots_vantage_step()) + { + bots_tactics.prepared = TRUE; + bots_routes_release_graph(); + platform_log("bots: tactics made in %ld ticks: %lu ms in all, at most %lu ms a tick (1 ms clock) (routes %s, %ld side lanes)", + bots_tactics.prepare_ticks + 1, bots_tactics.prepare_ms, + bots_tactics.prepare_most_ms, bots_routes_mode() == _bots_routes_direct ? "direct" : + bots_routes_mode() == _bots_routes_lanes ? "lanes" : "mixed", bots_routes_map.lane_count); + bots_tactics.roles_tick = 0; + } + spent = system_milliseconds() - started; + bots_tactics.prepare_ticks++; + bots_tactics.prepare_ms += spent; + if (spent > bots_tactics.prepare_most_ms) + bots_tactics.prepare_most_ms = spent; + } + if (now >= bots_tactics.roles_tick || now < bots_tactics.roles_tick - TICKS_PER_SECOND) + { + bots_tactics.roles_tick = now + TICKS_PER_SECOND; + bots_routes_read_setting(); + bots_roles_assign(); + } +} + +void bots_tactics_bot_reset(long bot_index, long player_index) +{ + struct bots_tactics_bot *state; + + if (bot_index < 0 || bot_index >= BOTS_MAXIMUM) + return; + state = &bots_tactics_bots[bot_index]; + bots_vantage_release(bot_index); + csmemset(state, 0, sizeof(*state)); + state->player_index = player_index; + state->random = (0x9E3779B1UL * (unsigned long)(bot_index + 7) ^ (unsigned long)network_game_get_random_seed() ^ + 0x5BD1E995UL) & 0xFFFFFFFFUL; + state->team = NONE; + state->vantage = NONE; + state->last_vantage = NONE; + state->waypoint = NONE; + state->role = NONE; + /* (its role and lane at once) */ + bots_tactics.roles_tick = 0; +} + +void bots_tactics_bot_dead(long bot_index) +{ + struct bots_tactics_bot *state; + + if (bot_index < 0 || bot_index >= BOTS_MAXIMUM) + return; + state = &bots_tactics_bots[bot_index]; + if (state->vantage != NONE) + bots_tactics_counts.vantage_leaves[_bots_vantage_left_other]++; + bots_vantage_release(bot_index); + state->waypoint = NONE; + csmemset(state->passed, 0, sizeof(state->passed)); + state->lane_given_up = FALSE; +} + +/* off its vantage point, for why: the game's goals a while before another */ +static void bots_tactics_leave(long bot_index, short why) +{ + struct bots_tactics_bot *state = &bots_tactics_bots[bot_index]; + boolean scoped = state->vantage_weapon == _bots_precision_long; + short weapon = state->vantage_weapon; + long now = game_time_get(); + + bots_tactics_counts.vantage_leaves[why]++; + platform_log("bots: bot %ld (%s) off vantage point %d (%s) after %.0f s, held %.0f s%s%s", bot_index + 1, + bots_role_name(state->role), (int)state->vantage + 1, bots_vantage_left_name(why), + (double)(now - state->vantage_tick) / TICKS_PER_SECOND, + state->hold_tick ? (double)(now - state->hold_tick) / TICKS_PER_SECOND : 0.0, + weapon != _bots_precision_none ? ", there for its " : "", weapon != _bots_precision_none ? bots_precision_name(weapon) : ""); + /* (debug: HALO_BOT_TRACE, each bot off its vantage point, why, its weapon) */ + if (bots_trace_enabled()) + { + struct player_datum *player = player_try_and_get(state->player_index); + long weapon_index = player ? bots_tactics_weapon(player->unit_index) : NONE; + + platform_log("bots: trace bot %ld (%s) off vantage point %d (%s) after %ld ticks, held %ld, weapon %s %d/%d", bot_index + 1, + bots_role_name(state->role), (int)state->vantage + 1, bots_vantage_left_name(why), game_time_get() - state->vantage_tick, + state->hold_tick ? game_time_get() - state->hold_tick : 0L, + weapon_index != NONE ? tag_get_name(weapon_get(weapon_index)->definition_index) : "none", + weapon_index != NONE ? (int)weapon_get(weapon_index)->weapon.magazines[0].rounds_loaded : 0, + weapon_index != NONE ? (int)weapon_get(weapon_index)->weapon.magazines[0].rounds_total : 0); + } + state->rest_weapon = weapon; + bots_vantage_release(bot_index); + /* (the game's goals a while: a sniper's, or a long precision weapon's + bot, soon back at it, sooner after a fight close up; at once after its + weapon changed, which may be taken up again; a while after the + objective) */ + if (why == _bots_vantage_left_weapon) + state->rest_until_tick = now + TICKS_PER_SECOND * 3; + else if (why == _bots_vantage_left_objective) + state->rest_until_tick = now + TICKS_PER_SECOND * 10; + else if (scoped) + state->rest_until_tick = now + (why == _bots_vantage_left_enemy ? bots_tactics_random_ticks(state, 8, 15) : + bots_tactics_random_ticks(state, 10, 20)); + else + state->rest_until_tick = now + bots_tactics_random_ticks(state, 30, 45); +} + +/* why the bot leaves its vantage point now, NONE to stay */ +static short bots_tactics_leave_reason(long bot_index, struct player_datum *player, long now) +{ + struct bots_tactics_bot *state = &bots_tactics_bots[bot_index]; + struct object_datum *object = object_try_and_get(player->unit_index); + long weapon_index = bots_tactics_weapon(player->unit_index); + + /* (its weapon first: the reason that says most) */ + if (state->vantage_weapon != _bots_precision_none) + { + short precision = bots_weapon_precision(weapon_index); + + if (!bots_tactics_still_precise(state->vantage_weapon, precision)) + return _bots_vantage_left_weapon; + /* (a sniper rifle taken up at, or on the way to, a pistol's or a + rocket launcher's vantage point: held as a sniper rifle's from now) */ + if (precision == _bots_precision_long && state->vantage_weapon != _bots_precision_long) + { + state->vantage_weapon = _bots_precision_long; + state->hold_ticks = (state->hold_tick ? now - state->hold_tick : 0) + bots_tactics_random_ticks(state, 35, 50); + platform_log("bots: bot %ld (%s) %s vantage point %d for its long precision now, for %.0f s", bot_index + 1, + bots_role_name(state->role), state->hold_tick ? "holds" : "goes to", (int)state->vantage + 1, + (double)(state->hold_ticks - (state->hold_tick ? now - state->hold_tick : 0)) / TICKS_PER_SECOND); + } + } + if (bots_tactics_weapon_low(weapon_index)) + return _bots_vantage_left_ammunition; + if (object && object->object.body_vitality < 0.34f) + return _bots_vantage_left_hurt; + if (state->hold_tick && now - state->hold_tick >= state->hold_ticks) + return _bots_vantage_left_time; + if (!state->hold_tick && now - state->vantage_tick > TICKS_PER_SECOND * 60) + { + SET_FLAG(state->failed_vantages, state->vantage, TRUE); + state->failed_until_tick = now + TICKS_PER_SECOND * 60; + bots_tactics_counts.vantage_failures++; + return _bots_vantage_left_other; + } + return NONE; +} + +/* A free vantage point suitable for the weapon: a CTF defender's over its +own stand, a pistol's nearby; while its team has fewer holding one than a third of its bots +(half for a long precision weapon's, a pistol's one apart). None: looked for +again in a few seconds */ +static void bots_tactics_seek(long bot_index, real_point3d const *position, + short weapon_wants) +{ + struct bots_tactics_bot *state = &bots_tactics_bots[bot_index]; + long now = game_time_get(); + real_point3d hill, *objective = NULL; + long index, holders = 0, middle_holders = 0, most; + short vantage; + + if (state->role == _bots_role_defender && bots_tactics.game == game_engine_ctf) + { + /* A CTF defender keeps sight of its own stand. */ + if (!bots_vantage_stand(state->team, &hill)) + return; + objective = &hill; + } + for (index = 0; index < BOTS_MAXIMUM; index++) + { + /* (a pistol's bot, one a team, is not counted: it keeps no sniper + from a vantage point) */ + if (index != bot_index && bots_tactics_bots[index].vantage != NONE && bots_tactics_bots[index].team == state->team) + { + if (bots_tactics_bots[index].vantage_weapon == _bots_precision_mid) + middle_holders++; + else + holders++; + } + } + most = weapon_wants == _bots_precision_long ? MAX(1, (bots_tactics.team_bots[state->team] + 1) / 2) : + MAX(1, bots_tactics.team_bots[state->team] / 3); + vantage = (weapon_wants == _bots_precision_mid ? !middle_holders : holders < most) ? + bots_vantage_choose(bot_index, position, objective, + weapon_wants == _bots_precision_mid ? BOTS_VANTAGE_MID_REACH : REAL_MAX) : NONE; + if (vantage == NONE) + { + state->rest_until_tick = now + TICKS_PER_SECOND * 5; + state->rest_weapon = weapon_wants; + return; + } + state->vantage = vantage; + state->vantage_weapon = weapon_wants; + state->vantage_tick = now; + state->hold_tick = 0; + state->hold_ticks = weapon_wants == _bots_precision_long ? + bots_tactics_random_ticks(state, 35, 50) : + weapon_wants == _bots_precision_mid ? bots_tactics_random_ticks(state, 12, 20) : bots_tactics_random_ticks(state, 20, 30); + bots_tactics_counts.vantages_chosen++; +} + +boolean bots_tactics_goal(long bot_index, long player_index, real_point3d const *position, real_point3d *goal, + long *surface_index) +{ + struct bots_tactics_bot *state; + struct player_datum *player; + long now = game_time_get(); + + if (bot_index < 0 || bot_index >= BOTS_MAXIMUM || !bots_tactics_enabled() || !bots_tactics.prepared || + bots_tactics.game == game_engine_race || bots_tactics.game == game_engine_none) + { + return FALSE; + } + state = &bots_tactics_bots[bot_index]; + player = player_try_and_get(player_index); + if (!player || player->unit_index == NONE || state->team == NONE) + return FALSE; + /* a vantage point it goes to, or holds */ + if (state->vantage != NONE) + { + short why = bots_tactics_leave_reason(bot_index, player, now); + + if (why != NONE) + bots_tactics_leave(bot_index, why); + else + { + bots_vantage_point(state->vantage, goal, surface_index); + if (!state->hold_tick && bots_tactics_distance2d(position, goal) < BOTS_VANTAGE_ARRIVED && + fabs(position->z - goal->z) < 1.5f) + { + state->hold_tick = now; + bots_tactics_counts.vantages_reached++; + platform_log("bots: bot %ld (%s) at vantage point %d (%.1f %.1f %.1f), for %.0f s%s%s", bot_index + 1, + bots_role_name(state->role), (int)state->vantage + 1, goal->x, goal->y, goal->z, + (double)state->hold_ticks / TICKS_PER_SECOND, + state->vantage_weapon != _bots_precision_none ? ", for its " : "", + state->vantage_weapon != _bots_precision_none ? bots_precision_name(state->vantage_weapon) : ""); + } + return TRUE; + } + } + /* one to go to: a sniper's, a precision weapon's (a sniper rifle's, a + pistol's near) or a rocket launcher's, a defender's over the hill (a CTF + defender's with a sniper rifle over its stand) */ + { + /* (no role holds one by itself: Quake III's defenders keep to their + flag and the hill, bots.c) */ + short weapon_wants = + bots_tactics_weapon_wants(state, bots_tactics_precision(player->unit_index)); + + /* (resting a while from a vantage point, the game's goals first; + but a sniper rifle taken up since one held for another weapon, a + pistol or a rocket launcher, goes to one at once) */ + if (now < state->rest_until_tick && + !(weapon_wants == _bots_precision_long && state->rest_weapon != _bots_precision_long)) + { + weapon_wants = _bots_precision_none; + } + if (weapon_wants != _bots_precision_none) + bots_tactics_seek(bot_index, position, weapon_wants); + if (state->vantage != NONE) + { + bots_vantage_point(state->vantage, goal, surface_index); + return TRUE; + } + } + /* (CTF's defenders keep about their flag by Quake III's rules: bots.c's + bots_ctf_choose_goal) */ + return FALSE; +} + +boolean bots_tactics_search_answer(long bot_index, real_point3d const *goal, boolean reached, boolean spent) +{ + struct bots_tactics_bot *state; + real_point3d point; + long surface_index; + + if (bot_index < 0 || bot_index >= BOTS_MAXIMUM || reached || !spent) + return FALSE; + if (bots_routes_search_failed(bot_index, goal)) + return TRUE; + state = &bots_tactics_bots[bot_index]; + if (state->vantage == NONE) + return FALSE; + bots_vantage_point(state->vantage, &point, &surface_index); + if (fabs(point.x - goal->x) + fabs(point.y - goal->y) + fabs(point.z - goal->z) > 0.5f) + return FALSE; + SET_FLAG(state->failed_vantages, state->vantage, TRUE); + state->failed_until_tick = game_time_get() + TICKS_PER_SECOND * 60; + bots_tactics_counts.vantage_failures++; + bots_tactics_leave(bot_index, _bots_vantage_left_other); + state->rest_until_tick = game_time_get() + TICKS_PER_SECOND * 5; + return TRUE; +} + +void bots_tactics_look(long bot_index, real_point3d const *position, long now, real *yaw, real *pitch) +{ + struct bots_tactics_bot *state; + unsigned long watched = 0; + long count = bots_places_count(), index; + struct bots_place const *place; + real desired_yaw, desired_pitch, off, dx, dy, dz; + + if (bot_index < 0 || bot_index >= BOTS_MAXIMUM || !bots_tactics.prepared || count <= 0) + return; + state = &bots_tactics_bots[bot_index]; + if (state->vantage != NONE && state->hold_tick) + watched = bots_vantage_sees(state->vantage); + if (!watched) + return; + if (now >= state->look_until_tick || !TEST_FLAG(watched, state->look_place)) + { + /* (the next place watched, in turn) */ + for (index = 1; index <= count; index++) + { + long next = (state->look_place + index) % count; + + if (TEST_FLAG(watched, next) && bots_tactics_distance2d(&bots_place_get(next)->point, position) > 3.0f) + { + state->look_place = (short)next; + break; + } + } + state->look_until_tick = now + TICKS_PER_SECOND * 2 + (long)(bots_tactics_random(state) % (TICKS_PER_SECOND * 2)); + } + place = bots_place_get(state->look_place); + dx = place->point.x - position->x; + dy = place->point.y - position->y; + dz = place->point.z - (position->z + 0.6f); + if (dx * dx + dy * dy < 1.0f) + return; + desired_yaw = (real)atan2(dy, dx); + desired_pitch = (real)atan2(dz, sqrt(dx * dx + dy * dy)); + off = (real)fmod(desired_yaw - *yaw, 2.0f * BOTS_TACTICS_PI); + if (off > BOTS_TACTICS_PI) + off -= 2.0f * BOTS_TACTICS_PI; + else if (off < -BOTS_TACTICS_PI) + off += 2.0f * BOTS_TACTICS_PI; + /* (turning at six degrees a tick) */ + *yaw += PIN(off, -0.105f, 0.105f); + *pitch += PIN(desired_pitch - *pitch, -0.05f, 0.05f); +} + +void bots_tactics_fight(long bot_index, real_point3d const *position, real target_distance, boolean *moving, + real *direction, real *throttle) +{ + struct bots_tactics_bot *state; + real_point3d point; + long surface_index; + + if (bot_index < 0 || bot_index >= BOTS_MAXIMUM) + return; + state = &bots_tactics_bots[bot_index]; + if (state->vantage == NONE || !state->hold_tick) + return; + if (target_distance < (state->vantage_weapon == _bots_precision_mid ? BOTS_VANTAGE_ENEMY_NEAR_MID : BOTS_VANTAGE_ENEMY_NEAR)) + { + bots_tactics_leave(bot_index, _bots_vantage_left_enemy); + return; + } + bots_vantage_point(state->vantage, &point, &surface_index); + if (bots_tactics_distance2d(position, &point) > 1.2f) + { + *direction = (real)atan2(point.y - position->y, point.x - position->x); + *moving = TRUE; + *throttle = 0.7f; + } + else + *throttle *= 0.3f; +} + +void bots_tactics_check(long bot_index, long player_index) +{ + struct player_datum *player; + short why; + + if (bot_index < 0 || bot_index >= BOTS_MAXIMUM || bots_tactics_bots[bot_index].vantage == NONE || + (player = player_try_and_get(player_index)) == NULL || player->unit_index == NONE) + { + return; + } + why = bots_tactics_leave_reason(bot_index, player, game_time_get()); + if (why != NONE) + bots_tactics_leave(bot_index, why); +} + +void bots_tactics_objective(long bot_index) +{ + if (bot_index < 0 || bot_index >= BOTS_MAXIMUM || bots_tactics_bots[bot_index].vantage == NONE) + return; + bots_tactics_leave(bot_index, _bots_vantage_left_objective); +} + +real bots_tactics_sight_scale(long bot_index) +{ + struct bots_tactics_bot const *state; + struct player_datum *player; + + if (bot_index < 0 || bot_index >= BOTS_MAXIMUM) + return 1.0f; + state = &bots_tactics_bots[bot_index]; + if (state->vantage == NONE || !state->hold_tick || state->player_index == NONE || + (player = player_try_and_get(state->player_index)) == NULL || player->unit_index == NONE) + { + return 1.0f; + } + return bots_tactics_precision(player->unit_index) == _bots_precision_long ? BOTS_VANTAGE_SCOPE_SIGHT : 1.0f; +} + +static long bots_tactics_leaves_total(void) +{ + long index, total = 0; + + for (index = 0; index < NUMBER_OF_BOTS_VANTAGE_LEFT; index++) + total += bots_tactics_counts.vantage_leaves[index]; + return total; +} + +void bots_tactics_report(long now) +{ + if (!bots_tactics.prepared) + return; + platform_log("bots: tactics at tick %ld: routes %s (%ld side lanes): lanes taken %ld, waypoints passed %ld, given up %ld; " + "vantage points %ld: chosen %ld, reached %ld, left %ld (time %ld, enemy near %ld, ammunition %ld, hurt %ld, weapon %ld, " + "objective %ld, other %ld), no way %ld%s", now, + bots_routes_mode() == _bots_routes_direct ? "direct" : bots_routes_mode() == _bots_routes_lanes ? "lanes" : "mixed", + bots_routes_map.lane_count, bots_tactics_counts.lanes_taken, bots_tactics_counts.waypoints_passed, + bots_tactics_counts.lanes_given_up, bots_vantage_count(), bots_tactics_counts.vantages_chosen, + bots_tactics_counts.vantages_reached, + bots_tactics_leaves_total(), + bots_tactics_counts.vantage_leaves[_bots_vantage_left_time], bots_tactics_counts.vantage_leaves[_bots_vantage_left_enemy], + bots_tactics_counts.vantage_leaves[_bots_vantage_left_ammunition], bots_tactics_counts.vantage_leaves[_bots_vantage_left_hurt], + bots_tactics_counts.vantage_leaves[_bots_vantage_left_weapon], bots_tactics_counts.vantage_leaves[_bots_vantage_left_objective], + bots_tactics_counts.vantage_leaves[_bots_vantage_left_other], bots_tactics_counts.vantage_failures, + bots_tactics_enabled() ? "" : " (no roles nor vantage points: HALO_BOT_ROLES=0)"); +} diff --git a/port/linux/game/bots_routes.c b/port/linux/game/bots_routes.c new file mode 100644 index 0000000000..c67f68789a --- /dev/null +++ b/port/linux/game/bots_routes.c @@ -0,0 +1,1308 @@ +/* Source: thelinkin3000/halo-ce-universal, commit + * d92cc93385edf03d0a4a21cfe4c58dd578a3e786, port/linux/game/bots_routes.c. + * Derived from BirchWoodGod/halo-ce-vita (GPL-3.0-only). + * Used only by GulchCE's optional enhanced bots. + */ +/* Optional enhanced bots' routes. Direct uses the original pathfinder's +goal. Lanes and Mixed distribute attackers over up to two side routes. +The graph joins validated walkable surfaces, excluding blocked machine +surfaces. Weighted shortest-path searches prefer opposite sides of the +direct route; a lane too close to that route or too long is rejected. + +Preparation advances in bounded steps each tick. Only two waypoints per +lane are retained; the graph is released after vantage preparation. A bot +abandons an unreachable lane for the rest of its life. Vehicle paths stay +direct. HALO_BOT_ROUTES_DUMP writes diagnostic geometry in the data folder. */ + +#include "cseries.h" +#include "game/game.h" +#include "game/game_engine.h" +#include "game/players.h" +#include "objects/objects.h" +#include "scenario/scenario.h" +#include "scenario/scenario_definitions.h" +#include "structures/structure_bsp_definitions.h" +#include "physics/collision_bsp_definitions.h" +#include "physics/collisions.h" +#include "tag_files/tag_groups.h" +#include "tag_files/tag_files.h" + +#include "bots.h" +#include "bots_tactics.h" +#include "bots_objectives.h" + +#include +#include +#include +#include + +/* ---------- constants */ + +/* a pathfinding surface's flag: walkable (path.c's) */ +#define BOTS_ROUTES_WALKABLE_BIT 6 +/* the most walkable surfaces a map's graph takes (Blood Gulch has 2807); +more, and the map has no lanes nor vantage points */ +#define BOTS_GRAPH_MAXIMUM_NODES 32768 +/* Bound the surface-to-node lookup too, including unwalkable surfaces. */ +#define BOTS_GRAPH_MAXIMUM_SURFACES 262144 +/* the corners of a surface looked at (its ring of edges) */ +#define BOTS_ROUTES_CORNERS 16 +/* the work of a tick while the lanes are made: surfaces looked at, the +searches' surfaces taken, the nodes placed across the direct route */ +#define BOTS_ROUTES_SURFACES_A_TICK 300 +#define BOTS_ROUTES_POPS_A_TICK 80 +#define BOTS_ROUTES_NODES_A_TICK 200 +/* the machines (doors, lifts) whose ground the graph leaves out */ +#define BOTS_ROUTES_MACHINES 32 +/* a goal nearer than this is gone to directly */ +#define BOTS_LANE_LEAST_DISTANCE 25.0f +/* how near a waypoint a bot has come to it, and how long it has to */ +#define BOTS_LANE_WAYPOINT_REACHED 3.0f +#define BOTS_LANE_WAYPOINT_SECONDS 40 + +enum +{ + _routes_phase_idle = 0, + _routes_phase_machines, + _routes_phase_nodes, + _routes_phase_links, + _routes_phase_bases, + _routes_phase_direct, + _routes_phase_place, + _routes_phase_lanes, + _routes_phase_done, + _routes_phase_none, +}; + +/* ---------- structures */ + +struct bots_lane_waypoint +{ + real_point3d point; + long surface_index; + /* how far along the direct route (0 to 1) */ + real along; +}; + +struct bots_lane +{ + boolean valid; + long waypoint_count; + struct bots_lane_waypoint waypoints[BOTS_LANE_WAYPOINTS]; + real length; + real offset; +}; + +/* ---------- globals */ + +struct bots_graph bots_graph; +struct bots_routes_map bots_routes_map; + +static struct +{ + short phase; + short mode; + struct structure_bsp const *structure; + long surface_count; + long *node_of_surface; + long cursor; + long link_capacity; + long link_write; + /* the search (Dijkstra's, an indexed binary heap): its costs, the way + back, the heap and each node's place in it (NONE: not in it, -2: done) */ + real *cost; + long *previous; + long *heap; + long *heap_position; + long heap_count; + long origin; + long target; + /* the bases' nodes, and which bases they are (bots_routes_find_bases' + sets: the stands, the teams' starting locations, the two furthest apart) */ + long base_nodes[2]; + long base_set; + /* the nodes' costs from the first base made (what is reached: the + vantage points' spots, lanes or none) */ + boolean costs_made; + /* the machines' spheres, whose ground the graph leaves out */ + long machine_count; + real_point3d machine_centers[BOTS_ROUTES_MACHINES]; + real machine_radii[BOTS_ROUTES_MACHINES]; + long machine_surfaces; + /* the side lane being searched (0 or 1), its side (-1 or 1) */ + long lane_index; + real lane_side; + real penalty_radius; + /* the direct route's polyline (bots_routes_map.route_points): its parts' + lengths, and the length to each point */ + real segment_lengths[BOTS_ROUTE_POINTS]; + real point_lengths[BOTS_ROUTE_POINTS]; + struct bots_lane lanes[BOTS_SIDE_LANES]; +} bots_routes; + +/* ---------- the setting */ + +static short bots_routes_setting(void) +{ + char const *value = getenv("HALO_BOT_ROUTES"); + + if (!value || !value[0]) + value = config_string("bots.routes"); + if (value && !strcmp(value, "lanes")) + return _bots_routes_lanes; + if (value && !strcmp(value, "mixed")) + return _bots_routes_mixed; + return _bots_routes_direct; +} + +/* the setting, read once a second (the panel changes it at any time) */ +short bots_routes_mode(void) +{ + return bots_routes.mode; +} + +void bots_routes_read_setting(void) +{ + bots_routes.mode = bots_routes_setting(); +} + +/* ---------- small helpers */ + +static real bots_routes_distance2d(real_point3d const *a, real_point3d const *b) +{ + real dx = a->x - b->x, dy = a->y - b->y; + + return (real)sqrt(dx * dx + dy * dy); +} + +static real bots_routes_distance3d(real_point3d const *a, real_point3d const *b) +{ + real dx = a->x - b->x, dy = a->y - b->y, dz = a->z - b->z; + + return (real)sqrt(dx * dx + dy * dy + dz * dz); +} + +long bots_routes_ground(real_point3d const *point, real_point3d *ground) +{ + struct collision_result collision; + real_point3d start = *point; + real_vector3d down = { 0.0f, 0.0f, -6.0f }; + + start.z += 0.4f; + if (collision_test_vector(FLAG(_collision_test_structure_bit) | FLAG(_collision_test_front_facing_surfaces_bit), + &start, &down, NONE, &collision) && collision.type == _collision_result_structure) + { + if (ground) + *ground = collision.point; + return collision.surface_index; + } + return NONE; +} + +/* the structure's collision bsp, NULL for none */ +static struct collision_bsp const *bots_routes_bsp(void) +{ + struct structure_bsp const *structure = bots_routes.structure; + + if (!structure || structure->collision_bsp.count <= 0) + return NULL; + return TAG_BLOCK_GET_ELEMENT(&structure->collision_bsp, 0, struct collision_bsp); +} + +/* whether a surface is walkable (the structure's pathfinding flags) */ +static boolean bots_routes_walkable(long surface_index) +{ + byte const *flags = (byte const *)bots_routes.structure->pathfinding_surfaces.address; + + return surface_index >= 0 && surface_index < bots_routes.surface_count && + TEST_FLAG(flags[surface_index], BOTS_ROUTES_WALKABLE_BIT); +} + +/* the surface's corners (at most BOTS_ROUTES_CORNERS) from its ring of edges, +and the surface across each edge (NONE for none); 0 for one not the bsp's */ +static long bots_routes_corners(struct collision_bsp const *bsp, long surface_index, real_point3d *corners, + long *neighbours) +{ + struct collision_surface const *surface; + long edge_index, count = 0; + + if (surface_index < 0 || surface_index >= bsp->surfaces.count) + return 0; + surface = TAG_BLOCK_GET_ELEMENT(&bsp->surfaces, surface_index, struct collision_surface); + edge_index = surface->first_edge_index; + do + { + struct collision_edge const *edge; + boolean right; + + if (edge_index < 0 || edge_index >= bsp->edges.count) + return 0; + edge = TAG_BLOCK_GET_ELEMENT(&bsp->edges, edge_index, struct collision_edge); + right = edge->surface_indices[1] == surface_index; + if (!VALID_INDEX(edge->vertex_indices[right], bsp->vertices.count)) + return 0; + corners[count] = TAG_BLOCK_GET_ELEMENT(&bsp->vertices, edge->vertex_indices[right], struct collision_vertex)->point; + if (neighbours) + neighbours[count] = edge->surface_indices[!right]; + count++; + edge_index = edge->edge_indices[right]; + } while (edge_index != surface->first_edge_index && count < BOTS_ROUTES_CORNERS); + return count; +} + +/* ---------- the walkable graph */ + +static void bots_routes_free(void) +{ + /* (the game's free, debug_memory.c's, takes no NULL) */ + if (bots_routes.node_of_surface) + free(bots_routes.node_of_surface); + if (bots_graph.nodes) + free(bots_graph.nodes); + if (bots_graph.link_first) + free(bots_graph.link_first); + if (bots_graph.links) + free(bots_graph.links); + if (bots_routes.cost) + free(bots_routes.cost); + if (bots_routes.previous) + free(bots_routes.previous); + if (bots_routes.heap) + free(bots_routes.heap); + if (bots_routes.heap_position) + free(bots_routes.heap_position); + bots_routes.node_of_surface = NULL; + bots_graph.nodes = NULL; + bots_graph.link_first = NULL; + bots_graph.links = NULL; + bots_routes.cost = NULL; + bots_routes.previous = NULL; + bots_routes.heap = NULL; + bots_routes.heap_position = NULL; + bots_graph.node_count = 0; + bots_graph.link_count = 0; + bots_routes.link_capacity = 0; +} + +/* the graph's memory let go (its answers, the lanes and the direct route, +kept) */ +void bots_routes_release_graph(void) +{ + bots_routes_free(); +} + +void bots_routes_reset(void) +{ + bots_routes_free(); + csmemset(&bots_routes_map, 0, sizeof(bots_routes_map)); + csmemset(bots_routes.lanes, 0, sizeof(bots_routes.lanes)); + bots_routes.phase = _routes_phase_idle; + bots_routes.costs_made = FALSE; + bots_routes.structure = NULL; + bots_routes.cursor = 0; +} + +/* the graph begun: the walkable surfaces counted, the memory for them; FALSE +for a map without (or with too many) */ +static boolean bots_routes_begin(void) +{ + struct structure_bsp const *structure = global_structure_bsp_get(); + struct collision_bsp const *bsp; + byte const *flags; + long index, count = 0; + + if (!structure || structure->collision_bsp.count <= 0 || structure->pathfinding_surfaces.count <= 0) + { + platform_log("bots: routes: the level has no walkable surfaces: no lanes, no vantage points"); + return FALSE; + } + bots_routes.structure = structure; + bsp = bots_routes_bsp(); + bots_routes.surface_count = MIN((long)bsp->surfaces.count, (long)structure->pathfinding_surfaces.count); + if (bots_routes.surface_count > BOTS_GRAPH_MAXIMUM_SURFACES) + { + platform_log("bots: routes: %ld surfaces exceed the %d surface budget: direct paths only", + bots_routes.surface_count, BOTS_GRAPH_MAXIMUM_SURFACES); + return FALSE; + } + flags = (byte const *)structure->pathfinding_surfaces.address; + for (index = 0; index < bots_routes.surface_count; index++) + { + if (TEST_FLAG(flags[index], BOTS_ROUTES_WALKABLE_BIT)) + count++; + } + if (count < 8 || count > BOTS_GRAPH_MAXIMUM_NODES) + { + platform_log("bots: routes: %ld walkable surfaces: no lanes, no vantage points", count); + return FALSE; + } + bots_routes.node_of_surface = (long *)malloc(sizeof(long) * (size_t)bots_routes.surface_count); + bots_graph.nodes = (struct bots_graph_node *)malloc(sizeof(struct bots_graph_node) * (size_t)count); + bots_graph.link_first = (long *)malloc(sizeof(long) * (size_t)(count + 1)); + bots_routes.link_capacity = count * 6; + bots_graph.links = (long *)malloc(sizeof(long) * (size_t)bots_routes.link_capacity); + bots_routes.cost = (real *)malloc(sizeof(real) * (size_t)count); + bots_routes.previous = (long *)malloc(sizeof(long) * (size_t)count); + bots_routes.heap = (long *)malloc(sizeof(long) * (size_t)count); + bots_routes.heap_position = (long *)malloc(sizeof(long) * (size_t)count); + if (!bots_routes.node_of_surface || !bots_graph.nodes || !bots_graph.link_first || !bots_graph.links || + !bots_routes.cost || !bots_routes.previous || !bots_routes.heap || !bots_routes.heap_position) + { + platform_log("bots: routes: no memory for %ld walkable surfaces", count); + bots_routes_free(); + return FALSE; + } + for (index = 0; index < bots_routes.surface_count; index++) + bots_routes.node_of_surface[index] = NONE; + bots_routes.base_set = 0; + bots_routes.machine_surfaces = 0; + bots_graph.node_count = 0; + bots_graph.link_count = 0; + bots_routes.cursor = 0; + return TRUE; +} + +/* the machines, and the scenery that is a door, whose ground the graph +leaves out: the way under Sidewinder's blast door between the bases, scenery +that never opens and that bots.c's searches learn to be in the way, would be +the direct route */ +static void bots_routes_find_machines(void) +{ + struct object_iterator iterator; + + bots_routes.machine_count = 0; + object_iterator_new(&iterator, _object_mask_machine | _object_mask_scenery, 0); + while (object_iterator_next(&iterator) && bots_routes.machine_count < BOTS_ROUTES_MACHINES) + { + struct object_datum *object = object_get(iterator.index); + char const *name = tag_get_name(object->definition_index); + + if (!object_try_and_get_and_verify_type(iterator.index, _object_mask_machine) && (!name || !strstr(name, "door"))) + continue; + bots_routes.machine_centers[bots_routes.machine_count] = object->object.bounding_sphere_center; + bots_routes.machine_radii[bots_routes.machine_count] = object->object.bounding_sphere_radius; + bots_routes.machine_count++; + } +} + +/* the nodes: a step of the walkable surfaces' middles, areas and slopes; TRUE +when all are made */ +static boolean bots_routes_nodes_step(void) +{ + struct collision_bsp const *bsp = bots_routes_bsp(); + long last = MIN(bots_routes.cursor + BOTS_ROUTES_SURFACES_A_TICK, bots_routes.surface_count); + + for (; bots_routes.cursor < last; bots_routes.cursor++) + { + long surface_index = bots_routes.cursor; + real_point3d corners[BOTS_ROUTES_CORNERS]; + long neighbours[BOTS_ROUTES_CORNERS]; + struct bots_graph_node *node; + real_vector3d normal = { 0.0f, 0.0f, 0.0f }; + long count, corner; + real reach; + + if (!bots_routes_walkable(surface_index)) + continue; + count = bots_routes_corners(bsp, surface_index, corners, neighbours); + if (count < 3) + continue; + node = &bots_graph.nodes[bots_graph.node_count]; + node->middle.x = node->middle.y = node->middle.z = 0.0f; + for (corner = 0; corner < count; corner++) + { + node->middle.x += corners[corner].x / (real)count; + node->middle.y += corners[corner].y / (real)count; + node->middle.z += corners[corner].z / (real)count; + } + /* (the area and the normal: the fan of triangles from the first corner) */ + for (corner = 1; corner + 1 < count; corner++) + { + real_vector3d a, b, c; + + vector_from_points3d(&corners[0], &corners[corner], &a); + vector_from_points3d(&corners[0], &corners[corner + 1], &b); + cross_product3d(&a, &b, &c); + normal.i += c.i; + normal.j += c.j; + normal.k += c.k; + } + /* (not under a machine: the surface reaching into its sphere) */ + reach = 0.0f; + for (corner = 0; corner < count; corner++) + reach = MAX(reach, bots_routes_distance2d(&node->middle, &corners[corner])); + for (corner = 0; corner < bots_routes.machine_count; corner++) + { + real_point3d const *center = &bots_routes.machine_centers[corner]; + real radius = bots_routes.machine_radii[corner]; + + if (bots_routes_distance2d(&node->middle, center) < radius * 0.8f + reach && + node->middle.z > center->z - radius - 1.0f && node->middle.z < center->z + radius) + { + break; + } + } + if (corner < bots_routes.machine_count) + { + bots_routes.machine_surfaces++; + continue; + } + node->area = 0.5f * (real)sqrt(normal.i * normal.i + normal.j * normal.j + normal.k * normal.k); + node->normal_k = node->area > 0.0f ? (real)fabs(normal.k) * 0.5f / node->area : 0.0f; + node->surface_index = surface_index; + node->cost = REAL_MAX; + node->route_distance = 0.0f; + node->route_side = 0.0f; + node->route_along = 0.0f; + /* (its walkable neighbours' surfaces, made nodes' indices once all + are made: bots_routes_links_step) */ + bots_graph.link_first[bots_graph.node_count] = bots_graph.link_count; + for (corner = 0; corner < count; corner++) + { + if (!bots_routes_walkable(neighbours[corner])) + continue; + if (bots_graph.link_count >= bots_routes.link_capacity) + { + long capacity = bots_routes.link_capacity * 2; + long *links = (long *)realloc(bots_graph.links, sizeof(long) * (size_t)capacity); + + if (!links) + break; + bots_graph.links = links; + bots_routes.link_capacity = capacity; + } + bots_graph.links[bots_graph.link_count++] = neighbours[corner]; + } + bots_routes.node_of_surface[surface_index] = bots_graph.node_count; + bots_graph.node_count++; + } + if (bots_routes.cursor < bots_routes.surface_count) + return FALSE; + bots_graph.link_first[bots_graph.node_count] = bots_graph.link_count; + return TRUE; +} + +/* the links: a step of the nodes' neighbours' surfaces made nodes' indices +(those left out dropped, the links packed down in place); TRUE when all are */ +static boolean bots_routes_links_step(void) +{ + long last = MIN(bots_routes.cursor + BOTS_ROUTES_SURFACES_A_TICK * 4, bots_graph.node_count); + + for (; bots_routes.cursor < last; bots_routes.cursor++) + { + long node_index = bots_routes.cursor; + long first = bots_graph.link_first[node_index], end = bots_graph.link_first[node_index + 1], link; + + bots_graph.link_first[node_index] = bots_routes.link_write; + for (link = first; link < end; link++) + { + long other = bots_routes.node_of_surface[bots_graph.links[link]]; + + if (other != NONE) + bots_graph.links[bots_routes.link_write++] = other; + } + } + if (bots_routes.cursor < bots_graph.node_count) + return FALSE; + bots_graph.link_first[bots_graph.node_count] = bots_routes.link_write; + bots_graph.link_count = bots_routes.link_write; + return TRUE; +} + +/* the node of the walkable surface under a point, else the nearest node's */ +static long bots_routes_node_at(real_point3d const *point) +{ + long surface_index = bots_routes_ground(point, NULL); + long index, best = NONE; + real best_distance = REAL_MAX; + + if (surface_index >= 0 && surface_index < bots_routes.surface_count && + bots_routes.node_of_surface[surface_index] != NONE) + { + return bots_routes.node_of_surface[surface_index]; + } + for (index = 0; index < bots_graph.node_count; index++) + { + real distance = bots_routes_distance3d(&bots_graph.nodes[index].middle, point); + + if (distance < best_distance) + { + best_distance = distance; + best = index; + } + } + return best; +} + +/* the map's two bases: the CTF flag stands (every stock map has them, in +every gametype), else (set 1, or no way between those: Prisoner's on its +upper floor) the teams' starting locations' middles, else (set 2) the two +starting locations furthest apart; FALSE without */ +static boolean bots_routes_find_bases(long set, real_point3d *bases) +{ + struct scenario *scenario = global_scenario_get(); + boolean found[2] = { FALSE, FALSE }; + real_point3d sums[2]; + long counts[2] = { 0, 0 }; + long index, other; + real best = 0.0f; + + if (!scenario) + return FALSE; + for (index = 0; index < scenario->netgame_flags.count; index++) + { + struct scenario_netgame_flag *flag = TAG_BLOCK_GET_ELEMENT(&scenario->netgame_flags, index, struct scenario_netgame_flag); + + if (flag->type == _netgame_flag_ctf_flag && (flag->team_index == 0 || flag->team_index == 1) && + !found[flag->team_index]) + { + bases[flag->team_index] = flag->position; + found[flag->team_index] = TRUE; + } + } + if (found[0] && found[1] && set <= 0) + return TRUE; + csmemset(sums, 0, sizeof(sums)); + for (index = 0; index < scenario->players.count; index++) + { + struct player_starting_location *location = + TAG_BLOCK_GET_ELEMENT(&scenario->players, index, struct player_starting_location); + + if (location->team_index == 0 || location->team_index == 1) + { + sums[location->team_index].x += location->position.x; + sums[location->team_index].y += location->position.y; + sums[location->team_index].z += location->position.z; + counts[location->team_index]++; + } + } + if (counts[0] > 0 && counts[1] > 0) + { + for (index = 0; index < 2; index++) + { + bases[index].x = sums[index].x / (real)counts[index]; + bases[index].y = sums[index].y / (real)counts[index]; + bases[index].z = sums[index].z / (real)counts[index]; + } + if (bots_routes_distance2d(&bases[0], &bases[1]) > 10.0f && set <= 1) + return TRUE; + } + for (index = 0; index < scenario->players.count; index++) + { + struct player_starting_location *a = TAG_BLOCK_GET_ELEMENT(&scenario->players, index, struct player_starting_location); + + for (other = index + 1; other < scenario->players.count; other++) + { + struct player_starting_location *b = TAG_BLOCK_GET_ELEMENT(&scenario->players, other, struct player_starting_location); + real distance = bots_routes_distance2d(&a->position, &b->position); + + if (distance > best) + { + best = distance; + bases[0] = a->position; + bases[1] = b->position; + } + } + } + return best > 10.0f; +} + +/* ---------- the searches (Dijkstra's, a step of surfaces a tick) */ + +/* what entering a node costs a lane's search: the nearer the direct route +the dearer, and the other side of it dearer still; neither near the bases +(the first and last sixth of the way, full from a third on), which every +way leaves and comes to */ +static real bots_routes_weight(long node_index) +{ + struct bots_graph_node const *node = &bots_graph.nodes[node_index]; + real weight = 1.0f, middle; + + if (bots_routes.lane_side == 0.0f) + return 1.0f; + middle = MIN(node->route_along, 1.0f - node->route_along); + middle = PIN((middle - 0.15f) / 0.15f, 0.0f, 1.0f); + if (middle <= 0.0f) + return 1.0f; + if (node->route_distance < bots_routes.penalty_radius) + weight += 4.0f * middle * (1.0f - node->route_distance / bots_routes.penalty_radius); + if (node->route_side * bots_routes.lane_side < 0.0f && node->route_distance > 2.0f) + weight += 10.0f * middle; + return weight; +} + +static boolean bots_routes_heap_less(long a, long b) +{ + return bots_routes.cost[bots_routes.heap[a]] < bots_routes.cost[bots_routes.heap[b]]; +} + +static void bots_routes_heap_swap(long a, long b) +{ + long node = bots_routes.heap[a]; + + bots_routes.heap[a] = bots_routes.heap[b]; + bots_routes.heap[b] = node; + bots_routes.heap_position[bots_routes.heap[a]] = a; + bots_routes.heap_position[bots_routes.heap[b]] = b; +} + +static void bots_routes_heap_up(long position) +{ + while (position > 0 && bots_routes_heap_less(position, (position - 1) / 2)) + { + bots_routes_heap_swap(position, (position - 1) / 2); + position = (position - 1) / 2; + } +} + +static void bots_routes_heap_down(long position) +{ + for (;;) + { + long child = position * 2 + 1, best = position; + + if (child < bots_routes.heap_count && bots_routes_heap_less(child, best)) + best = child; + if (child + 1 < bots_routes.heap_count && bots_routes_heap_less(child + 1, best)) + best = child + 1; + if (best == position) + return; + bots_routes_heap_swap(position, best); + position = best; + } +} + +static void bots_routes_search_start(long origin, long target, real lane_side) +{ + long index; + + for (index = 0; index < bots_graph.node_count; index++) + { + bots_routes.cost[index] = REAL_MAX; + bots_routes.previous[index] = NONE; + bots_routes.heap_position[index] = NONE; + } + bots_routes.origin = origin; + bots_routes.target = target; + bots_routes.lane_side = lane_side; + bots_routes.cost[origin] = 0.0f; + bots_routes.heap[0] = origin; + bots_routes.heap_position[origin] = 0; + bots_routes.heap_count = 1; +} + +/* a step of the search; TRUE when done (every node reached taken, or the +target, when there is one) */ +static boolean bots_routes_search_step(void) +{ + long pops; + + for (pops = 0; pops < BOTS_ROUTES_POPS_A_TICK && bots_routes.heap_count > 0; pops++) + { + long node_index = bots_routes.heap[0]; + real node_weight = bots_routes_weight(node_index); + long link; + + bots_routes.heap_count--; + if (bots_routes.heap_count > 0) + { + bots_routes.heap[0] = bots_routes.heap[bots_routes.heap_count]; + bots_routes.heap_position[bots_routes.heap[0]] = 0; + bots_routes_heap_down(0); + } + bots_routes.heap_position[node_index] = -2; + if (node_index == bots_routes.target) + return TRUE; + for (link = bots_graph.link_first[node_index]; link < bots_graph.link_first[node_index + 1]; link++) + { + long other = bots_graph.links[link]; + real cost; + + if (bots_routes.heap_position[other] == -2) + continue; + cost = bots_routes.cost[node_index] + bots_routes_distance3d(&bots_graph.nodes[node_index].middle, + &bots_graph.nodes[other].middle) * 0.5f * (node_weight + bots_routes_weight(other)); + if (cost >= bots_routes.cost[other]) + continue; + bots_routes.cost[other] = cost; + bots_routes.previous[other] = node_index; + if (bots_routes.heap_position[other] == NONE) + { + bots_routes.heap[bots_routes.heap_count] = other; + bots_routes.heap_position[other] = bots_routes.heap_count; + bots_routes.heap_count++; + } + bots_routes_heap_up(bots_routes.heap_position[other]); + } + } + return bots_routes.heap_count <= 0; +} + +/* ---------- the direct route */ + +void bots_routes_place_on_route(real_point3d const *point, real *along, real *offset) +{ + long index, best = 0; + real best_distance = REAL_MAX, best_u = 0.0f, best_side = 1.0f; + + *along = 0.0f; + *offset = 0.0f; + if (bots_routes_map.route_point_count < 2 || bots_routes_map.route_length <= 0.0f) + return; + for (index = 0; index + 1 < bots_routes_map.route_point_count; index++) + { + real_point3d const *a = &bots_routes_map.route_points[index], *b = &bots_routes_map.route_points[index + 1]; + real dx = b->x - a->x, dy = b->y - a->y, px = point->x - a->x, py = point->y - a->y; + real length2 = dx * dx + dy * dy; + real u = length2 > 0.0001f ? (px * dx + py * dy) / length2 : 0.0f; + real cx, cy, distance; + + u = PIN(u, 0.0f, 1.0f); + cx = a->x + dx * u - point->x; + cy = a->y + dy * u - point->y; + distance = (real)sqrt(cx * cx + cy * cy); + if (distance < best_distance) + { + best_distance = distance; + best = index; + best_u = u; + best_side = dx * py - dy * px >= 0.0f ? 1.0f : -1.0f; + } + } + *along = (bots_routes.point_lengths[best] + bots_routes.segment_lengths[best] * best_u) / bots_routes_map.route_length; + *offset = best_distance * best_side; +} + +/* the direct route from the search's way back from the second base: its +points every sixteenth of its length (2D), FALSE when the second base was +not reached */ +static boolean bots_routes_make_direct(void) +{ + long node_index, count = 0, point; + real total = 0.0f, walked = 0.0f; + long *route; + + if (bots_routes.cost[bots_routes.target] >= REAL_MAX) + return FALSE; + for (node_index = bots_routes.target; node_index != NONE; node_index = bots_routes.previous[node_index]) + count++; + route = (long *)malloc(sizeof(long) * (size_t)count); + if (!route) + return FALSE; + point = count; + for (node_index = bots_routes.target; node_index != NONE; node_index = bots_routes.previous[node_index]) + route[--point] = node_index; + for (point = 0; point + 1 < count; point++) + total += bots_routes_distance2d(&bots_graph.nodes[route[point]].middle, &bots_graph.nodes[route[point + 1]].middle); + if (total < 1.0f || count < 2) + { + free(route); + return FALSE; + } + bots_routes_map.route_points[0] = bots_graph.nodes[route[0]].middle; + bots_routes_map.route_point_count = 1; + for (point = 0; point + 1 < count && bots_routes_map.route_point_count < BOTS_ROUTE_POINTS; point++) + { + real_point3d const *a = &bots_graph.nodes[route[point]].middle, *b = &bots_graph.nodes[route[point + 1]].middle; + real step = bots_routes_distance2d(a, b); + + while (step > 0.0f && bots_routes_map.route_point_count < BOTS_ROUTE_POINTS - 1 && + walked + step >= total * (real)bots_routes_map.route_point_count / (real)(BOTS_ROUTE_POINTS - 1)) + { + real u = (total * (real)bots_routes_map.route_point_count / (real)(BOTS_ROUTE_POINTS - 1) - walked) / step; + real_point3d *p = &bots_routes_map.route_points[bots_routes_map.route_point_count++]; + + p->x = a->x + (b->x - a->x) * u; + p->y = a->y + (b->y - a->y) * u; + p->z = a->z + (b->z - a->z) * u; + } + walked += step; + } + bots_routes_map.route_points[bots_routes_map.route_point_count++] = bots_graph.nodes[route[count - 1]].middle; + free(route); + bots_routes_map.route_length = 0.0f; + for (point = 0; point < bots_routes_map.route_point_count; point++) + { + bots_routes.point_lengths[point] = bots_routes_map.route_length; + bots_routes.segment_lengths[point] = point + 1 < bots_routes_map.route_point_count ? + bots_routes_distance2d(&bots_routes_map.route_points[point], &bots_routes_map.route_points[point + 1]) : 0.0f; + bots_routes_map.route_length += bots_routes.segment_lengths[point]; + } + return bots_routes_map.route_length > 1.0f; +} + +/* a step of the nodes placed across the direct route; TRUE when done */ +static boolean bots_routes_place_step(void) +{ + long last = MIN(bots_routes.cursor + BOTS_ROUTES_NODES_A_TICK, bots_graph.node_count); + + for (; bots_routes.cursor < last; bots_routes.cursor++) + { + struct bots_graph_node *node = &bots_graph.nodes[bots_routes.cursor]; + real offset; + + bots_routes_place_on_route(&node->middle, &node->route_along, &offset); + node->route_distance = (real)fabs(offset); + node->route_side = offset >= 0.0f ? 1.0f : -1.0f; + } + return bots_routes.cursor >= bots_graph.node_count; +} + +/* (debug) HALO_BOT_ROUTES_DUMP=: the walkable graph's nodes (where, +how far off the direct route, reached) and each lane's surfaces, for a +picture of them */ +static void bots_routes_dump(char const *what, long const *route, long count) +{ + char const *name = getenv("HALO_BOT_ROUTES_DUMP"); + FILE *file; + long index; + + if (!name || !name[0] || !(file = fopen(name, route ? "a" : "w"))) + return; + if (!route) + { + for (index = 0; index < bots_graph.node_count; index++) + { + struct bots_graph_node const *node = &bots_graph.nodes[index]; + + fprintf(file, "node %.2f %.2f %.2f %.2f %.0f %d\n", node->middle.x, node->middle.y, node->middle.z, + node->route_distance, node->route_side, node->cost < REAL_MAX); + } + for (index = 0; index < bots_routes_map.route_point_count; index++) + fprintf(file, "route %.2f %.2f %.2f\n", bots_routes_map.route_points[index].x, bots_routes_map.route_points[index].y, + bots_routes_map.route_points[index].z); + } + for (index = 0; route && index < count; index++) + { + struct bots_graph_node const *node = &bots_graph.nodes[route[index]]; + + fprintf(file, "%s %.2f %.2f %.2f\n", what, node->middle.x, node->middle.y, node->middle.z); + } + fclose(file); +} + +/* ---------- the side lanes */ + +/* the lane's search done: its way back made the lane, if it is one */ +static void bots_routes_make_lane(long lane_index) +{ + struct bots_lane *lane = &bots_routes.lanes[lane_index]; + long node_index, count = 0, point, waypoint, peak = NONE; + real length = 0.0f, offset = 0.0f, walked; + long *route; + char const *why = NULL; + + csmemset(lane, 0, sizeof(*lane)); + if (bots_routes.cost[bots_routes.target] >= REAL_MAX) + { + platform_log("bots: routes: lane %ld: none (the second base not reached)", lane_index + 1); + return; + } + for (node_index = bots_routes.target; node_index != NONE; node_index = bots_routes.previous[node_index]) + count++; + route = (long *)malloc(sizeof(long) * (size_t)count); + if (!route) + return; + point = count; + for (node_index = bots_routes.target; node_index != NONE; node_index = bots_routes.previous[node_index]) + route[--point] = node_index; + for (point = 0; point < count; point++) + { + struct bots_graph_node const *node = &bots_graph.nodes[route[point]]; + + if (point > 0) + length += bots_routes_distance3d(&bots_graph.nodes[route[point - 1]].middle, &node->middle); + if (node->route_along > 0.15f && node->route_along < 0.85f && node->route_distance > offset) + { + offset = node->route_distance; + peak = point; + } + } + lane->length = length; + lane->offset = offset; + bots_routes_dump(lane_index ? "lane2" : "lane1", route, count); + if (peak == NONE || offset < MAX(5.0f, bots_routes_map.route_length * 0.08f)) + why = "it keeps near the direct route"; + else if (length > bots_routes_map.route_length * 2.2f) + why = "too long"; + /* the waypoints: its surfaces a third and two thirds of the way along + it, those well off the direct route; else the one furthest off */ + if (!why) + { + static real const fractions[BOTS_LANE_WAYPOINTS] = { 0.33f, 0.67f }; + + for (waypoint = 0; waypoint < BOTS_LANE_WAYPOINTS; waypoint++) + { + long best = NONE; + real best_difference = REAL_MAX; + + walked = 0.0f; + for (point = 0; point < count; point++) + { + struct bots_graph_node const *node = &bots_graph.nodes[route[point]]; + + if (point > 0) + walked += bots_routes_distance3d(&bots_graph.nodes[route[point - 1]].middle, &node->middle); + if (node->route_distance >= offset * 0.5f && node->route_along > 0.1f && node->route_along < 0.9f && + fabs(walked / length - fractions[waypoint]) < best_difference) + { + best_difference = (real)fabs(walked / length - fractions[waypoint]); + best = route[point]; + } + } + if (best == NONE || (lane->waypoint_count > 0 && + bots_routes_distance2d(&lane->waypoints[lane->waypoint_count - 1].point, &bots_graph.nodes[best].middle) < 8.0f)) + { + continue; + } + lane->waypoints[lane->waypoint_count].point = bots_graph.nodes[best].middle; + lane->waypoints[lane->waypoint_count].surface_index = bots_graph.nodes[best].surface_index; + lane->waypoints[lane->waypoint_count].along = bots_graph.nodes[best].route_along; + lane->waypoint_count++; + } + if (!lane->waypoint_count) + { + lane->waypoints[0].point = bots_graph.nodes[route[peak]].middle; + lane->waypoints[0].surface_index = bots_graph.nodes[route[peak]].surface_index; + lane->waypoints[0].along = bots_graph.nodes[route[peak]].route_along; + lane->waypoint_count = 1; + } + /* (in order along the direct route) */ + if (lane->waypoint_count == 2 && lane->waypoints[0].along > lane->waypoints[1].along) + { + struct bots_lane_waypoint first = lane->waypoints[0]; + + lane->waypoints[0] = lane->waypoints[1]; + lane->waypoints[1] = first; + } + } + /* (the second lane by the first's waypoints: the same lane) */ + if (!why && lane_index == 1 && bots_routes.lanes[0].valid) + { + long a, b; + + for (a = 0; a < bots_routes.lanes[0].waypoint_count; a++) + { + for (b = 0; b < lane->waypoint_count; b++) + { + if (bots_routes_distance2d(&bots_routes.lanes[0].waypoints[a].point, &lane->waypoints[b].point) < 10.0f) + why = "the first lane's"; + } + } + } + free(route); + if (why) + { + lane->waypoint_count = 0; + platform_log("bots: routes: lane %ld: none (%s: %.0f units, %.0f off the direct route at most)", lane_index + 1, why, + length, offset); + return; + } + lane->valid = TRUE; + bots_routes_map.lane_count++; + if (lane->waypoint_count == 2) + { + platform_log("bots: routes: lane %ld by (%.1f %.1f %.1f) (%.1f %.1f %.1f): %.0f units (the direct route %.0f), %.0f off it at most", + lane_index + 1, lane->waypoints[0].point.x, lane->waypoints[0].point.y, lane->waypoints[0].point.z, + lane->waypoints[1].point.x, lane->waypoints[1].point.y, lane->waypoints[1].point.z, length, + bots_routes_map.route_length, offset); + } + else + { + platform_log("bots: routes: lane %ld by (%.1f %.1f %.1f): %.0f units (the direct route %.0f), %.0f off it at most", + lane_index + 1, lane->waypoints[0].point.x, lane->waypoints[0].point.y, lane->waypoints[0].point.z, length, + bots_routes_map.route_length, offset); + } +} + +/* ---------- making them: a step a tick */ + +static void bots_routes_log_direct(void) +{ + char line[600]; + int length = 0; + long point; + + for (point = 0; point < bots_routes_map.route_point_count && length < (int)sizeof(line) - 30; point++) + { + int written = snprintf(line + length, sizeof(line) - (size_t)length, " (%.1f %.1f)", bots_routes_map.route_points[point].x, + bots_routes_map.route_points[point].y); + /* snprintf returns the required length, even for extreme map coordinates. */ + if (written < 0 || written >= (int)sizeof(line) - length) + break; + length += written; + } + line[length] = 0; + platform_log("bots: routes: walkable graph of %ld surfaces (%ld links; %ld under %ld machines left out), bases (%.1f %.1f %.1f) " + "and (%.1f %.1f %.1f); the direct route %.0f units:%s", bots_graph.node_count, bots_graph.link_count, + bots_routes.machine_surfaces, bots_routes.machine_count, bots_routes_map.bases[0].x, + bots_routes_map.bases[0].y, bots_routes_map.bases[0].z, bots_routes_map.bases[1].x, bots_routes_map.bases[1].y, + bots_routes_map.bases[1].z, bots_routes_map.route_length, line); +} + +/* a step of the map's routes; TRUE once they are made (or the map has none) */ +boolean bots_routes_step(void) +{ + switch (bots_routes.phase) + { + case _routes_phase_idle: + bots_routes.phase = bots_routes_begin() ? _routes_phase_machines : _routes_phase_none; + break; + case _routes_phase_machines: + bots_routes_find_machines(); + bots_routes.phase = _routes_phase_nodes; + break; + case _routes_phase_nodes: + if (bots_routes_nodes_step()) + { + bots_routes.cursor = 0; + bots_routes.link_write = 0; + bots_routes.phase = _routes_phase_links; + } + break; + case _routes_phase_links: + if (bots_routes_links_step()) + bots_routes.phase = _routes_phase_bases; + break; + case _routes_phase_bases: + { + real_point3d bases[2]; + long a, b; + + if (bots_graph.node_count < 8 || !bots_routes_find_bases(bots_routes.base_set, bases)) + { + platform_log("bots: routes: no bases found: no lanes"); + bots_routes.phase = _routes_phase_none; + break; + } + a = bots_routes_node_at(&bases[0]); + b = bots_routes_node_at(&bases[1]); + if (a == NONE || b == NONE || a == b) + { + platform_log("bots: routes: the bases are on no walkable surface: no lanes"); + bots_routes.phase = _routes_phase_none; + break; + } + bots_routes_map.bases[0] = bots_graph.nodes[a].middle; + bots_routes_map.bases[1] = bots_graph.nodes[b].middle; + bots_routes_map.base_surfaces[0] = bots_graph.nodes[a].surface_index; + bots_routes_map.base_surfaces[1] = bots_graph.nodes[b].surface_index; + bots_routes_map.has_bases = TRUE; + bots_routes.base_nodes[0] = a; + bots_routes.base_nodes[1] = b; + /* (the whole graph from the first base: its costs say what is reached) */ + bots_routes_search_start(a, NONE, 0.0f); + bots_routes.phase = _routes_phase_direct; + break; + } + case _routes_phase_direct: + if (bots_routes_search_step()) + { + long index; + + for (index = 0; index < bots_graph.node_count; index++) + bots_graph.nodes[index].cost = bots_routes.cost[index]; + bots_routes.costs_made = TRUE; + bots_routes.target = bots_routes.base_nodes[1]; + /* (no way between them: the next bases) */ + if (bots_routes.cost[bots_routes.target] >= REAL_MAX && bots_routes.base_set < 2) + { + platform_log("bots: routes: no way between the bases (%.1f %.1f %.1f) and (%.1f %.1f %.1f): others", + bots_routes_map.bases[0].x, bots_routes_map.bases[0].y, bots_routes_map.bases[0].z, + bots_routes_map.bases[1].x, bots_routes_map.bases[1].y, bots_routes_map.bases[1].z); + bots_routes.base_set++; + bots_routes_map.has_bases = FALSE; + bots_routes.phase = _routes_phase_bases; + break; + } + if (!bots_routes_make_direct()) + { + platform_log("bots: routes: no way between the bases: no lanes"); + bots_routes_map.has_bases = FALSE; + bots_routes.phase = _routes_phase_none; + break; + } + bots_routes_log_direct(); + bots_routes.cursor = 0; + bots_routes.phase = _routes_phase_place; + } + break; + case _routes_phase_place: + if (bots_routes_place_step()) + { + bots_routes_dump(NULL, NULL, 0); + bots_routes.penalty_radius = PIN(bots_routes_map.route_length * 0.15f, 6.0f, 18.0f); + bots_routes.lane_index = 0; + bots_routes_search_start(bots_routes.base_nodes[0], bots_routes.base_nodes[1], 1.0f); + bots_routes.phase = _routes_phase_lanes; + } + break; + case _routes_phase_lanes: + if (bots_routes_search_step()) + { + bots_routes_make_lane(bots_routes.lane_index); + if (++bots_routes.lane_index < BOTS_SIDE_LANES) + bots_routes_search_start(bots_routes.base_nodes[0], bots_routes.base_nodes[1], -1.0f); + else + { + /* (the second lane but not the first: it is the first) */ + if (!bots_routes.lanes[0].valid && bots_routes.lanes[1].valid) + { + bots_routes.lanes[0] = bots_routes.lanes[1]; + bots_routes.lanes[1].valid = FALSE; + } + bots_routes.phase = _routes_phase_done; + } + } + break; + case _routes_phase_done: + case _routes_phase_none: + bots_routes_map.ready = TRUE; + return TRUE; + } + return FALSE; +} + +/* whether the graph is there to read (the vantage points' making) */ +boolean bots_routes_graph_made(void) +{ + return bots_routes.costs_made && bots_graph.nodes != NULL; +} + +/* ---------- a bot's lane */ + +static boolean bots_routes_lane_valid(short lane) +{ + return lane >= 1 && lane <= BOTS_SIDE_LANES && bots_routes.lanes[lane - 1].valid; +} + +/* the lane of the bot of this rank among its team's attackers (0 the direct +route): Lanes the direct, the first and the second in turn; Mixed every +third a side lane, the first and the second in turn */ +short bots_routes_lane_for_rank(short rank) +{ + short lane = 0; + + if (bots_routes.mode == _bots_routes_lanes) + lane = (short)(rank % 3); + else if (bots_routes.mode == _bots_routes_mixed) + lane = rank % 3 == 1 ? (short)((rank / 3) % 2 + 1) : 0; + if (lane && !bots_routes_lane_valid(lane)) + lane = bots_routes_lane_valid(1) ? 1 : 0; + return lane; +} + +boolean bots_routes_search_goal(long bot_index, real_point3d const *start, real_point3d *goal, long *surface_index) +{ + struct bots_tactics_bot *state; + struct bots_lane const *lane; + real start_along, goal_along, offset, travel; + long index, best = NONE; + + if (bot_index < 0 || bot_index >= BOTS_MAXIMUM) + return FALSE; + state = &bots_tactics_bots[bot_index]; + if (bots_routes.mode == _bots_routes_direct || !bots_routes_map.ready || !bots_routes_lane_valid(state->lane) || + state->lane_given_up || state->vantage != NONE || bots_routes_distance2d(start, goal) < BOTS_LANE_LEAST_DISTANCE) + { + state->waypoint = NONE; + return FALSE; + } + lane = &bots_routes.lanes[state->lane - 1]; + bots_routes_place_on_route(start, &start_along, &offset); + bots_routes_place_on_route(goal, &goal_along, &offset); + travel = goal_along - start_along; + if (fabs(travel) >= 0.2f) + { + /* (the first waypoint on the way, in the way the bot goes) */ + for (index = 0; index < lane->waypoint_count && best == NONE; index++) + { + long waypoint = travel > 0.0f ? index : lane->waypoint_count - 1 - index; + real along = lane->waypoints[waypoint].along; + + if (state->passed[waypoint]) + continue; + if (travel > 0.0f ? along > start_along + 0.03f && along < goal_along - 0.03f : + along < start_along - 0.03f && along > goal_along + 0.03f) + { + best = waypoint; + } + } + } + if (best == NONE) + { + state->waypoint = NONE; + return FALSE; + } + if (state->waypoint != best) + { + state->waypoint = (short)best; + state->waypoint_tick = game_time_get(); + bots_tactics_counts.lanes_taken++; + } + *goal = lane->waypoints[best].point; + *surface_index = lane->waypoints[best].surface_index; + return TRUE; +} + +boolean bots_routes_waypoint_reached(long bot_index, real_point3d const *position) +{ + struct bots_tactics_bot *state; + real_point3d const *point; + + if (bot_index < 0 || bot_index >= BOTS_MAXIMUM) + return FALSE; + state = &bots_tactics_bots[bot_index]; + if (state->waypoint == NONE || !bots_routes_lane_valid(state->lane)) + return FALSE; + point = &bots_routes.lanes[state->lane - 1].waypoints[state->waypoint].point; + if (bots_routes_distance2d(point, position) < BOTS_LANE_WAYPOINT_REACHED && fabs(point->z - position->z) < 2.5f) + { + state->passed[state->waypoint] = TRUE; + state->waypoint = NONE; + bots_tactics_counts.waypoints_passed++; + return TRUE; + } + if (game_time_get() - state->waypoint_tick > TICKS_PER_SECOND * BOTS_LANE_WAYPOINT_SECONDS) + { + state->lane_given_up = TRUE; + state->waypoint = NONE; + bots_tactics_counts.lanes_given_up++; + return TRUE; + } + return FALSE; +} + +/* whether the goal a search went to is the bot's waypoint, given up then */ +boolean bots_routes_search_failed(long bot_index, real_point3d const *goal) +{ + struct bots_tactics_bot *state = &bots_tactics_bots[bot_index]; + + if (state->waypoint == NONE || !bots_routes_lane_valid(state->lane) || + bots_routes_distance3d(goal, &bots_routes.lanes[state->lane - 1].waypoints[state->waypoint].point) > 0.5f) + { + return FALSE; + } + state->lane_given_up = TRUE; + state->waypoint = NONE; + bots_tactics_counts.lanes_given_up++; + return TRUE; +} + +/* the lane's name for halo.log */ +char const *bots_routes_lane_name(short lane) +{ + return lane == 1 ? "lane 1" : lane == 2 ? "lane 2" : "direct"; +} + +/* a lane's waypoint (for the vantage points' places): FALSE past the last */ +boolean bots_routes_lane_waypoint(long lane_index, long waypoint, real_point3d *point) +{ + if (lane_index < 0 || lane_index >= BOTS_SIDE_LANES || !bots_routes.lanes[lane_index].valid || + waypoint < 0 || waypoint >= bots_routes.lanes[lane_index].waypoint_count) + { + return FALSE; + } + *point = bots_routes.lanes[lane_index].waypoints[waypoint].point; + return TRUE; +} diff --git a/port/linux/game/bots_tactics.h b/port/linux/game/bots_tactics.h new file mode 100644 index 0000000000..88f638ce4b --- /dev/null +++ b/port/linux/game/bots_tactics.h @@ -0,0 +1,299 @@ +/* Source: thelinkin3000/halo-ce-universal, commit + * d92cc93385edf03d0a4a21cfe4c58dd578a3e786, port/linux/game/bots_tactics.h. + * Derived from BirchWoodGod/halo-ce-vita (GPL-3.0-only). + * Used only by GulchCE's optional enhanced bots. + */ +/* Host-owned roles, lane waypoints and vantage choices for enhanced bots. +Prepared geometry is per-map; per-bot state is reset on respawn. No state +here is replicated: the host publishes ordinary player actions. */ +#ifndef HALO_BOTS_TACTICS_H +#define HALO_BOTS_TACTICS_H + +/* ---------- routes */ + +enum +{ + /* every bot the shortest way (the bots before: all down the middle) */ + _bots_routes_direct = 0, + /* the attackers spread over the map's lanes: the direct route and up to + two side lanes */ + _bots_routes_lanes, + /* most the direct route, every third attacker a side lane */ + _bots_routes_mixed, + NUMBER_OF_BOTS_ROUTES, +}; + +/* a bot's part in its team (bots_roles.c) */ +enum +{ + /* the game's objective (the flag, the hill, the ball, the race) */ + _bots_role_attacker = 0, + /* CTF: near its flag stand; King: near the hill. */ + _bots_role_defender, + /* Slayer: about the map, after the enemy */ + _bots_role_roamer, + NUMBER_OF_BOTS_ROLES, +}; + +/* what kind of a precision weapon the bot holds (bots.c's +bots_weapon_precision, from the weapon's tag) */ +enum +{ + /* none: the bot as before */ + _bots_precision_none = 0, + /* a zoom and a bullet (the pistol): a vantage point near, held a little + while, by a roamer */ + _bots_precision_mid, + /* a scope and a bullet (the sniper rifle): a vantage point, held */ + _bots_precision_long, + /* a zoom and one slow projectile (the rocket launcher) */ + _bots_precision_heavy, +}; + +/* the most waypoints a lane goes by, side lanes, vantage points kept a map, +places they are scored by (the flag stands, the hills, the ball's spawns, +the direct route), and points of the direct route kept */ +#define BOTS_LANE_WAYPOINTS 2 +#define BOTS_SIDE_LANES 2 +#define BOTS_VANTAGE_MAXIMUM 6 +#define BOTS_PLACES_MAXIMUM 16 +#define BOTS_ROUTE_POINTS 17 + +/* ---------- what bots.c tells */ + +/* a map's start and end (bots.c's bots_initialize_for_new_map and +bots_dispose_from_old_map): all forgotten; the walkable graph's memory let go */ +void bots_tactics_initialize_for_new_map(void); +void bots_tactics_dispose_from_old_map(void); +/* once a bots' tick, before the bots: the setting, the map's lanes and +vantage points made a bounded step a tick, and the teams' roles */ +void bots_tactics_update(void); +/* a bot made for a player (bots_bot_reset: its index, its player), and a bot +dead (its vantage point let go, its lane's waypoints forgotten) */ +void bots_tactics_bot_reset(long bot_index, long player_index); +void bots_tactics_bot_dead(long bot_index); + +/* bots_choose_goal: a vantage point the bot goes to (and +holds), with its surface; FALSE for none (the game's goals as before) */ +boolean bots_tactics_goal(long bot_index, long player_index, real_point3d const *position, real_point3d *goal, + long *surface_index); +/* bots_search_ask, on foot to the goal given (an objective, a roaming place, +an enemy last seen): the waypoint of the bot's lane its search goes to +instead, into *goal and *surface_index; FALSE for the goal itself */ +boolean bots_routes_search_goal(long bot_index, real_point3d const *start, real_point3d *goal, long *surface_index); +/* bots_follow_path, each tick: TRUE when the bot has come to its lane's +waypoint (or gave it up): a new path, on to the goal */ +boolean bots_routes_waypoint_reached(long bot_index, real_point3d const *position); +/* bots_search_take: a search's answer for the goal it went to, reached or not +and its surfaces all tried (spent): TRUE when that was a waypoint or a +vantage point now given up (a new search, on to the goal) */ +boolean bots_tactics_search_answer(long bot_index, real_point3d const *goal, boolean reached, boolean spent); +/* bots_bot_walk, standing (not moving): where the bot looks, at a vantage +point (towards the places it watches), turned into *yaw and *pitch */ +void bots_tactics_look(long bot_index, real_point3d const *position, long now, real *yaw, real *pitch); +/* bots_bot_update, fighting on foot: at its vantage point the bot stays +there (*moving, *direction and *throttle changed), and leaves it when the +enemy comes this near */ +void bots_tactics_fight(long bot_index, real_point3d const *position, real target_distance, boolean *moving, + real *direction, real *throttle); +/* bots_choose_goal, first: off its vantage point when it is time (its +weapon changed, nearly empty, hurt, its time up), whatever it goes for +meanwhile (a powerup, a vehicle) */ +void bots_tactics_check(long bot_index, long player_index); +/* bots_choose_goal: the game's objective comes first now (the flag or the +ball carried, its own flag to bring back, its carrier to chase): off its +vantage point */ +void bots_tactics_objective(long bot_index); +/* bots_target_score: how much further the bot sees an enemy (1 as before; +more through its scope at its vantage point) */ +real bots_tactics_sight_scale(long bot_index); +/* bots_report, each minute: halo.log's tactics line */ +void bots_tactics_report(long now); + +/* ---------- between the three files */ + +/* a bot's part: its role and lane, its lane's waypoints, its vantage point */ +struct bots_tactics_bot +{ + long player_index; + unsigned long random; + /* its team (0 in a game without teams), its role, its lane (0 the direct + route, 1 and 2 the side lanes) and its place among its team's attackers */ + long team; + short role; + short lane; + short rank; + /* lanes: the waypoint its searches go by (of its lane's, NONE for + none), since when; the waypoints passed this life; the lane given up this + life (a waypoint it found no way to, or did not come to) */ + short waypoint; + long waypoint_tick; + boolean passed[BOTS_LANE_WAYPOINTS]; + boolean lane_given_up; + /* vantage: the point it goes to (NONE for none), since when, when it got + there (0 before) and for how long it holds it; none until then (after + one), the last held, and those it found no way to, not until then */ + short vantage; + long vantage_tick; + long hold_tick; + long hold_ticks; + long rest_until_tick; + short last_vantage; + unsigned long failed_vantages; + long failed_until_tick; + /* The precision category of the weapon used to hold this point. */ + short vantage_weapon; + /* the precision weapon of the vantage point it rests from (a sniper + rifle taken up after a pistol's: no rest) */ + short rest_weapon; + /* looking about there: at which watched place, until when */ + short look_place; + long look_until_tick; +}; + +extern struct bots_tactics_bot bots_tactics_bots[]; + +/* the map's walkable graph, while the lanes and vantage points are made +(bots_routes.c; let go once made): a node a walkable surface of the +structure (its middle, area, how flat, reached from the first base), and its +neighbours, the walkable surfaces across its edges */ +struct bots_graph_node +{ + real_point3d middle; + real area; + real normal_k; + long surface_index; + /* the cost of the way from the first base (REAL_MAX: not reached) */ + real cost; + /* across the direct route: how far from it, on which side, and how far + along it (0 at the first base, 1 at the second) */ + real route_distance; + real route_side; + real route_along; +}; + +struct bots_graph +{ + long node_count; + struct bots_graph_node *nodes; + long *link_first; + long *links; + long link_count; +}; + +extern struct bots_graph bots_graph; + +/* the map's places the bots care about (bots_vantage.c): the vantage points +are scored by what they see of them, and look at them */ +struct bots_place +{ + real_point3d point; + real weight; + char const *name; +}; + +/* what is known of the map once made (bots_routes.c): ready, the bases, the +direct route (points along it, its length), and whether it has lanes */ +struct bots_routes_map +{ + boolean ready; + boolean has_bases; + real_point3d bases[2]; + long base_surfaces[2]; + long route_point_count; + real_point3d route_points[BOTS_ROUTE_POINTS]; + real route_length; + long lane_count; +}; + +extern struct bots_routes_map bots_routes_map; + +/* bots_routes.c's: the setting (read once a second: bots_routes_read_setting); +the map's routes made a step a tick (TRUE once made), the graph let go +(once the vantage points are made too), all forgotten (a new map) */ +short bots_routes_mode(void); +void bots_routes_read_setting(void); +boolean bots_routes_step(void); +boolean bots_routes_graph_made(void); +void bots_routes_release_graph(void); +void bots_routes_reset(void); +/* the lane (0 the direct route) of the bot of this rank among its team's +attackers, by the setting; a lane's name; a side lane's waypoint (FALSE past +its last) */ +short bots_routes_lane_for_rank(short rank); +char const *bots_routes_lane_name(short lane); +boolean bots_routes_lane_waypoint(long lane_index, long waypoint, real_point3d *point); +/* a search to the bot's waypoint found no way: the lane given up (TRUE when +the goal was its waypoint) */ +boolean bots_routes_search_failed(long bot_index, real_point3d const *goal); +/* the direct route's polyline: how far along (0 to 1) and +how far off it (signed: the side) a point is */ +void bots_routes_place_on_route(real_point3d const *point, real *along, real *offset); +/* a point's ground: the walkable surface under it (NONE for none), and the +point there */ +long bots_routes_ground(real_point3d const *point, real_point3d *ground); +/* (debug: HALO_BOT_ROLES=0, neither roles nor vantage points: the bots as +before but for their routes) */ +boolean bots_tactics_enabled(void); +/* the gametype's engine (game_engine_ctf ...), read once a tick */ +long bots_tactics_game(void); +/* enhanced_bots.c: the precision of a weapon object (NONE: none) */ +short bots_weapon_precision(long weapon_index); +/* a bot's next random number (its own, seeded by its index and the game's) */ +unsigned long bots_tactics_random(struct bots_tactics_bot *state); + +/* bots_vantage.c's: the map's vantage points made after the routes, a step a +tick (TRUE when done); its memory let go; and a bot's vantage point let go */ +boolean bots_vantage_step(void); +void bots_vantage_dispose(void); +void bots_vantage_release(long bot_index); +/* the vantage point for a bot of the role: the best not another's, near +`position` and no further than `maximum_distance` from it (NONE for none); +for a CTF defender, one overlooking its team's stand, `objective` */ +short bots_vantage_choose(long bot_index, real_point3d const *position, real_point3d const *objective, + real maximum_distance); +/* a team's flag stand (the place the vantage points see; FALSE for none) */ +boolean bots_vantage_stand(long team, real_point3d *point); +/* A vantage point's ground and surface. */ +void bots_vantage_point(short vantage, real_point3d *point, long *surface_index); +long bots_vantage_count(void); +/* the places a vantage point sees (a bit a place), and the places */ +unsigned long bots_vantage_sees(short vantage); +long bots_places_count(void); +struct bots_place const *bots_place_get(long index); +/* why a bot left its vantage point */ +enum +{ + _bots_vantage_left_time = 0, + _bots_vantage_left_enemy, + _bots_vantage_left_ammunition, + _bots_vantage_left_hurt, + /* its precision weapon dropped or swapped for another */ + _bots_vantage_left_weapon, + /* the game's objective first (the flag, the ball) */ + _bots_vantage_left_objective, + _bots_vantage_left_other, + NUMBER_OF_BOTS_VANTAGE_LEFT, +}; + +/* the statistics of halo.log's tactics line */ +struct bots_tactics_counts +{ + long lanes_taken; + long waypoints_passed; + long lanes_given_up; + long vantages_chosen; + long vantages_reached; + long vantage_leaves[NUMBER_OF_BOTS_VANTAGE_LEFT]; + long vantage_failures; +}; + +extern struct bots_tactics_counts bots_tactics_counts; + +/* the platform layer's */ +const char *config_string(char const *name); +void platform_log(char const *format, ...); +/* bots.c's: whether each bot's state is logged (debug.bot_trace) */ +boolean bots_trace_enabled(void); + +#endif diff --git a/port/linux/game/bots_vantage.c b/port/linux/game/bots_vantage.c new file mode 100644 index 0000000000..e7efe506a1 --- /dev/null +++ b/port/linux/game/bots_vantage.c @@ -0,0 +1,721 @@ +/* Source: thelinkin3000/halo-ce-universal, commit + * d92cc93385edf03d0a4a21cfe4c58dd578a3e786, port/linux/game/bots_vantage.c. + * Derived from BirchWoodGod/halo-ce-vita (GPL-3.0-only). + * Used only by GulchCE's optional enhanced bots. + */ +/* Optional enhanced bots' vantage points: standing places with sight of +flag stands, hills, routes and item spawns. A bounded surface scan retains +30 candidates; two sight rays per tick score their coverage and openness. +Up to six separated spots survive. The temporary graph and height grid are +released after preparation; per-bot claims are released on death/unload. +Weapon and objective policy is in bots_roles.c and enhanced_bots.c. */ + +#include "cseries.h" +#include "game/game.h" +#include "game/game_engine.h" +#include "game/players.h" +#include "scenario/scenario.h" +#include "scenario/scenario_definitions.h" +#include "physics/collisions.h" +#include "tag_files/tag_groups.h" + +#include "bots.h" +#include "bots_tactics.h" +#include "bots_objectives.h" + +#include +#include +#include + +/* ---------- constants */ + +/* the spots looked at with rays, and how far apart */ +#define BOTS_VANTAGE_CANDIDATES 30 +#define BOTS_VANTAGE_CANDIDATE_SPACING 6.0f +/* the vantage points kept, how far apart */ +#define BOTS_VANTAGE_SPACING 12.0f +/* the work of a tick: surfaces scored, rays cast */ +#define BOTS_VANTAGE_NODES_A_TICK 200 +#define BOTS_VANTAGE_RAYS_A_TICK 2 +/* a bot's eyes above its feet, a place's middle above its ground */ +#define BOTS_VANTAGE_EYE_HEIGHT 0.62f +#define BOTS_PLACE_HEIGHT 0.55f +/* how far a place is seen, and the openness rays' length */ +#define BOTS_VANTAGE_SIGHT 90.0f +#define BOTS_VANTAGE_OPEN_RAYS 8 +#define BOTS_VANTAGE_OPEN_LENGTH 15.0f +/* the height grid's cells (world units) */ +#define BOTS_VANTAGE_CELL 8.0f +#define BOTS_VANTAGE_GRID_MAXIMUM 128 + +enum +{ + _vantage_phase_idle = 0, + _vantage_phase_bounds, + _vantage_phase_grid, + _vantage_phase_candidates, + _vantage_phase_rays, + _vantage_phase_done, +}; + +/* ---------- structures */ + +struct bots_vantage_spot +{ + real_point3d point; + long surface_index; + real height; + real first_score; + real score; + unsigned long sees; + short sees_count; + short open; +}; + +/* ---------- globals */ + +static struct +{ + short phase; + long cursor; + unsigned long long started_us; + /* the places */ + long place_count; + struct bots_place places[BOTS_PLACES_MAXIMUM]; + /* the height grid: its corner, size, and each cell's area and area-weighted + height */ + real grid_x; + real grid_y; + real grid_x1; + real grid_y1; + real cell; + long grid_width; + long grid_height; + real *grid_area; + real *grid_height_sum; + /* the spots scored */ + long candidate_count; + struct bots_vantage_spot candidates[BOTS_VANTAGE_CANDIDATES]; + long rays; + /* the vantage points, the bot going to each (NONE: none) */ + long count; + struct bots_vantage_spot points[BOTS_VANTAGE_MAXIMUM]; + long claims[BOTS_VANTAGE_MAXIMUM]; +} bots_vantage; + +/* ---------- small helpers */ + +static real bots_vantage_distance3d(real_point3d const *a, real_point3d const *b) +{ + real dx = a->x - b->x, dy = a->y - b->y, dz = a->z - b->z; + + return (real)sqrt(dx * dx + dy * dy + dz * dz); +} + +/* how much a place this far away counts: best from twelve to fifty units */ +static real bots_vantage_range(real distance) +{ + if (distance < 5.0f) + return 0.2f; + if (distance < 12.0f) + return 0.2f + 0.8f * (distance - 5.0f) / 7.0f; + if (distance < 50.0f) + return 1.0f; + if (distance < BOTS_VANTAGE_SIGHT) + return 1.0f - 0.7f * (distance - 50.0f) / (BOTS_VANTAGE_SIGHT - 50.0f); + return 0.0f; +} + +/* whether a ray from `from` to `to` meets nothing (the bots' line of sight +but for vehicles, which move) */ +static boolean bots_vantage_clear(real_point3d const *from, real_point3d const *to) +{ + struct collision_result collision; + real_vector3d vector; + + vector.i = to->x - from->x; + vector.j = to->y - from->y; + vector.k = to->z - from->z; + bots_vantage.rays++; + return !collision_test_vector(_collision_test_for_line_of_sight_flags & ~FLAG(_collision_test_objects_vehicles_bit), + from, &vector, NONE, &collision); +} + +static void bots_vantage_add_place(real_point3d const *point, real weight, char const *name) +{ + real_point3d ground; + struct bots_place *place; + + if (bots_vantage.place_count >= BOTS_PLACES_MAXIMUM) + return; + place = &bots_vantage.places[bots_vantage.place_count]; + place->point = *point; + if (bots_routes_ground(point, &ground) != NONE) + place->point = ground; + place->point.z += BOTS_PLACE_HEIGHT; + place->weight = weight; + place->name = name; + bots_vantage.place_count++; +} + +/* the places that matter in this game */ +static void bots_vantage_find_places(void) +{ + struct scenario *scenario = global_scenario_get(); + long game = bots_tactics_game(); + long index, lane, waypoint; + real_point3d point; + + bots_vantage.place_count = 0; + if (!scenario) + return; + for (index = 0; index < scenario->netgame_flags.count; index++) + { + struct scenario_netgame_flag *flag = TAG_BLOCK_GET_ELEMENT(&scenario->netgame_flags, index, struct scenario_netgame_flag); + + if (flag->type == _netgame_flag_ctf_flag && (flag->team_index == 0 || flag->team_index == 1)) + bots_vantage_add_place(&flag->position, game == game_engine_ctf ? 3.0f : 1.5f, flag->team_index ? "stand 1" : "stand 0"); + } + if (game == game_engine_king) + { + /* (a hill's markers share its team index: their middle) */ + for (index = 0; index < 8; index++) + { + real_point3d sum = { 0.0f, 0.0f, 0.0f }; + long marker, count = 0; + + for (marker = 0; marker < scenario->netgame_flags.count; marker++) + { + struct scenario_netgame_flag *flag = + TAG_BLOCK_GET_ELEMENT(&scenario->netgame_flags, marker, struct scenario_netgame_flag); + + if (flag->type == _netgame_flag_hill && flag->team_index == index) + { + sum.x += flag->position.x; + sum.y += flag->position.y; + sum.z += flag->position.z; + count++; + } + } + if (count) + { + sum.x /= (real)count; + sum.y /= (real)count; + sum.z /= (real)count; + bots_vantage_add_place(&sum, 3.0f, "hill"); + } + } + } + if (game == game_engine_oddball) + { + long count = 0; + + for (index = 0; index < scenario->netgame_flags.count && count < 4; index++) + { + struct scenario_netgame_flag *flag = + TAG_BLOCK_GET_ELEMENT(&scenario->netgame_flags, index, struct scenario_netgame_flag); + + if (flag->type == _netgame_flag_oddball_ball_spawn) + { + bots_vantage_add_place(&flag->position, 2.0f, "ball spawn"); + count++; + } + } + } + if (bots_routes_map.route_point_count == BOTS_ROUTE_POINTS) + { + for (index = 4; index <= 12; index += 4) + bots_vantage_add_place(&bots_routes_map.route_points[index], 2.0f, "route"); + } + for (lane = 0; lane < BOTS_SIDE_LANES; lane++) + { + for (waypoint = 0; bots_routes_lane_waypoint(lane, waypoint, &point); waypoint++) + bots_vantage_add_place(&point, 1.0f, "lane"); + } + /* the weapon and item spawns, where the players go (Sidewinder's field, + whose stands and direct route are in its bases and gullies), as many as + there is room for, each the furthest from those taken */ + { + long first = bots_vantage.place_count, count; + + for (count = 0; bots_vantage.place_count < BOTS_PLACES_MAXIMUM && count < 8; count++) + { + long best = NONE; + real best_distance = -1.0f; + + for (index = 0; index < scenario->netgame_equipment.count; index++) + { + struct scenario_netgame_equipment *equipment = + TAG_BLOCK_GET_ELEMENT(&scenario->netgame_equipment, index, struct scenario_netgame_equipment); + real nearest = REAL_MAX; + long place; + + for (place = 0; place < bots_vantage.place_count; place++) + { + real distance = bots_vantage_distance3d(&bots_vantage.places[place].point, &equipment->position); + + if (place >= first || distance < 2.0f) + nearest = MIN(nearest, distance); + } + if (nearest > best_distance && nearest > 6.0f) + { + best_distance = nearest; + best = index; + } + } + if (best == NONE) + break; + bots_vantage_add_place(&TAG_BLOCK_GET_ELEMENT(&scenario->netgame_equipment, best, + struct scenario_netgame_equipment)->position, 1.0f, "item"); + } + } +} + +static void bots_vantage_free(void) +{ + /* (the game's free, debug_memory.c's, takes no NULL) */ + if (bots_vantage.grid_area) + free(bots_vantage.grid_area); + if (bots_vantage.grid_height_sum) + free(bots_vantage.grid_height_sum); + bots_vantage.grid_area = NULL; + bots_vantage.grid_height_sum = NULL; +} + +/* ---------- making them */ + +void bots_vantage_dispose(void) +{ + long index; + + bots_vantage_free(); + bots_vantage.phase = _vantage_phase_idle; + bots_vantage.count = 0; + bots_vantage.candidate_count = 0; + bots_vantage.place_count = 0; + bots_vantage.rays = 0; + for (index = 0; index < BOTS_VANTAGE_MAXIMUM; index++) + bots_vantage.claims[index] = NONE; +} + +static void bots_vantage_begin(void) +{ + bots_vantage_dispose(); + bots_vantage.phase = _vantage_phase_bounds; + bots_vantage.cursor = 0; + bots_vantage.grid_x = bots_vantage.grid_y = REAL_MAX; + bots_vantage.grid_x1 = bots_vantage.grid_y1 = -REAL_MAX; + bots_vantage.grid_width = bots_vantage.grid_height = 0; + bots_vantage_find_places(); +} + +/* the height grid's cell of a point (NONE outside) */ +static long bots_vantage_cell(real x, real y) +{ + long cx = (long)((x - bots_vantage.grid_x) / bots_vantage.cell); + long cy = (long)((y - bots_vantage.grid_y) / bots_vantage.cell); + + if (cx < 0 || cy < 0 || cx >= bots_vantage.grid_width || cy >= bots_vantage.grid_height) + return NONE; + return cy * bots_vantage.grid_width + cx; +} + +/* how high a spot stands above the walkable surfaces about it (the area's +mean height in the 3 by 3 cells about it) */ +static real bots_vantage_height(real_point3d const *point) +{ + long cx = (long)((point->x - bots_vantage.grid_x) / bots_vantage.cell); + long cy = (long)((point->y - bots_vantage.grid_y) / bots_vantage.cell); + real area = 0.0f, sum = 0.0f; + long x, y; + + for (y = cy - 1; y <= cy + 1; y++) + { + for (x = cx - 1; x <= cx + 1; x++) + { + if (x < 0 || y < 0 || x >= bots_vantage.grid_width || y >= bots_vantage.grid_height) + continue; + area += bots_vantage.grid_area[y * bots_vantage.grid_width + x]; + sum += bots_vantage.grid_height_sum[y * bots_vantage.grid_width + x]; + } + } + return area > 0.0f ? point->z - sum / area : 0.0f; +} + +/* a spot kept among the candidates by its first score (a better one within +their spacing taking its place) */ +static void bots_vantage_consider(struct bots_vantage_spot const *spot) +{ + long index, worst = NONE; + + for (index = 0; index < bots_vantage.candidate_count; index++) + { + struct bots_vantage_spot *other = &bots_vantage.candidates[index]; + + if (bots_vantage_distance3d(&other->point, &spot->point) < BOTS_VANTAGE_CANDIDATE_SPACING) + { + if (other->first_score < spot->first_score) + *other = *spot; + return; + } + } + if (bots_vantage.candidate_count < BOTS_VANTAGE_CANDIDATES) + { + bots_vantage.candidates[bots_vantage.candidate_count++] = *spot; + return; + } + for (index = 0; index < bots_vantage.candidate_count; index++) + { + if (worst == NONE || bots_vantage.candidates[index].first_score < bots_vantage.candidates[worst].first_score) + worst = index; + } + if (bots_vantage.candidates[worst].first_score < spot->first_score) + bots_vantage.candidates[worst] = *spot; +} + +/* the vantage points chosen from the spots */ +static void bots_vantage_choose_points(void) +{ + long index, other; + + for (index = 0; index < bots_vantage.candidate_count; index++) + { + struct bots_vantage_spot *spot = &bots_vantage.candidates[index]; + long place; + + spot->score = 0.8f * PIN(spot->height, 0.0f, 6.0f) + 2.5f * (real)spot->open / (real)BOTS_VANTAGE_OPEN_RAYS; + spot->sees_count = 0; + for (place = 0; place < bots_vantage.place_count; place++) + { + if (TEST_FLAG(spot->sees, place)) + { + spot->score += bots_vantage.places[place].weight * + bots_vantage_range(bots_vantage_distance3d(&spot->point, &bots_vantage.places[place].point)); + spot->sees_count++; + } + } + } + /* (debug: HALO_BOT_TRACE, every spot scored) */ + for (index = 0; bots_trace_enabled() && index < bots_vantage.candidate_count; index++) + { + struct bots_vantage_spot const *spot = &bots_vantage.candidates[index]; + + platform_log("bots: trace vantage spot (%.1f %.1f %.1f) height %.1f open %d sees %d (%lx) first %.1f score %.1f", + spot->point.x, spot->point.y, spot->point.z, spot->height, (int)spot->open, (int)spot->sees_count, spot->sees, + spot->first_score, spot->score); + } + for (index = 0; bots_trace_enabled() && index < bots_vantage.place_count; index++) + platform_log("bots: trace vantage place %ld %s (%.1f %.1f %.1f) weight %.1f", index, bots_vantage.places[index].name, + bots_vantage.places[index].point.x, bots_vantage.places[index].point.y, bots_vantage.places[index].point.z, + bots_vantage.places[index].weight); + bots_vantage.count = 0; + while (bots_vantage.count < BOTS_VANTAGE_MAXIMUM) + { + long best = NONE; + + for (index = 0; index < bots_vantage.candidate_count; index++) + { + struct bots_vantage_spot const *spot = &bots_vantage.candidates[index]; + boolean near = FALSE; + + if (spot->sees_count < 2 || (best != NONE && spot->score <= bots_vantage.candidates[best].score)) + continue; + for (other = 0; other < bots_vantage.count && !near; other++) + near = bots_vantage_distance3d(&bots_vantage.points[other].point, &spot->point) < BOTS_VANTAGE_SPACING; + if (!near) + best = index; + } + if (best == NONE) + break; + bots_vantage.points[bots_vantage.count] = bots_vantage.candidates[best]; + bots_vantage.claims[bots_vantage.count] = NONE; + bots_vantage.count++; + } + for (index = 0; index < bots_vantage.count; index++) + { + struct bots_vantage_spot const *spot = &bots_vantage.points[index]; + char seen[200]; + int length = 0; + long place; + + seen[0] = 0; + for (place = 0; place < bots_vantage.place_count && length < (int)sizeof(seen) - 24; place++) + { + if (TEST_FLAG(spot->sees, place)) + length += snprintf(seen + length, sizeof(seen) - (size_t)length, "%s%s %.0f", length ? ", " : "", + bots_vantage.places[place].name, bots_vantage_distance3d(&spot->point, &bots_vantage.places[place].point)); + } + platform_log("bots: vantage point %ld at (%.1f %.1f %.1f): %.1f above its surroundings, open %d/%d, sees %d of %ld places " + "(%s); score %.1f", index + 1, spot->point.x, spot->point.y, spot->point.z, spot->height, (int)spot->open, + BOTS_VANTAGE_OPEN_RAYS, (int)spot->sees_count, bots_vantage.place_count, seen, spot->score); + } + platform_log("bots: vantage: %ld points of %ld spots scored (%ld places, %ld rays)", bots_vantage.count, + bots_vantage.candidate_count, bots_vantage.place_count, bots_vantage.rays); +} + +/* a step of the map's vantage points; TRUE once made (or none) */ +boolean bots_vantage_step(void) +{ + switch (bots_vantage.phase) + { + case _vantage_phase_idle: + bots_vantage_begin(); + break; + case _vantage_phase_bounds: + { + long last; + + if (!bots_routes_graph_made() || bots_vantage.place_count < 2) + { + platform_log("bots: vantage: none (%s)", bots_routes_graph_made() ? "fewer than two places" : "no walkable graph"); + bots_vantage.phase = _vantage_phase_done; + break; + } + last = MIN(bots_vantage.cursor + BOTS_VANTAGE_NODES_A_TICK * 4, bots_graph.node_count); + for (; bots_vantage.cursor < last; bots_vantage.cursor++) + { + struct bots_graph_node const *node = &bots_graph.nodes[bots_vantage.cursor]; + + bots_vantage.grid_x = MIN(bots_vantage.grid_x, node->middle.x); + bots_vantage.grid_y = MIN(bots_vantage.grid_y, node->middle.y); + bots_vantage.grid_x1 = MAX(bots_vantage.grid_x1, node->middle.x); + bots_vantage.grid_y1 = MAX(bots_vantage.grid_y1, node->middle.y); + } + if (bots_vantage.cursor >= bots_graph.node_count) + { + real width = bots_vantage.grid_x1 - bots_vantage.grid_x; + real height = bots_vantage.grid_y1 - bots_vantage.grid_y; + long cells; + + bots_vantage.cell = MAX(BOTS_VANTAGE_CELL, MAX(width, height) / (real)BOTS_VANTAGE_GRID_MAXIMUM); + bots_vantage.grid_width = (long)(width / bots_vantage.cell) + 1; + bots_vantage.grid_height = (long)(height / bots_vantage.cell) + 1; + cells = bots_vantage.grid_width * bots_vantage.grid_height; + bots_vantage.grid_area = (real *)malloc((size_t)cells * sizeof(real)); + bots_vantage.grid_height_sum = (real *)malloc((size_t)cells * sizeof(real)); + if (bots_vantage.grid_area) + csmemset(bots_vantage.grid_area, 0, (size_t)cells * sizeof(real)); + if (bots_vantage.grid_height_sum) + csmemset(bots_vantage.grid_height_sum, 0, (size_t)cells * sizeof(real)); + if (!bots_vantage.grid_area || !bots_vantage.grid_height_sum) + { + bots_vantage_free(); + platform_log("bots: vantage: none (no memory for the height grid)"); + bots_vantage.phase = _vantage_phase_done; + break; + } + bots_vantage.cursor = 0; + bots_vantage.phase = _vantage_phase_grid; + } + break; + } + case _vantage_phase_grid: + { + long last = MIN(bots_vantage.cursor + BOTS_VANTAGE_NODES_A_TICK * 4, bots_graph.node_count); + + for (; bots_vantage.cursor < last; bots_vantage.cursor++) + { + struct bots_graph_node const *node = &bots_graph.nodes[bots_vantage.cursor]; + long cell = bots_vantage_cell(node->middle.x, node->middle.y); + + if (cell == NONE || node->cost >= REAL_MAX) + continue; + bots_vantage.grid_area[cell] += node->area; + bots_vantage.grid_height_sum[cell] += node->area * node->middle.z; + } + if (bots_vantage.cursor >= bots_graph.node_count) + { + bots_vantage.cursor = 0; + bots_vantage.candidate_count = 0; + bots_vantage.phase = _vantage_phase_candidates; + } + break; + } + case _vantage_phase_candidates: + { + long last = MIN(bots_vantage.cursor + BOTS_VANTAGE_NODES_A_TICK, bots_graph.node_count); + + for (; bots_vantage.cursor < last; bots_vantage.cursor++) + { + struct bots_graph_node const *node = &bots_graph.nodes[bots_vantage.cursor]; + struct bots_vantage_spot spot; + long place; + + /* (reached from the bases, flat, room to stand) */ + if (node->cost >= REAL_MAX || node->normal_k < 0.8f || node->area < 0.25f) + continue; + csmemset(&spot, 0, sizeof(spot)); + spot.point = node->middle; + spot.surface_index = node->surface_index; + spot.height = bots_vantage_height(&node->middle); + spot.first_score = PIN(spot.height, -2.0f, 8.0f); + for (place = 0; place < bots_vantage.place_count; place++) + { + spot.first_score += 0.25f * bots_vantage.places[place].weight * + bots_vantage_range(bots_vantage_distance3d(&node->middle, &bots_vantage.places[place].point)); + } + bots_vantage_consider(&spot); + } + if (bots_vantage.cursor >= bots_graph.node_count) + { + bots_vantage_free(); + bots_vantage.cursor = 0; + bots_vantage.phase = _vantage_phase_rays; + } + break; + } + case _vantage_phase_rays: + { + long rays_a_spot = bots_vantage.place_count + BOTS_VANTAGE_OPEN_RAYS; + long total = rays_a_spot * bots_vantage.candidate_count; + long rays; + + for (rays = 0; rays < BOTS_VANTAGE_RAYS_A_TICK && bots_vantage.cursor < total; bots_vantage.cursor++) + { + struct bots_vantage_spot *spot = &bots_vantage.candidates[bots_vantage.cursor / rays_a_spot]; + long ray = bots_vantage.cursor % rays_a_spot; + real_point3d eye = spot->point, to; + + eye.z += BOTS_VANTAGE_EYE_HEIGHT; + if (ray < bots_vantage.place_count) + { + to = bots_vantage.places[ray].point; + if (bots_vantage_distance3d(&eye, &to) > BOTS_VANTAGE_SIGHT || bots_vantage_distance3d(&eye, &to) < 1.0f) + continue; + rays++; + if (bots_vantage_clear(&eye, &to)) + SET_FLAG(spot->sees, ray, TRUE); + } + else + { + real angle = (real)(ray - bots_vantage.place_count) * 2.0f * 3.14159265f / (real)BOTS_VANTAGE_OPEN_RAYS; + + to = eye; + to.x += (real)cos(angle) * BOTS_VANTAGE_OPEN_LENGTH; + to.y += (real)sin(angle) * BOTS_VANTAGE_OPEN_LENGTH; + rays++; + if (bots_vantage_clear(&eye, &to)) + spot->open++; + } + } + if (bots_vantage.cursor >= total) + { + bots_vantage_choose_points(); + bots_vantage.phase = _vantage_phase_done; + } + break; + } + case _vantage_phase_done: + return TRUE; + } + return FALSE; +} + +/* ---------- the bots at them */ + +short bots_vantage_choose(long bot_index, real_point3d const *position, real_point3d const *objective, + real maximum_distance) +{ + struct bots_tactics_bot *state = &bots_tactics_bots[bot_index]; + long index, best = NONE, objective_place = NONE; + real best_score = -REAL_MAX; + long now = game_time_get(); + + /* (over the hill: the place nearest it, which the point must see) */ + if (objective) + { + real nearest = 15.0f; + + for (index = 0; index < bots_vantage.place_count; index++) + { + real distance = bots_vantage_distance3d(&bots_vantage.places[index].point, objective); + + if (distance < nearest) + { + nearest = distance; + objective_place = index; + } + } + if (objective_place == NONE) + return NONE; + } + for (index = 0; index < bots_vantage.count; index++) + { + struct bots_vantage_spot const *spot = &bots_vantage.points[index]; + real score; + + if ((bots_vantage.claims[index] != NONE && bots_vantage.claims[index] != bot_index) || + (TEST_FLAG(state->failed_vantages, index) && now < state->failed_until_tick) || + (index == state->last_vantage && bots_vantage.count > 1) || + (objective_place != NONE && (!TEST_FLAG(spot->sees, objective_place) || + bots_vantage_distance3d(&spot->point, &bots_vantage.places[objective_place].point) > 40.0f)) || + bots_vantage_distance3d(&spot->point, position) > maximum_distance) + { + continue; + } + score = spot->score - bots_vantage_distance3d(&spot->point, position) / 10.0f + + (real)(bots_tactics_random(state) & 0xFF) / 128.0f; + if (score > best_score) + { + best_score = score; + best = index; + } + } + if (best != NONE) + bots_vantage.claims[best] = bot_index; + return (short)best; +} + +void bots_vantage_release(long bot_index) +{ + struct bots_tactics_bot *state = &bots_tactics_bots[bot_index]; + + if (state->vantage >= 0 && state->vantage < BOTS_VANTAGE_MAXIMUM && bots_vantage.claims[state->vantage] == bot_index) + bots_vantage.claims[state->vantage] = NONE; + if (state->vantage != NONE) + state->last_vantage = state->vantage; + state->vantage = NONE; + state->vantage_weapon = _bots_precision_none; + state->hold_tick = 0; +} + +void bots_vantage_point(short vantage, real_point3d *point, long *surface_index) +{ + *point = bots_vantage.points[vantage].point; + *surface_index = bots_vantage.points[vantage].surface_index; +} + +boolean bots_vantage_stand(long team, real_point3d *point) +{ + long index; + + for (index = 0; index < bots_vantage.place_count; index++) + { + if (!strcmp(bots_vantage.places[index].name, team ? "stand 1" : "stand 0")) + { + *point = bots_vantage.places[index].point; + return team == 0 || team == 1; + } + } + return FALSE; +} + +unsigned long bots_vantage_sees(short vantage) +{ + return vantage >= 0 && vantage < bots_vantage.count ? bots_vantage.points[vantage].sees : 0; +} + +long bots_vantage_count(void) +{ + return bots_vantage.count; +} + +long bots_places_count(void) +{ + return bots_vantage.place_count; +} + +struct bots_place const *bots_place_get(long index) +{ + return &bots_vantage.places[index]; +} diff --git a/port/linux/game/bots_vehicles.c b/port/linux/game/bots_vehicles.c new file mode 100644 index 0000000000..4b92fae464 --- /dev/null +++ b/port/linux/game/bots_vehicles.c @@ -0,0 +1,693 @@ +/* Focused adaptation of BirchWoodGod/halo-ce-vita's ground-vehicle bots, +via thelinkin3000/halo-ce-universal 18a94774a73ca275e9c0ab4f281e492ad8bb656e. +The inherited vehicle definitions and seat checks are GPL-3.0-only. +See docs/reading/bots_and_android_features.md for provenance. + +The standalone enhanced controller owns paths and combat. This module chooses an accessible seat, +uses the action button to enter/leave, and translates a path direction into +driving controls. No new attachment, vehicle or network rules are needed. */ +#include "cseries.h" +#include "game/game.h" +#include "game/players.h" +#include "game/game_engine.h" +#include "objects/objects.h" +#include "units/units.h" +#include "units/unit_definitions.h" +#include "units/vehicle_definitions.h" +#include "tag_files/tag_groups.h" +#include "bots.h" +#include "bots_tactics.h" +#include "bots_vehicles.h" +#include "infection.h" +#include "enhanced_bots_flight.h" +#include "mcc_seats.h" +#include "items/weapons.h" +#include "items/weapon_definitions.h" +#include +#include + +int config_boolean(char const *name); + +/* The public vehicle tag layout used by the fork; no SDK declarations. */ +struct bots_vehicle_definition +{ + byte unit[0x2F4]; + short type; + short pad; + byte unknown[0x94]; + real radius; +}; +typedef char bots_vehicle_radius_offset[offsetof(struct bots_vehicle_definition, radius) == 0x38C ? 1 : -1]; + +static struct bots_vehicle_state +{ + long sought, ridden, avoided; + short seat; + long next_scan, next_companion_scan, deadline, next_press, stuck_tick, reverse_until, stuck_count; + long unit_index, spawn_tick, sought_tick, ride_tick, avoided_until; + long boarding_until, driverless_tick, off_arc_tick, last_enemy_tick, charge_tick; + long target_unit; + long last_progress; + real best_distance; + boolean flipping; + real_point3d entrance, last_position; +} vehicles[BOTS_MAXIMUM]; + +static real distance(real_point3d const *a, real_point3d const *b) +{ + real x = a->x - b->x, y = a->y - b->y, z = a->z - b->z; + return (real)sqrt(x*x + y*y + z*z); +} + +static real angle(real value) +{ + value = (real)fmod(value, 6.28318531f); + if (value > 3.14159265f) value -= 6.28318531f; + if (value < -3.14159265f) value += 6.28318531f; + return value; +} + +static struct bots_vehicle_definition *definition(long index) +{ + static struct bots_vehicle_definition seated_biped; + if (mcc_seat_parent(index)) + { + seated_biped.type = -1; + return &seated_biped; + } + return (struct bots_vehicle_definition *)tag_get(VEHICLE_DEFINITION_TAG, object_get(index)->definition_index); +} + +static long vehicle_driver(long index) +{ + long controller = mcc_seat_controller(index); + return controller != NONE ? controller : unit_get(index)->unit.driver_object_index; +} + +static boolean drivable(long index) +{ + short type = definition(index)->type; + /* Authored ground and flying physics supported by the engine. */ + return type == 0 || type == 1 || type == 3 || type == 4 || type == 5; +} + +void bots_vehicles_reset_player(long index) +{ + csmemset(&vehicles[index], 0, sizeof(vehicles[index])); + vehicles[index].sought = vehicles[index].ridden = vehicles[index].avoided = NONE; + vehicles[index].seat = NONE; + vehicles[index].unit_index = NONE; + vehicles[index].target_unit = NONE; + enhanced_flight_reset(index); +} + +void bots_vehicles_reset(void) +{ + long index; + for (index = 0; index < BOTS_MAXIMUM; index++) + bots_vehicles_reset_player(index); +} + +long bots_vehicle_parent(long unit_index) +{ + struct object_datum *object = object_try_and_get(unit_index); + long parent = object ? object->object.parent_object_index : NONE; + return parent != NONE && (object_try_and_get_and_verify_type(parent, _object_mask_vehicle) || mcc_seat_parent(parent)) ? parent : NONE; +} + +long bots_vehicle_navigation(long unit_index, real *radius) +{ + long parent = bots_vehicle_parent(unit_index); + if (parent != NONE && vehicle_driver(parent) == unit_index && drivable(parent)) + { + real width = definition(parent)->radius; + *radius = width > 0.1f && width < 64.0f ? width : MAX(1.0f, MIN(object_get(parent)->object.bounding_sphere_radius, 64.0f)); + return parent; + } + return unit_index; +} + +boolean bots_vehicle_flying(long unit_index) +{ + long parent = bots_vehicle_parent(unit_index); + return parent != NONE && (definition(parent)->type == 3 || definition(parent)->type == 5); +} + +boolean bots_vehicle_seeking(long index) +{ + return config_boolean("bots.vehicles") && vehicles[index].sought != NONE; +} + +long bots_vehicle_sought(long index) +{ + return vehicles[index].sought; +} + +void bots_vehicle_cancel(long index) +{ + struct bots_vehicle_state *state = &vehicles[index]; + if (state->sought != NONE) + { + state->avoided = state->sought; + state->avoided_until = game_time_get() + 10 * TICKS_PER_SECOND; + } + state->sought = NONE; + state->flipping = FALSE; + state->next_scan = game_time_get() + TICKS_PER_SECOND; +} + +long bots_vehicle_weapon(long unit_index, long weapon_index) +{ + long parent = bots_vehicle_parent(unit_index); + struct unit_datum *vehicle; + short slot; + if (parent == NONE) return weapon_index; + vehicle = unit_get(parent); + slot = vehicle->unit.current_weapon_index; + if ((vehicle->unit.gunner_object_index == unit_index || + (vehicle->unit.driver_object_index == unit_index && definition(parent)->type == 6)) && + slot >= 0 && slot < MAXIMUM_WEAPONS_PER_UNIT) + return vehicle->unit.weapon_object_indices[slot]; + return weapon_index; +} + +static short turret_seat(long vehicle_index); + +static boolean seat_takeover(long other, long unit_index, long vehicle_index) +{ + struct object_datum *claimed = object_try_and_get(vehicles[other].unit_index); + struct player_datum *player, *owner; + if (!claimed || !game_engine_has_teams()) return FALSE; + player = player_try_and_get(unit_get(unit_index)->unit.player_index); + owner = player_try_and_get(unit_get(vehicles[other].unit_index)->unit.player_index); + return player && owner && player->team_index == owner->team_index && + distance(&claimed->object.position, &object_get(vehicle_index)->object.position) > + distance(&object_get(unit_index)->object.position, &object_get(vehicle_index)->object.position) + 15.0f; +} + +static boolean seat_available(long index, long unit_index, long vehicle_index, short seat_index) +{ + struct unit_datum *vehicle = unit_get(vehicle_index); + struct unit_definition *tag = unit_definition_get(vehicle->definition_index); + struct unit_seat *seat; + long other; + if (seat_index < 0 || seat_index >= tag->unit.seats.count || + vehicle->object.up.k < 0.5f || TEST_FLAG(vehicle->object.damage_flags, _object_dead_bit) || + TEST_FLAG(vehicle->unit.flags, _unit_not_enterable_by_player_bit)) return FALSE; + seat = TAG_BLOCK_GET_ELEMENT(&tag->unit.seats, seat_index, struct unit_seat); + if (TEST_FLAG(seat->flags, _unit_seat_driver_bit) && !drivable(vehicle_index) && + turret_seat(vehicle_index) != seat_index) return FALSE; + if (!TEST_FLAG(seat->flags, _unit_seat_driver_bit) && !TEST_FLAG(seat->flags, _unit_seat_gunner_bit) && + vehicle_driver(vehicle_index) == NONE) return FALSE; + /* A seat marked as requiring a driver follows the engine's player check. */ + if (TEST_FLAG(seat->flags, 9) && vehicle_driver(vehicle_index) == NONE) return FALSE; + for (other = 0; other < BOTS_MAXIMUM; other++) + if (other != index && vehicles[other].sought == vehicle_index && vehicles[other].seat == seat_index && + !seat_takeover(other, unit_index, vehicle_index)) + return FALSE; + return unit_has_animation_to_enter_seat(unit_index, vehicle_index, seat_index) && + unit_can_enter_seat(unit_index, vehicle_index, seat_index, NULL); +} + +static boolean friendly_driver(long unit_index, long vehicle_index) +{ + long driver = vehicle_driver(vehicle_index); + struct player_datum *player, *other; + if (driver == NONE || !game_engine_has_teams()) return FALSE; + player = player_try_and_get(unit_get(unit_index)->unit.player_index); + other = player_try_and_get(unit_get(driver)->unit.player_index); + return player && other && player->team_index == other->team_index; +} + +static boolean human_driver(long vehicle_index) +{ + long driver = vehicle_driver(vehicle_index); + struct player_datum *player = driver != NONE ? player_try_and_get(unit_get(driver)->unit.player_index) : NULL; + return player && !bots_player_owned(player->network_player_data.machine_index); +} + +static boolean vehicle_free(long vehicle_index) +{ + long child = object_get(vehicle_index)->object.first_child_object_index; + while (child != NONE) + { + struct object_datum *object = object_try_and_get(child); + if (!object || TEST_FLAG(_object_mask_unit, object->object.type)) return FALSE; + child = object->object.next_object_index; + } + return TRUE; +} + +static short turret_seat(long vehicle_index) +{ + struct unit_definition *tag = unit_definition_get(object_get(vehicle_index)->definition_index); + short seat, gunner = NONE, driver = NONE; + for (seat = 0; seat < tag->unit.seats.count; seat++) + { + struct unit_seat *entry = TAG_BLOCK_GET_ELEMENT(&tag->unit.seats, seat, struct unit_seat); + if (TEST_FLAG(entry->flags, _unit_seat_driver_bit) && driver == NONE) driver = seat; + if (TEST_FLAG(entry->flags, _unit_seat_gunner_bit) && gunner == NONE) gunner = seat; + } + if (definition(vehicle_index)->type == 6) return gunner != NONE ? gunner : driver; + return driver == NONE && definition(vehicle_index)->type != -1 ? gunner : NONE; +} + +/* Tank, jeep, scout: reach, share of the journey, nearby exception, +allowable detour, and preference. The fork credits BirchWoodGod's drivers. */ +static struct { real reach, share, close, slack, bonus; } const vehicle_worth[3] = +{ + { 50.0f, 1.0f, 20.0f, 20.0f, 12.0f }, + { 30.0f, 0.6f, 0.0f, 5.0f, 0.0f }, + { 40.0f, 0.8f, 10.0f, 10.0f, 5.0f }, +}; + +static boolean bots_vehicle_choose_goal(long index, long unit_index, real_point3d const *destination, + real_point3d *goal, long *surface, boolean companion) +{ + struct bots_vehicle_state *state = &vehicles[index]; + struct object_datum *unit = object_get(unit_index); + long now = game_time_get(); + if (!config_boolean("bots.vehicles") || bots_vehicle_parent(unit_index) != NONE) + { + state->sought = NONE; + return FALSE; + } + if (infection_enabled() && infection_unit_is_zombie(unit_index)) return FALSE; + if (state->unit_index != unit_index) state->spawn_tick = now; + state->unit_index = unit_index; + if (state->sought != NONE && state->flipping && + (object_try_and_get_and_verify_type(state->sought, _object_mask_vehicle) || mcc_seat_parent(state->sought)) && object_get(state->sought)->object.up.k >= 0.5f) + { + state->sought = NONE; + state->flipping = FALSE; + state->next_scan = now; + } + if (state->sought != NONE && (!(object_try_and_get_and_verify_type(state->sought, _object_mask_vehicle) || mcc_seat_parent(state->sought)) || + now >= state->deadline || (state->flipping ? !vehicle_free(state->sought) : + !seat_available(index, unit_index, state->sought, state->seat)))) + { + state->avoided = state->sought; + state->avoided_until = now + TICKS_PER_SECOND * 30; + state->sought = NONE; + state->next_scan = now + TICKS_PER_SECOND * 10; + } + if (state->sought == NONE && now >= (companion ? state->next_companion_scan : state->next_scan)) + { + struct object_iterator iterator; + struct object_datum *vehicle; + real best = REAL_MAX; + real journey = distance(&unit->object.position, destination); + if (companion) state->next_companion_scan = now + TICKS_PER_SECOND; + else state->next_scan = now + TICKS_PER_SECOND * 2; + object_iterator_new(&iterator, _object_mask_unit, 0); + while ((vehicle = object_iterator_next(&iterator)) != NULL) + { + struct unit_definition *tag; + short seat; + real reach = distance(&unit->object.position, &vehicle->object.position); + short turret, type, kind; + real close; + boolean friendly; + if (iterator.index == unit_index || (!object_try_and_get_and_verify_type(iterator.index, _object_mask_vehicle) && + !mcc_seat_parent(iterator.index))) continue; + turret = turret_seat(iterator.index); + type = definition(iterator.index)->type; + friendly = friendly_driver(unit_index, iterator.index); + if (companion && (!friendly || !human_driver(iterator.index))) continue; + kind = type == 0 ? 0 : type == 4 ? 2 : 1; + close = vehicle_worth[kind].close; + if ((iterator.index == state->avoided && now < state->avoided_until) || + TEST_FLAG(vehicle->object.damage_flags, _object_dead_bit) || + TEST_FLAG(unit_get(iterator.index)->unit.flags, _unit_not_enterable_by_player_bit)) + continue; + if (now - state->spawn_tick < 10 * TICKS_PER_SECOND) close = MAX(close + 10.0f, 15.0f); + if (turret != NONE) + { + struct object_datum *target = object_try_and_get(state->target_unit); + if (!target || reach > 12.0f || now - state->last_enemy_tick > 5 * TICKS_PER_SECOND || + distance(&target->object.position, &vehicle->object.position) > 60.0f) continue; + } + else if (!friendly && (!drivable(iterator.index) || journey < 35.0f || reach > MIN(vehicle_worth[kind].reach, + MAX(close, journey * vehicle_worth[kind].share)) || (reach > close && + distance(&vehicle->object.position, destination) > journey + vehicle_worth[kind].slack))) continue; + /* A large custom hull can have an entrance far from its origin. */ + if (friendly && reach > 25.0f + MAX(0.0f, vehicle->object.bounding_sphere_radius)) continue; + if (vehicle->object.up.k < 0.5f) + { + long other; + if (turret != NONE || reach > 15.0f || reach + 10.0f >= best || !vehicle_free(iterator.index)) continue; + for (other = 0; other < BOTS_MAXIMUM; other++) + if (other != index && vehicles[other].sought == iterator.index && vehicles[other].flipping) break; + if (other < BOTS_MAXIMUM) continue; + best = reach + 10.0f; + state->sought = iterator.index; + state->seat = NONE; + state->flipping = TRUE; + state->entrance = vehicle->object.position; + continue; + } + tag = unit_definition_get(vehicle->definition_index); + for (seat = 0; seat < tag->unit.seats.count; seat++) + { + real_point3d entrance, seat_point; + struct unit_seat *entry = TAG_BLOCK_GET_ELEMENT(&tag->unit.seats, seat, struct unit_seat); + boolean driver = TEST_FLAG(entry->flags, _unit_seat_driver_bit); + real score = reach - (driver ? vehicle_worth[kind].bonus : + TEST_FLAG(entry->flags, _unit_seat_gunner_bit) ? 3.5f : -3.0f); + if (score >= best || (turret != NONE && seat != turret)) continue; + if (turret == NONE && !driver && !friendly) continue; + /* A human may creep forward while teammates approach. Do not + chase a vehicle travelling faster than a running biped. */ + if (turret == NONE && magnitude3d(&vehicle->object.translational_velocity) > 0.08f) continue; + if (seat_available(index, unit_index, iterator.index, seat) && + unit_get_seat_entrance_point(unit_index, iterator.index, seat, &entrance, &seat_point, NULL)) + { + if (friendly && distance(&unit->object.position, &entrance) > 25.0f) continue; + best = score; + state->sought = iterator.index; + state->seat = seat; + state->entrance = entrance; + state->flipping = FALSE; + } + } + } + if (state->sought != NONE) + { + long other; + for (other = 0; other < BOTS_MAXIMUM; other++) + if (other != index && vehicles[other].sought == state->sought && vehicles[other].seat == state->seat && + seat_takeover(other, unit_index, state->sought)) + { + vehicles[other].sought = NONE; + vehicles[other].next_scan = now + 3 * TICKS_PER_SECOND; + } + state->sought_tick = now; + state->last_progress = now; + state->best_distance = distance(&unit->object.position, &state->entrance); + state->deadline = now + (long)(MAX(25.0f, distance(&unit->object.position, &state->entrance) / 1.6f + 8.0f) * TICKS_PER_SECOND); + } + } + if (state->sought == NONE) return FALSE; + if (!state->flipping) + { + real_point3d seat_point; + if (!unit_get_seat_entrance_point(unit_index, state->sought, state->seat, &state->entrance, &seat_point, NULL)) return FALSE; + } + { + real remaining = distance(&unit->object.position, &state->entrance); + if (remaining < state->best_distance - 0.5f) + { + state->best_distance = remaining; + state->last_progress = now; + } + if (now - state->last_progress > 8 * TICKS_PER_SECOND) + { + bots_vehicle_cancel(index); + return FALSE; + } + } + *surface = bots_routes_ground(&state->entrance, goal); + return *surface != NONE; +} + +boolean bots_vehicle_goal(long index, long unit_index, real_point3d const *destination, + real_point3d *goal, long *surface) +{ + return bots_vehicle_choose_goal(index, unit_index, destination, goal, surface, FALSE); +} + +/* Nearby human transports take precedence over an optional weapon detour. +Carriers and bots already holding a hill keep their objective responsibilities. */ +boolean bots_vehicle_player_goal(long index, long unit_index, real_point3d const *destination, + real_point3d *goal, long *surface) +{ + return bots_vehicle_choose_goal(index, unit_index, destination, goal, surface, TRUE); +} + +static boolean boarding(long index, long vehicle_index) +{ + struct bots_vehicle_state *driver = &vehicles[index]; + long other, now = game_time_get(); + boolean waiting = FALSE; + for (other = 0; other < BOTS_MAXIMUM; other++) + { + struct bots_vehicle_state *rider = &vehicles[other]; + struct object_datum *unit = object_try_and_get(rider->unit_index); + if (other != index && unit && rider->sought == vehicle_index && !rider->flipping && + now - rider->sought_tick < 12 * TICKS_PER_SECOND && friendly_driver(rider->unit_index, vehicle_index) && + distance(&unit->object.position, &object_get(vehicle_index)->object.position) < 25.0f) + waiting = TRUE; + } + if (!waiting) { driver->boarding_until = 0; return FALSE; } + if (!driver->boarding_until) driver->boarding_until = now + 12 * TICKS_PER_SECOND; + return now < driver->boarding_until; +} + +static boolean turret_action(struct bots_vehicle_state *state, long vehicle_index, long target_index, + struct player_action *action) +{ + long now = game_time_get(); + struct unit_datum *vehicle = unit_get(vehicle_index); + struct object_datum *target = object_try_and_get(target_index); + if (target) + { + real_vector3d toward; + real length, aim; + long weapon = bots_vehicle_weapon(state->unit_index, NONE); + vector_from_points3d(&vehicle->object.bounding_sphere_center, &target->object.bounding_sphere_center, &toward); + length = magnitude3d(&toward); + aim = length > 0.01f ? dot_product3d(&toward, &vehicle->unit.aiming_vector) / length : 1.0f; + if (aim < 0.90630779f) + { + if (!state->off_arc_tick) state->off_arc_tick = now; + if (now - state->off_arc_tick > 2 * TICKS_PER_SECOND) return TRUE; + } + else state->off_arc_tick = 0; + if (weapon != NONE) + { + struct weapon_definition *tag = weapon_definition_get(weapon_get(weapon)->definition_index); + real charge = tag->weapon.triggers.count > 0 ? + TAG_BLOCK_GET_ELEMENT(&tag->weapon.triggers, 0, struct weapon_trigger_definition)->charging_time : 0.0f; + if (charge > 0.0f) + { + long ticks = (long)(MIN(charge, 5.0f) * TICKS_PER_SECOND + 0.5f); + if (!state->charge_tick && action->primary_trigger > 0.0f) state->charge_tick = now; + if (state->charge_tick) + { + action->primary_trigger = now - state->charge_tick <= ticks + 3 ? 1.0f : 0.0f; + if (!action->primary_trigger) state->charge_tick = 0; + SET_FLAG(action->control_flags, _unit_control_weapon_primary_trigger_bit, action->primary_trigger > 0.0f); + } + } + } + } + else { state->off_arc_tick = 0; state->charge_tick = 0; } + return now - MAX(state->ride_tick, state->last_enemy_tick) > 6 * TICKS_PER_SECOND; +} + +void bots_vehicle_action(long index, long unit_index, real_point3d const *goal, + boolean objective, boolean moving, real direction, long target_unit, boolean hurt, struct player_action *action) +{ + struct bots_vehicle_state *state = &vehicles[index]; + long parent = bots_vehicle_parent(unit_index), now = game_time_get(); + struct unit_datum *vehicle; + boolean leave = FALSE, human_transport; + if (state->unit_index != unit_index) state->spawn_tick = now; + state->unit_index = unit_index; + if (target_unit != NONE) { state->target_unit = target_unit; state->last_enemy_tick = now; } + if (parent == NONE) + { + if (state->ridden != NONE) + { + platform_log("bots: bot %ld left vehicle %ld", index + 1, state->ridden); + state->avoided = state->ridden; + state->avoided_until = now + (enhanced_flight_failed(index) ? 120 : 30) * TICKS_PER_SECOND; + enhanced_flight_reset(index); + state->ridden = state->sought = NONE; + state->next_scan = now + TICKS_PER_SECOND * 15; + } + if (config_boolean("bots.vehicles") && state->sought != NONE && now >= state->next_press && + (object_try_and_get_and_verify_type(state->sought, _object_mask_vehicle) || mcc_seat_parent(state->sought))) + { + short nearest; + if (state->flipping) + { + struct object_datum *target = object_get(state->sought); + real_point3d const *position = &object_get(unit_index)->object.position; + if (distance(position, &target->object.position) < MAX(1.0f, target->object.bounding_sphere_radius * 0.8f)) + { + action->throttle.i = action->throttle.j = 0.0f; + action->desired_facing.yaw = (real)atan2(target->object.position.y - position->y, target->object.position.x - position->x); + if (vehicle_free(state->sought)) action->control_flags |= FLAG(_unit_control_action_bit); + state->next_press = now + TICKS_PER_SECOND / 2; + } + return; + } + /* Press Use only for the chosen seat; the normal player code + checks reach, motion, hostility and occupancy again. */ + if (unit_find_nearby_seat(unit_index, state->sought, &nearest) == _unit_nearby_seat_available && nearest == state->seat) + { + action->throttle.i = action->throttle.j = 0.0f; + action->control_flags |= FLAG(_unit_control_action_bit); + state->next_press = now + TICKS_PER_SECOND / 2; + } + else if (distance(&object_get(unit_index)->object.position, &state->entrance) < 3.0f) + { + real_point3d *position = &object_get(unit_index)->object.position; + real_point3d aim = state->entrance; + real_point3d const *center = &object_get(state->sought)->object.position; + real dx = aim.x - position->x, dy = aim.y - position->y; + real vx = center->x - position->x, vy = center->y - position->y; + real length = MAX(0.01f, (real)sqrt(dx * dx + dy * dy)); + real along = (dx * vx + dy * vy) / (length * length); + real width = distance(center, &state->entrance); + real toward, relative; + if (length > 1.2f && along > 0.0f && along < 1.2f && fabs(dx * vy - dy * vx) / length < width * 0.9f) + { + real side = -dy * vx + dx * vy > 0.0f ? -1.0f : 1.0f; + aim.x = center->x - dy / length * width * 1.1f * side; + aim.y = center->y + dx / length * width * 1.1f * side; + } + toward = (real)atan2(aim.y - position->y, aim.x - position->x); + relative = angle(toward - action->desired_facing.yaw); + action->throttle.i = (real)cos(relative) * 0.5f; + action->throttle.j = (real)sin(relative) * 0.5f; + } + } + return; + } + vehicle = unit_get(parent); + human_transport = vehicle_driver(parent) != unit_index && friendly_driver(unit_index, parent) && human_driver(parent); + if (state->ridden != parent) + { + state->ridden = parent; + state->sought = NONE; + state->stuck_tick = now; + state->ride_tick = now; + state->boarding_until = state->driverless_tick = state->off_arc_tick = state->charge_tick = 0; + state->last_position = vehicle->object.position; + state->stuck_count = state->reverse_until = 0; + platform_log("bots: bot %ld entered vehicle %ld seat %d type %d (%s)", index + 1, parent, + unit_get(unit_index)->unit.parent_seat_index, definition(parent)->type, tag_get_name(vehicle->definition_index)); + } + action->control_flags &= ~(FLAG(_unit_control_jump_bit) | FLAG(_unit_control_throw_grenade_bit) | + FLAG(_unit_control_use_equipment_bit)); + action->throttle.i = action->throttle.j = 0.0f; + if (bots_vehicle_flying(unit_index)) + { + boolean landing = (objective && !human_transport) || !config_boolean("bots.vehicles"); + real dx = goal->x - vehicle->object.position.x, dy = goal->y - vehicle->object.position.y; + real landing_radius = MAX(10.0f, vehicle->object.bounding_sphere_radius); + if (vehicle_driver(parent) == unit_index) + { + real_point3d destination = config_boolean("bots.vehicles") ? *goal : vehicle->object.position; + real aimed_yaw = action->desired_facing.yaw, aimed_pitch = action->desired_facing.pitch; + real trigger = action->primary_trigger; + unsigned long firing = action->control_flags & FLAG(_unit_control_weapon_primary_trigger_bit); + enhanced_flight_action(index, parent, definition(parent)->type == 3, &destination, landing, boarding(index, parent), action); + /* Retain an aimed shot only when flight steering still faces it. */ + if (target_unit != NONE && fabs(angle(action->desired_facing.yaw - aimed_yaw)) < 0.15f && + fabs(action->desired_facing.pitch - aimed_pitch) < 0.15f) + { + action->primary_trigger = trigger; + action->control_flags |= firing; + } + } + if ((landing || vehicle_driver(parent) == NONE || enhanced_flight_failed(index)) && enhanced_flight_can_exit(parent) && + (!config_boolean("bots.vehicles") || !objective || vehicle_driver(parent) == NONE || enhanced_flight_failed(index) || enhanced_flight_landing(index) || + dx * dx + dy * dy < landing_radius * landing_radius) && now >= state->next_press) + { + action->control_flags |= FLAG(_unit_control_action_bit); + state->next_press = now + TICKS_PER_SECOND / 2; + } + return; + } + if (vehicle_driver(parent) == unit_index && drivable(parent)) + { + real heading = (real)atan2(vehicle->object.forward.j, vehicle->object.forward.i); + real aimed_yaw = action->desired_facing.yaw, aimed_pitch = action->desired_facing.pitch; + boolean wait = now - state->ride_tick < TICKS_PER_SECOND || boarding(index, parent); + if (target_unit != NONE && !objective) + { + struct object_datum *target = object_try_and_get(target_unit); + if (target) + { + real range = distance(&target->object.position, &vehicle->object.position); + short type = definition(parent)->type; + if (type == 0 || type == 4) + { + direction = aimed_yaw; + moving = range > (type == 0 ? 20.0f : 12.0f); + } + else + { + direction = (real)atan2(target->object.position.y - vehicle->object.position.y, + target->object.position.x - vehicle->object.position.x); + if (vehicle->unit.gunner_object_index != NONE && range < 18.0f) + direction += (index & 1 ? 1.0f : -1.0f) * (range < 10.0f ? 1.885f : 1.257f); + moving = TRUE; + } + } + } + if (wait) moving = FALSE; + if (now - state->stuck_tick >= TICKS_PER_SECOND) + { + if (moving && distance(&state->last_position, &vehicle->object.position) < 0.6f) + { + state->stuck_count++; + if (state->stuck_count >= 2) bots_vehicle_obstacle(parent, goal); + if (state->stuck_count % 2 == 0) state->reverse_until = now + TICKS_PER_SECOND; + } + else state->stuck_count = 0; + state->last_position = vehicle->object.position; + state->stuck_tick = now; + } + if (moving) + { + if (definition(parent)->type == 4 && target_unit != NONE) + { + /* The Ghost can keep aiming while translating along its route. */ + action->throttle.i = (real)cos(angle(direction - aimed_yaw)); + action->throttle.j = (real)sin(angle(direction - aimed_yaw)); + } + else + { + action->desired_facing.yaw = direction; + action->desired_facing.pitch = 0.0f; + action->throttle.i = fabs(angle(direction - heading)) > 1.57f ? 0.6f : 1.0f; + } + if (now < state->reverse_until) + { + action->throttle.i = -0.6f; + action->desired_facing.yaw = heading - PIN(angle(direction - heading), -1.0f, 1.0f); + } + } + /* Changing the driver's aim must not turn a shot at an enemy into + a shot down the route. Gunners retain their separate combat controls. */ + if (fabs(angle(action->desired_facing.yaw - aimed_yaw)) > 0.15f || + fabs(action->desired_facing.pitch - aimed_pitch) > 0.15f) + { + action->control_flags &= ~FLAG(_unit_control_weapon_primary_trigger_bit); + action->primary_trigger = 0.0f; + } + } + else if (turret_seat(parent) == unit_get(unit_index)->unit.parent_seat_index) + { + leave = turret_action(state, parent, target_unit, action); + /* A human may be driving toward the fight; keep the gunner aboard. */ + leave = hurt || (leave && !human_transport); + } + else if (vehicle_driver(parent) == NONE) + { + if (!state->driverless_tick) state->driverless_tick = now; + leave = now - state->driverless_tick > 3 * TICKS_PER_SECOND && now - state->last_enemy_tick > 2 * TICKS_PER_SECOND; + } + else state->driverless_tick = 0; + if ((leave || !config_boolean("bots.vehicles") || vehicle->object.up.k < 0.3f || state->stuck_count >= 6 || + TEST_FLAG(vehicle->object.damage_flags, _object_dead_bit) || + (objective && !human_transport && distance(goal, &vehicle->object.position) < 10.0f && turret_seat(parent) == NONE)) && now >= state->next_press) + { + action->control_flags |= FLAG(_unit_control_action_bit); + state->next_press = now + TICKS_PER_SECOND / 2; + } +} diff --git a/port/linux/game/bots_vehicles.h b/port/linux/game/bots_vehicles.h new file mode 100644 index 0000000000..1e5524ca73 --- /dev/null +++ b/port/linux/game/bots_vehicles.h @@ -0,0 +1,22 @@ +/* Optional vehicle choices and ordinary player controls, owned by the host. */ +#ifndef HALO_BOTS_VEHICLES_H +#define HALO_BOTS_VEHICLES_H +struct player_action; +void bots_vehicles_reset(void); +void bots_vehicles_reset_player(long index); +long bots_vehicle_parent(long unit_index); +long bots_vehicle_navigation(long unit_index, real *radius); +long bots_vehicle_weapon(long unit_index, long weapon_index); +boolean bots_vehicle_goal(long index, long unit_index, real_point3d const *destination, + real_point3d *goal, long *surface); +boolean bots_vehicle_player_goal(long index, long unit_index, real_point3d const *destination, + real_point3d *goal, long *surface); +void bots_vehicle_action(long index, long unit_index, real_point3d const *goal, + boolean objective, boolean moving, real direction, long target_unit, boolean hurt, struct player_action *action); +/* Bot-owned obstacle learning; never changes the engine's path graph. */ +void bots_vehicle_obstacle(long vehicle_index, real_point3d const *goal); +boolean bots_vehicle_seeking(long index); +long bots_vehicle_sought(long index); +void bots_vehicle_cancel(long index); +boolean bots_vehicle_flying(long unit_index); +#endif diff --git a/port/linux/game/bots_worker.inl b/port/linux/game/bots_worker.inl new file mode 100644 index 0000000000..825d11dfac --- /dev/null +++ b/port/linux/game/bots_worker.inl @@ -0,0 +1,235 @@ +/* Optional path worker, inspired by thelinkin3000/halo-ce-universal's +BirchWoodGod-derived bots. This implementation owns three bounded jobs. +Only graph traversal runs off-thread; engine queries and path smoothing +stay on the game thread. Included by enhanced_bots_controller.c after bots_navigation.inl. */ +#include "physics/breakable_surfaces.h" +#include + +void bots_path_find_snapshot(struct path_state *state); + +struct bots_path_job +{ + void *request, *done; + boolean pending, waypoint, navigation; + long bot, unit, goal_surface, tick, serial, parent, seat; + short goal_kind, phase, link; + real radius; + real_point3d start, goal, original_goal, origin; + struct structure_bsp *original_structure; + struct structure_bsp structure; + struct path_state state; + byte *walkable; + long capacity; +}; +static struct +{ + boolean attempted; + void *thread, *wake, *quit; + struct bots_path_job *jobs; +} bots_worker; + +static unsigned long __stdcall bots_worker_main(void *unused) +{ + long index; + (void)unused; + for (;;) + { + WaitForSingleObject(bots_worker.wake, INFINITE); + if (WaitForSingleObject(bots_worker.quit, 0) == WAIT_OBJECT_0) break; + for (index = 0; index < BOTS_SEARCHES_A_TICK; index++) + { + struct bots_path_job *job = &bots_worker.jobs[index]; + if (WaitForSingleObject(job->request, 0) != WAIT_OBJECT_0) continue; + bots_path_find_snapshot(&job->state); + SetEvent(job->done); + } + } + return 0; +} + +static void bots_worker_stop(void) +{ + long index; + if (bots_worker.thread) + { + SetEvent(bots_worker.quit); + SetEvent(bots_worker.wake); + WaitForSingleObject(bots_worker.thread, INFINITE); + CloseHandle(bots_worker.thread); + } + if (bots_worker.jobs) + { + for (index = 0; index < BOTS_SEARCHES_A_TICK; index++) + { + struct bots_path_job *job = &bots_worker.jobs[index]; + if (job->request) CloseHandle(job->request); + if (job->done) CloseHandle(job->done); + if (job->walkable) free(job->walkable - 1); + } + free(bots_worker.jobs); + } + if (bots_worker.wake) CloseHandle(bots_worker.wake); + if (bots_worker.quit) CloseHandle(bots_worker.quit); + csmemset(&bots_worker, 0, sizeof(bots_worker)); +} + +/* Malformed rings use shared engine diagnostics. Keep those searches on +the game thread instead of racing the diagnostics' once-only flags. */ +static boolean bots_worker_graph_valid(struct structure_bsp const *structure) +{ + struct collision_bsp const *bsp; + long surface; + if (structure->collision_bsp.count <= 0) return FALSE; + bsp = TAG_BLOCK_GET_ELEMENT(&structure->collision_bsp, 0, struct collision_bsp); + for (surface = 0; surface < bsp->surfaces.count; surface++) + { + long first = TAG_BLOCK_GET_ELEMENT(&bsp->surfaces, surface, struct collision_surface)->first_edge_index; + long edge = first, count = 0; + do + { + struct collision_edge *entry; + long side, neighbor; + if (edge < 0 || edge >= bsp->edges.count || count++ >= MAXIMUM_PATH_EDGES_PER_COLLISION_SURFACE) return FALSE; + entry = TAG_BLOCK_GET_ELEMENT(&bsp->edges, edge, struct collision_edge); + for (side = 0; side < 2; side++) + if (entry->vertex_indices[side] < 0 || entry->vertex_indices[side] >= bsp->vertices.count) return FALSE; + side = entry->surface_indices[1] == surface; + if (entry->surface_indices[side] != surface) return FALSE; + neighbor = entry->surface_indices[!side]; + if (neighbor != NONE && (neighbor < 0 || neighbor >= bsp->surfaces.count)) return FALSE; + edge = entry->edge_indices[side]; + } while (edge != first); + } + return TRUE; +} + +static boolean bots_worker_start(struct structure_bsp const *structure) +{ + long index; + char const *fixed = getenv("HALO_FIXED_TICK"); + if (bots_worker.attempted) return bots_worker.thread != NULL; + bots_worker.attempted = TRUE; + if (!bots_worker_enabled || (fixed && atoi(fixed))) return FALSE; + if (!bots_worker_graph_valid(structure)) + { + platform_log("bots: path worker disabled for invalid collision rings; using synchronous searches"); + return FALSE; + } + /* cseries pairs tracked malloc/free; libc calloc has no engine header. */ + bots_worker.jobs = (struct bots_path_job *)malloc(BOTS_SEARCHES_A_TICK * sizeof(struct bots_path_job)); + if (bots_worker.jobs) csmemset(bots_worker.jobs, 0, BOTS_SEARCHES_A_TICK * sizeof(struct bots_path_job)); + bots_worker.wake = CreateEventA(NULL, FALSE, FALSE, NULL); + bots_worker.quit = CreateEventA(NULL, TRUE, FALSE, NULL); + if (!bots_worker.jobs || !bots_worker.wake || !bots_worker.quit) goto failed; + for (index = 0; index < BOTS_SEARCHES_A_TICK; index++) + { + bots_worker.jobs[index].request = CreateEventA(NULL, FALSE, FALSE, NULL); + bots_worker.jobs[index].done = CreateEventA(NULL, TRUE, FALSE, NULL); + if (!bots_worker.jobs[index].request || !bots_worker.jobs[index].done) goto failed; + } + bots_worker.thread = CreateThread(NULL, 256 * 1024, bots_worker_main, NULL, 0, NULL); + if (!bots_worker.thread) goto failed; + platform_log("bots: snapshot path worker enabled"); + return TRUE; +failed: + bots_worker_stop(); + bots_worker.attempted = TRUE; + platform_log("bots: path worker unavailable; using synchronous searches"); + return FALSE; +} + +/* Events transfer ownership of each job. A completed stale answer may be +discarded, but an in-flight job is never overwritten, even after respawn. */ +static struct bots_path_job *bots_worker_job(struct bots_bot *bot) +{ + long index; + if (!bots_worker.thread) return NULL; + for (index = 0; index < BOTS_SEARCHES_A_TICK; index++) + { + struct bots_path_job *job = &bots_worker.jobs[index]; + struct bots_bot *owner; + struct bots_nav_route *route; + if (!job->pending) continue; + owner = &bots_globals.bots[job->bot]; + route = &bots_navigation.routes[job->bot]; + if (WaitForSingleObject(job->done, 0) == WAIT_OBJECT_0 && + (owner->unit_index != job->unit || owner->goal_serial != job->serial || + owner->navigation_parent != job->parent || owner->navigation_seat != job->seat || owner->goal_kind != job->goal_kind || + bots_distance3d(&owner->goal_point, &job->original_goal) > 1.0f || + bots_distance3d(&owner->last_position, &job->origin) > 3.0f || + route->phase != job->phase || route->link != job->link || game_time_get() - job->tick > TICKS_PER_SECOND)) + { + job->pending = FALSE; + continue; + } + if (owner == bot) return job; + } + return NULL; +} + +static boolean bots_worker_submit(struct bots_bot *bot, struct path_state *state, + real_point3d const *start, real_point3d const *goal, long goal_surface, + boolean waypoint, boolean navigation, real radius) +{ + struct bots_path_job *job = NULL; + struct collision_bsp const *bsp; + long index, count = state->structure->pathfinding_surfaces.count; + long const *broken; + if (count <= 0 || !bots_worker_start(state->structure)) return FALSE; + for (index = 0; index < BOTS_SEARCHES_A_TICK; index++) + if (!bots_worker.jobs[index].pending) { job = &bots_worker.jobs[index]; break; } + if (!job) return FALSE; + if (job->capacity < count) + { + byte *memory = (byte *)malloc((size_t)count + 1); + if (!memory) return FALSE; + /* Preserve the old tracked allocation if growth fails. */ + if (job->walkable) free(job->walkable - 1); + /* An open edge's neighbor is NONE; path.c reads this sentinel. */ + memory[0] = 0; + job->walkable = memory + 1; + job->capacity = count; + } + job->structure = *state->structure; + job->original_structure = state->structure; + csmemcpy(job->walkable, state->structure->pathfinding_surfaces.address, count); + job->structure.pathfinding_surfaces.address = job->walkable; + /* Snapshot mutable breakage before handing immutable BSP geometry to + the worker. Map disposal joins it before that geometry can be freed. */ + bsp = TAG_BLOCK_GET_ELEMENT(&state->structure->collision_bsp, 0, struct collision_bsp); + broken = (long const *)breakable_surface_flags_get(); + if (!state->input.ignore_broken_surfaces) + for (index = 0; index < count && index < bsp->surfaces.count; index++) + { + struct collision_surface *surface = TAG_BLOCK_GET_ELEMENT(&bsp->surfaces, index, struct collision_surface); + if (TEST_FLAG(job->walkable[index], 7) && TEST_FLAG(surface->flags, 3) && broken && + surface->breakable_surface_index < state->structure->breakable_surfaces.count && + !BIT_VECTOR_TEST_FLAG(broken, surface->breakable_surface_index)) + SET_FLAG(job->walkable[index], BOTS_PATHFINDING_WALKABLE_BIT, FALSE); + } + job->state = *state; + job->state.structure = &job->structure; + job->state.input.ignore_broken_surfaces = TRUE; + job->bot = (long)(bot - bots_globals.bots); + job->unit = bot->unit_index; + job->serial = bot->goal_serial; + job->parent = bot->navigation_parent; + job->seat = bot->navigation_seat; + job->goal_kind = bot->goal_kind; + job->original_goal = bot->goal_point; + job->origin = bot->last_position; + job->phase = bots_navigation.routes[job->bot].phase; + job->link = bots_navigation.routes[job->bot].link; + job->tick = game_time_get(); + job->start = *start; + job->goal = *goal; + job->goal_surface = goal_surface; + job->waypoint = waypoint; + job->navigation = navigation; + job->radius = radius; + job->pending = TRUE; + ResetEvent(job->done); + SetEvent(job->request); + SetEvent(bots_worker.wake); + return TRUE; +} diff --git a/port/linux/game/cache_file_formats.c b/port/linux/game/cache_file_formats.c index 13b3e8103c..8c82a997a3 100644 --- a/port/linux/game/cache_file_formats.c +++ b/port/linux/game/cache_file_formats.c @@ -24,6 +24,7 @@ evidence. /* ---------- headers */ #include "cache_file_formats.h" +#include "custom_edition_hud_scale.h" #include #include @@ -3199,7 +3200,7 @@ flag at half the size of its bitmap, and Custom Edition's HUD bitmaps are made for that: in Blood Gulch every flagged element draws a bitmap twice the size of the one its Xbox counterpart draws, and every other element one of the same size (docs/custom_edition_caches.md). A bitmap may ask the same of -every element that draws it (hud_bitmap_halves_scale). This build has no +every element that draws it (hud_bitmap_scale_flags). This build has no such flags (hud_draw.c draws a bitmap at its size times the placement's scale), so the scale takes them in. @@ -3209,15 +3210,18 @@ items are halved by their bitmap's flags alone. A number keeps its flag, which hud_draw_numbers reads: its scale is not its digits'. */ static void hud_placement_convert( uint8_t *placement, - int bitmap_halves_scale, + uint16_t bitmap_flags, + int items, struct custom_edition_conversion_report *report) { uint16_t flags = read_u16(placement + HUD_PLACEMENT_SCALING_FLAGS_OFFSET); + float scale = custom_edition_hud_scale(bitmap_flags, + !items && flag_is_set(flags, HUD_SCALING_USE_HIGH_RESOLUTION_SCALE_BIT)); - if (flag_is_set(flags, HUD_SCALING_USE_HIGH_RESOLUTION_SCALE_BIT) || bitmap_halves_scale) + if (scale != 1.0f) { - write_f32(placement + HUD_PLACEMENT_WIDTH_SCALE_OFFSET, read_f32(placement + HUD_PLACEMENT_WIDTH_SCALE_OFFSET) * 0.5f); - write_f32(placement + HUD_PLACEMENT_HEIGHT_SCALE_OFFSET, read_f32(placement + HUD_PLACEMENT_HEIGHT_SCALE_OFFSET) * 0.5f); + write_f32(placement + HUD_PLACEMENT_WIDTH_SCALE_OFFSET, read_f32(placement + HUD_PLACEMENT_WIDTH_SCALE_OFFSET) * scale); + write_f32(placement + HUD_PLACEMENT_HEIGHT_SCALE_OFFSET, read_f32(placement + HUD_PLACEMENT_HEIGHT_SCALE_OFFSET) * scale); write_u16( placement + HUD_PLACEMENT_SCALING_FLAGS_OFFSET, (uint16_t)(flags & ~(1U << HUD_SCALING_USE_HIGH_RESOLUTION_SCALE_BIT))); @@ -3227,9 +3231,8 @@ static void hud_placement_convert( return; } -/* whether the bitmap a HUD element draws (its tag reference) has Halo PC's -half HUD scale or force HUD high resolution scale flag */ -static int hud_bitmap_halves_scale( +/* The flags of the bitmap a HUD element draws (its tag reference). */ +static uint16_t hud_bitmap_scale_flags( struct load_state const *state, uint8_t const *reference) { @@ -3252,7 +3255,7 @@ static int hud_bitmap_halves_scale( } flags = read_u16(state->tag_cache + offset + BITMAP_GROUP_FLAGS_OFFSET); - return flag_is_set(flags, BITMAP_HALF_HUD_SCALE_BIT) || flag_is_set(flags, BITMAP_FORCE_HUD_HIGH_RESOLUTION_SCALE_BIT); + return flags; } /* the placement at `placement_offset` in each element of the block at @@ -3427,17 +3430,9 @@ static void hud_conversion_placement( int items) { struct hud_conversion const *conversion = context; - int bitmap_halves_scale = bitmap && hud_bitmap_halves_scale(conversion->state, bitmap); + uint16_t bitmap_flags = bitmap ? hud_bitmap_scale_flags(conversion->state, bitmap) : 0; - if (items) - { - if (bitmap_halves_scale) - hud_placement_convert(placement, 1, conversion->report); - } - else - { - hud_placement_convert(placement, bitmap_halves_scale, conversion->report); - } + hud_placement_convert(placement, bitmap_flags, items, conversion->report); return; } diff --git a/port/linux/game/cache_file_formats.h b/port/linux/game/cache_file_formats.h index fe06f5db06..d4f461b642 100644 --- a/port/linux/game/cache_file_formats.h +++ b/port/linux/game/cache_file_formats.h @@ -312,7 +312,7 @@ struct custom_edition_conversion_report unplayable */ int32_t sounds_undecodable; /* HUD element placements with Halo PC's high resolution scale, whose - scale was halved */ + scale was reduced by the CE placement and bitmap flags */ int32_t hud_placements_rescaled; /* HUD meters whose minimum alpha (Halo PC's, where the Xbox's meters have an overlays block) was taken out */ diff --git a/port/linux/game/changelog_menu_runtime.inl b/port/linux/game/changelog_menu_runtime.inl new file mode 100644 index 0000000000..f35e66a636 --- /dev/null +++ b/port/linux/game/changelog_menu_runtime.inl @@ -0,0 +1,164 @@ +/* The changelog's eight visible text rows read paired immutable body and + * category-heading string lists; exactly one contains text at each index. + * The container's otherwise unused list fields keep its own line offset; + * deleting or opening a build discards that state with the instance. */ + +#include "tag_files/tag_files.h" + +#define CHANGELOG_VISIBLE_LINES 8 + +static boolean changelog_menu_main_focus(struct widget_instance *widget, boolean corner) +{ + struct widget_instance *main_list, *corner_list, *button, *child; + char const *name; + short index; + + while (widget && widget->parent) + widget = widget->parent; + name = widget ? tag_get_name(widget->definition_tag_index) : NULL; + if (!name || strcmp(name, "pc\\main_menu\\main_menu")) + return FALSE; + main_list = named(widget, "main_menu_select_list", 0); + corner_list = named(widget, "changelog_corner", 0); + button = named(corner_list, "main_menu_item_changelog", 0); + if (!main_list || main_list->type != 3 || !corner_list || corner_list->type != 3 || !button) + return FALSE; + if (corner) + { + main_list->focused_child = NULL; + corner_list->focused_child = button; + widget->focused_child = corner_list; + } + else + { + /* Mouse focus clears the old chain, but retains the list's selected + index. Restore that child without changing the six-row tab behavior. */ + if (!main_list->focused_child) + { + child = main_list->child; + for (index = 0; child && child->next && index < main_list->parameters.list.selected_index; index++) + child = child->next; + main_list->focused_child = child; + } + if (main_list->focused_child && main_list->focused_child->animation.number_of_sprite_frames == 2) + main_list->focused_child->animation.current_frame_index = 1; + widget->focused_child = main_list; + } + return TRUE; +} + +static void changelog_menu_focus_update(struct widget_instance *widget) +{ + static char const prefix[] = "pc\\main_menu\\changelog\\build_"; + struct widget_instance *corner, *button, *main_list, *child; + char const *name = widget ? tag_get_name(widget->definition_tag_index) : NULL; + short index; + + if (!name) + return; + if (widget->type == 0 && !widget->parent && !strncmp(name, prefix, sizeof(prefix) - 1) && + name[sizeof(prefix) - 1] && strspn(name + sizeof(prefix) - 1, "0123456789") == strlen(name + sizeof(prefix) - 1)) + { + short list_index; + + /* The engine updates only the focused list. Synchronize our two + button groups so the inactive group cannot retain a white outline. */ + for (list_index = 0; list_index < 2; list_index++) + { + main_list = named(widget, list_index ? "buttons" : "scroll_controls", 0); + if (!main_list || main_list->type != 3) + continue; + for (child = main_list->child, index = 0; child && index < 3; child = child->next, index++) + if (child->animation.number_of_sprite_frames == 2) + child->animation.current_frame_index = !child->disabled && + widget->focused_child == main_list && main_list->focused_child == child; + } + return; + } + if (strcmp(name, "pc\\main_menu\\main_menu")) + return; + corner = named(widget, "changelog_corner", 0); + button = named(corner, "main_menu_item_changelog", 0); + if (corner && button) + { + button->animation.current_frame_index = widget->focused_child == corner && corner->focused_child == button; + main_list = named(widget, "main_menu_select_list", 0); + /* Mouse focus bypasses the Right handler. The inactive list is not + updated by the engine, so clear its old glow before it is rendered. */ + if (widget->focused_child == corner && main_list) + for (child = main_list->child, index = 0; child && index < 6; child = child->next, index++) + if (child->animation.number_of_sprite_frames == 2) + child->animation.current_frame_index = 0; + } +} + +static boolean changelog_menu_event(struct widget_instance *widget, char const *event) +{ + static char const prefix[] = "pc\\main_menu\\changelog\\build_"; + struct widget_instance *root = widget; + struct string_list *strings, *headings; + char const *name; + char list_name[256], row_name[32], position[64]; + wchar_t wide_position[64]; + long list_tag, heading_tag, count, first, maximum, row; + boolean initialize = !strcmp(event, "port changelog init"); + long direction = !strcmp(event, "port changelog down") ? 1 : -1; + + if (!strcmp(event, "port changelog corner focus") || !strcmp(event, "port changelog main focus")) + return changelog_menu_main_focus(widget, !strcmp(event, "port changelog corner focus")); + if (!initialize && strcmp(event, "port changelog up") && strcmp(event, "port changelog down")) + return FALSE; + while (root && root->parent) + root = root->parent; + if (!root || root->type != 0) + return FALSE; + name = tag_get_name(root->definition_tag_index); + if (!name || strncmp(name, prefix, sizeof(prefix) - 1)) + return FALSE; + if (snprintf(list_name, sizeof(list_name), "%s\\lines", name) >= (long)sizeof(list_name)) + return FALSE; + list_tag = tag_loaded(UNICODE_STRING_LIST_TAG, list_name); + if (list_tag == NONE) + return FALSE; + strings = unicode_string_list_definition_get(list_tag); + if (!strings || strings->strings.count <= CHANGELOG_VISIBLE_LINES || strings->strings.count > 32767) + return FALSE; + if (snprintf(list_name, sizeof(list_name), "%s\\headings", name) >= (long)sizeof(list_name)) + return FALSE; + heading_tag = tag_loaded(UNICODE_STRING_LIST_TAG, list_name); + if (heading_tag == NONE) + return FALSE; + headings = unicode_string_list_definition_get(heading_tag); + if (!headings || headings->strings.count != strings->strings.count) + return FALSE; + /* The trailing empty strings let a short document fill the viewport. */ + count = strings->strings.count - CHANGELOG_VISIBLE_LINES; + maximum = MAX(0, count - CHANGELOG_VISIBLE_LINES); + first = initialize ? 0 : PIN((long)root->parameters.list.selected_index + direction, 0, maximum); + root->parameters.list.selected_index = (short)first; + for (row = 0; row < CHANGELOG_VISIBLE_LINES; row++) + { + struct widget_instance *text; + + snprintf(row_name, sizeof(row_name), "row_%ld", row); + text = named(root, row_name, 0); + if (text && text->type == 1) + text->parameters.text_box.string_list_index = (short)(first + row); + snprintf(row_name, sizeof(row_name), "heading_row_%ld", row); + text = named(root, row_name, 0); + if (text && text->type == 1) + text->parameters.text_box.string_list_index = (short)(first + row); + } + snprintf(position, sizeof(position), "Lines %ld-%ld of %ld", first + 1, + MIN(first + CHANGELOG_VISIBLE_LINES, count), count); + halo_menus_utf16(position, (unsigned short *)wide_position, NUMBEROF(wide_position)); + text_set(named(root, "scroll_position", 0), wide_position); + /* At either end, the buttons stay visible but cannot take focus/clicks. */ + widget = named(root, "scroll_up", 0); + if (widget) + widget->disabled = first == 0; + widget = named(root, "scroll_down", 0); + if (widget) + widget->disabled = first == maximum; + return TRUE; +} diff --git a/port/linux/game/controller_button_menu.inl b/port/linux/game/controller_button_menu.inl index e13c2be0dc..75cd9f865f 100644 --- a/port/linux/game/controller_button_menu.inl +++ b/port/linux/game/controller_button_menu.inl @@ -25,11 +25,7 @@ static void controller_button_rows_show(struct widget_instance *list) family = (short)device.family; } if (family < 0 || family > 3) family = 0; - spinner = named(list, "keyboard_glyphs_spinner", 0); - setting = spinner ? pc_menu_setting_get(spinner->definition_tag_index) : NULL; - index = spinner ? spinner->parameters.list.selected_index : -1; - if (detect && setting && index >= 0 && index < setting->value_count && - !strcmp(setting->values[index], "true") && keyboard_prompt_active(port)) family = 4; + if (detect && keyboard_prompt_active(port)) family = 4; shown = named(list, rows[family], 0); if (!shown) return; for (index = 0; index < 5; index++) diff --git a/port/linux/game/controller_glyphs.c b/port/linux/game/controller_glyphs.c index cd5dc296f8..b1593c26f4 100644 --- a/port/linux/game/controller_glyphs.c +++ b/port/linux/game/controller_glyphs.c @@ -111,10 +111,9 @@ struct bitmap_data *controller_glyph_bitmap(short style, short slot, real_rectan uv->y1 = entry->bounds[3] / 512.0f; return bitmap; } - -boolean controller_glyph_draw_with_release(short style, short index, +static boolean controller_glyph_draw_internal(short style, short index, struct icon_hud_element_definition const *icon, rectangle2d *cursor, pixel32 color, - void (*unbind)(unsigned long const *)) + void (*unbind)(unsigned long const *), boolean menu) { struct rasterizer_dynamic_screen_geometry_parameters parameters; struct dynamic_screen_vertex vertices[4]; @@ -135,6 +134,14 @@ boolean controller_glyph_draw_with_release(short style, short index, scale = local_player_count() > 1 ? 0.75f : 1.0f; cell_width = (slot < 6 ? 21.0f : slot < 8 ? 44.0f : 32.0f) * scale; cell_height = (slot < 6 ? 26.0f : slot < 8 ? 33.0f : 34.0f) * scale; + /* Menu helpers have a smaller, fixed footer than gameplay prompts. Keep + * their visible ink inside it and reserve space after the entire glyph. */ + if (menu) + { + scale = 1.0f; + cell_width = slot < 6 ? 16.0f : 20.0f; + cell_height = slot < 6 ? 20.0f : 22.0f; + } width = entry->bounds[2] - entry->bounds[0]; height = entry->bounds[3] - entry->bounds[1]; fit = MIN(cell_width / width, cell_height / height); @@ -159,10 +166,25 @@ boolean controller_glyph_draw_with_release(short style, short index, vertices[i].color = color; } rasterizer_psuedo_dynamic_screen_quad_draw(¶meters, vertices); - cursor->x0 += (short)((slot < 4 ? 22.0f : slot < 6 ? 20.0f : slot < 8 ? 45.0f : 33.0f) * scale); + cursor->x0 += (short)(menu ? cell_width + 10.0f : + (slot < 4 ? 22.0f : slot < 6 ? 20.0f : slot < 8 ? 45.0f : 33.0f) * scale); return TRUE; } +boolean controller_glyph_draw_with_release(short style, short index, + struct icon_hud_element_definition const *icon, rectangle2d *cursor, pixel32 color, + void (*unbind)(unsigned long const *)) +{ + return controller_glyph_draw_internal(style, index, icon, cursor, color, unbind, FALSE); +} + +boolean controller_glyph_draw_menu(short style, short index, rectangle2d *cursor, pixel32 color) +{ + struct icon_hud_element_definition icon; + memset(&icon, 0, sizeof(icon)); + return controller_glyph_draw_internal(style, index, &icon, cursor, color, NULL, TRUE); +} + boolean controller_glyph_draw(short style, short index, struct icon_hud_element_definition const *icon, rectangle2d *cursor, pixel32 color) { diff --git a/port/linux/game/controller_glyphs.h b/port/linux/game/controller_glyphs.h index d594747ec2..0e562aec94 100644 --- a/port/linux/game/controller_glyphs.h +++ b/port/linux/game/controller_glyphs.h @@ -6,12 +6,12 @@ struct icon_hud_element_definition; short controller_glyph_style(void); struct bitmap_data *controller_glyph_bitmap(short style, short slot, real_rectangle2d *uv); -boolean controller_glyph_draw(short style, short index, - struct icon_hud_element_definition const *icon, rectangle2d *cursor, pixel32 color); -/* Optional owner callback releases external bindings before bitmap deletion. */ boolean controller_glyph_draw_with_release(short style, short index, struct icon_hud_element_definition const *icon, rectangle2d *cursor, pixel32 color, void (*unbind)(unsigned long const *)); void controller_glyphs_dispose(void); +boolean controller_glyph_draw_menu(short style, short index, rectangle2d *cursor, pixel32 color); +boolean controller_glyph_draw(short style, short index, + struct icon_hud_element_definition const *icon, rectangle2d *cursor, pixel32 color); #endif diff --git a/port/linux/game/controller_remap_menu.inl b/port/linux/game/controller_remap_menu.inl index 8ee77b8a75..d36c0e1652 100644 --- a/port/linux/game/controller_remap_menu.inl +++ b/port/linux/game/controller_remap_menu.inl @@ -5,9 +5,10 @@ static wchar_t const *const pad_action_labels[CONTROLLER_REMAP_ACTIONS] = { L"FLASHLIGHT", L"THROW GRENADE", L"FIRE", L"CROUCH", L"ZOOM", L"SCOREBOARD", L"SCREENSHOT", L"MOVE FORWARD", L"MOVE BACKWARD", L"STRAFE LEFT", L"STRAFE RIGHT", L"ALL CHAT", L"TEAM CHAT", L"VEHICLE CHAT", L"PUSH TO TALK", - L"CAMERA SPEED UP", L"CAMERA SPEED DOWN", L"CAMERA / PLAYER SWITCH", L"CAMERA RAISE", L"CAMERA LOWER", L"CYCLE CAMERA" + L"CAMERA SPEED UP", L"CAMERA SPEED DOWN", L"CAMERA / PLAYER SWITCH", L"CAMERA RAISE", L"CAMERA LOWER", L"CYCLE CAMERA", + L"THIRD PERSON ON / OFF", L"SWAP SHOULDER" }; -static short const pad_action_groups[CONTROLLER_REMAP_ACTIONS] = {0,1,1,1,1,2,1,1,0,2,2,2,0,0,0,0,3,3,3,3,4,4,4,4,4,4}; +static short const pad_action_groups[CONTROLLER_REMAP_ACTIONS] = {0,1,1,1,1,2,1,1,0,2,2,2,0,0,0,0,3,3,3,3,4,4,4,4,4,4,5,5}; static struct { unsigned char buttons[4][CONTROLLER_REMAP_ACTIONS]; @@ -199,6 +200,8 @@ static void pad_editor_update(struct widget_instance *list) snprintf(caption, sizeof(caption), "Choose buttons for chat and push-to-talk.\r\nChat belongs to the player who opens it.\r\nVoice uses the shared microphone and the\r\nfirst player's team and vehicle channels."); else if (group == 4) snprintf(caption, sizeof(caption), "Hold Cycle Camera for one second to change views.\r\nCamera / Player Switch changes who you control.\r\nOther actions control an available debug camera.\r\nThese buttons can reuse your gameplay buttons."); + else if (group == 5) + snprintf(caption, sizeof(caption), "Toggle third person or swap its shoulder.\r\nUses the same camera settings as the keyboard.\r\nHost camera rules still apply.\r\nBoth actions are UNBOUND by default."); } } for (i = 0; caption[i] && i < 255; i++) text[i] = (wchar_t)(unsigned char)caption[i]; diff --git a/port/linux/game/covenant_emitter_lighting.c b/port/linux/game/covenant_emitter_lighting.c new file mode 100644 index 0000000000..f437f6f720 --- /dev/null +++ b/port/linux/game/covenant_emitter_lighting.c @@ -0,0 +1,431 @@ +/* Render-owned illumination from visible Covenant shields and fuel rods. + No tags, shield state, weapon effects or simulation lights are changed. */ +#include "cseries.h" +#include "objects/objects.h" +#include "objects/object_definitions.h" +#include "objects/object_lights.h" +#include "models/model_definitions.h" +#include "items/weapons.h" +#include "units/units.h" +#include "camera/observer.h" +#include "game/players.h" +#include "covenant_emitter_lighting.h" +#include "ammo_counter_lighting.h" +#include "needler_lighting.h" +#include "authored_emitter_lighting.h" +#include "ambient_emitter_lighting.h" +#include "plasma_occlusion.h" +#include +#include + +#include "lighting_config.h" +real render_interpolation_game_time_sec(long ticks); +long light_port_glow_definition_get(void); +boolean light_port_glow_set(long light, long owner, real_rgb_color const *color, real radius); +boolean light_port_glow_move(long light, real_point3d const *position); + +enum { EMITTER_LIGHTS = 8 }; +static struct emitter_light +{ + int active, connected, seen, kind, component; + long object, light, rasterizer; + real strength, last_time, radius; + real_point3d position; + real_vector3d direction; +} emitters[EMITTER_LIGHTS]; +static const real_rgb_color emitter_black = {0, 0, 0}; + +int covenant_emitter_lighting_enabled(void) +{ + return lighting_config_boolean("display.jackal_shield_lighting") || lighting_config_boolean("display.fuel_rod_lighting") || + lighting_config_boolean("display.covenant_shield_lighting") || lighting_config_boolean("display.ammo_counter_lighting") || + lighting_config_boolean("display.needler_lighting") || ambient_emitter_lighting_enabled(); +} + +static int emitter_kind_enabled(int kind) +{ + return lighting_config_boolean(kind == EMITTER_VEHICLE ? "display.vehicle_lighting" : + kind == EMITTER_WORLD ? "display.world_lighting" : kind == EMITTER_FLAME ? "display.plasma_lighting" : kind == 4 ? "display.needler_lighting" : kind == 3 ? "display.ammo_counter_lighting" : kind == 2 ? "display.covenant_shield_lighting" : + kind == 1 ? "display.fuel_rod_lighting" : "display.jackal_shield_lighting"); +} + +static int emitter_shield_visible(struct object_datum *object) +{ + struct object_definition *definition = object_definition_get(object->definition_index); + struct model *model; + int i; + if (definition->object.model.index == NONE || + (object->object.maximum_body_vitality > 0.0f && object->object.body_vitality <= 0.0f) || + object->object.shield_vitality <= 0.0f || + TEST_FLAG(object->object.damage_flags, _object_shield_depleted_bit)) + return FALSE; + model = model_definition_get(definition->object.model.index); + for (i = 0; i < model->regions.count && i < MAXIMUM_REGIONS_PER_OBJECT; i++) + { + struct model_region *region = TAG_BLOCK_GET_ELEMENT(&model->regions, i, struct model_region); + if (!strcmp(region->name, "shield")) + /* Stock base00 is permutation zero; ~shield_off is one. The + shield-light marker itself also exists in the off permutation. */ + return object->object.region_permutations[i] == 0 && + !TEST_FLAG(object->object.regions_destroyed_flags, i); + } + return FALSE; +} + +static int emitter_sample(long index, int component, struct emitter_sample *sample) +{ + struct object_datum *object = object_try_and_get(index); + struct object_marker marker; + const char *name; + const char *marker_name; + real nearest = 25.0f; + short player; + int counter_pose; + sample->view_gain = 1.0f; + if (!object || TEST_FLAG(object->object.flags, _object_invisible_bit) || + object->object.node_matrices.size < sizeof(real_matrix4x3)) + return FALSE; + name = tag_get_name(object->definition_index); + if (!name) + return FALSE; + if (ambient_emitter_lighting_sample(index, component, sample)) + marker_name = NULL; + else if (component) + return FALSE; + else if ((object->object.type == _object_type_biped && + (!strcmp(name, "characters\\jackal\\jackal") || !strcmp(name, "characters\\jackal\\jackal major"))) || + (object->object.type == _object_type_scenery && !strcmp(name, "scenery\\c_field_generator\\c_field_generator"))) + { + sample->kind = object->object.type == _object_type_scenery ? 2 : 0; + sample->radius = sample->kind == 2 ? 2.8f : 3.6f; + marker_name = "shield light"; + /* The stock shield shader's colour source is change colour C. */ + sample->color = object->object.outgoing_change_colors[2]; + if (sample->kind == 0 && sample->color.blue > sample->color.red * 2.0f) + { + /* Blue needs more luminance and reach to illuminate nearby walls. */ + sample->color.red = MAX(sample->color.red, 0.30f); + sample->color.green = MAX(sample->color.green, 0.42f); + } + if (sample->kind == 0 && sample->color.red > sample->color.blue * 2.0f) + { + /* Gold shares the blue shield's reach, with brighter warm spill. */ + sample->color.green = MAX(sample->color.green, 0.78f); + sample->color.blue = MAX(sample->color.blue, 0.24f); + } + { + /* Both stock shield combiners blend change colour C towards red + using A-out (stage 3). Use that evaluated animation value, not + vitality or our own hit timer, so damage/recovery stay in sync. */ + real flash = PIN(object->object.outgoing_function_values[0], 0.0f, 1.0f); + sample->color.red += (1.0f - sample->color.red) * flash; + sample->color.green *= 1.0f - flash; + sample->color.blue *= 1.0f - flash; + } + sample->strength = emitter_shield_visible(object) ? + 0.7f + 0.15f * PIN(object->object.shield_vitality, 0.0f, 1.0f) + + 0.15f * PIN(object->object.recent_shield_damage, 0.0f, 1.0f) : 0.0f; + } + else if ((object->object.type == _object_type_weapon && !strcmp(name, "weapons\\fuel rod gun\\fuel rod")) || + (object->object.type == _object_type_biped && !strcmp(name, "characters\\hunter\\hunter"))) + { + /* The rod marker is on the back of this model, not at its muzzle. + Dropped rods remain luminous while their stock model still exists. */ + if (object->object.type == _object_type_weapon && object->object.parent_object_index != NONE) + { + struct unit_datum *unit = unit_try_and_get(object->object.parent_object_index); + if (!unit || TEST_FLAG(unit->object.flags, _object_invisible_bit) || + unit->unit.current_weapon_index < 0 || unit->unit.current_weapon_index >= MAXIMUM_WEAPONS_PER_UNIT || + unit_inventory_get_weapon(object->object.parent_object_index, unit->unit.current_weapon_index) != index) + return FALSE; + } + sample->kind = 1; + sample->radius = 1.6f; + /* The Hunter's visible rods and rodflare marker belong to its animated + forearm, not its separate model-less weapon. */ + marker_name = object->object.type == _object_type_biped ? "rodflare" : "lens flare"; + sample->color.red = 0.15f; + sample->color.green = 1.0f; + sample->color.blue = 0.05f; + sample->strength = 0.75f; + } + else if (object->object.type == _object_type_weapon && + (counter_pose = ammo_counter_lighting_position(index, &sample->position, &sample->direction))) + { + sample->kind = 3; + sample->radius = 0.95f; + sample->color.red = 0.24f; + sample->color.green = 0.65f; + sample->color.blue = 1.0f; + /* Keep view-specific brightness out of the shared temporal history. */ + sample->strength = 0.65f; + sample->view_gain = counter_pose == 2 ? 1.35f / 0.65f : 1.0f; + marker_name = NULL; + } + else if (object->object.type == _object_type_weapon && needler_lighting_position(index, &sample->position, &sample->direction)) + { + sample->kind = 4; + sample->radius = 1.5f; + sample->color.red = 1.0f; + sample->color.green = 0.24f; + sample->color.blue = 0.85f; + sample->strength = 0.9f; + marker_name = NULL; + } + else + return FALSE; + if (!emitter_kind_enabled(sample->kind)) + return FALSE; + if (marker_name) + { + if (!object_get_marker_by_name(index, marker_name, &marker, 1)) + return FALSE; + sample->position = marker.matrix.position; + } + for (player = local_player_get_next(NONE); player != NONE; player = local_player_get_next(player)) + { + const struct observer_result *camera = observer_get_camera(player); + if (camera) + nearest = MIN(nearest, distance3d(&sample->position, &camera->position)); + } + /* Fade before the admission boundary instead of popping at 25 units. */ + sample->strength *= PIN((25.0f - nearest) / 3.0f, 0.0f, 1.0f); + return TRUE; +} + +static void emitter_release(struct emitter_light *emitter) +{ + if (emitter->active && emitter->light != NONE && + light_port_glow_set(emitter->light, NONE, &emitter_black, 0.0f)) + light_delete(emitter->light); + memset(emitter, 0, sizeof(*emitter)); +} + +void covenant_emitter_lighting_update(void) +{ + struct object_iterator iterator; + struct object_datum *object; + unsigned long mask; + int i, slot, component; + real now = render_interpolation_game_time_sec(game_time_get()); + for (i = 0; i < EMITTER_LIGHTS; i++) + { + if (emitters[i].active && (!emitter_kind_enabled(emitters[i].kind) || now < emitters[i].last_time)) + emitter_release(&emitters[i]); + emitters[i].seen = FALSE; + } + if (!covenant_emitter_lighting_enabled()) + return; + mask = ambient_emitter_lighting_begin(); + if (lighting_config_boolean("display.jackal_shield_lighting") || lighting_config_boolean("display.fuel_rod_lighting")) + mask |= _object_mask_biped; + if (lighting_config_boolean("display.fuel_rod_lighting") || lighting_config_boolean("display.ammo_counter_lighting") || + lighting_config_boolean("display.needler_lighting")) + mask |= _object_mask_weapon; + if (lighting_config_boolean("display.covenant_shield_lighting")) mask |= _object_mask_scenery; + /* With no live stream and no enabled object emitters, skip the object + walk. Still release unseen stream lights below. */ + object_iterator_new(&iterator, mask, 0); + while (mask && (object = object_iterator_next(&iterator)) != NULL) + for (component = 0; component < (object->object.type == _object_type_vehicle ? 2 : 1); component++) + { + struct emitter_sample sample; + struct emitter_light *emitter; + real_rgb_color color; + real blend; + long definition; + if (!emitter_sample(iterator.index, component, &sample)) + continue; + slot = NONE; + for (i = 0; i < EMITTER_LIGHTS; i++) + { + if (emitters[i].active && emitters[i].object == iterator.index && emitters[i].component == component) + { + slot = i; + if (emitters[i].kind != sample.kind) emitter_release(&emitters[i]); + break; + } + if (!emitters[i].active && slot == NONE) + slot = i; + } + /* New ambient sources must not displace the baseline's held-weapon + and shield lights. Reclaim the weakest ambient slot only when a + visible baseline emitter needs one; the eight-light budget stays. */ + if (slot == NONE && sample.kind < EMITTER_VEHICLE && sample.strength > 0.0f) + { + for (i = 0; i < EMITTER_LIGHTS; i++) + if (emitters[i].kind >= EMITTER_VEHICLE && + (slot == NONE || emitters[i].strength < emitters[slot].strength)) + slot = i; + if (slot != NONE) emitter_release(&emitters[slot]); + } + if (slot == NONE || (!emitters[slot].active && sample.strength <= 0.0f)) + continue; + emitter = &emitters[slot]; + if (!emitter->active) + { + emitter->active = TRUE; + emitter->object = iterator.index; + emitter->kind = sample.kind; + emitter->position = sample.position; + emitter->component = component; + emitter->light = emitter->rasterizer = NONE; + emitter->last_time = now; + } + emitter->seen = TRUE; + /* Exponential easing has the same response at 30, 60 and 120 FPS. + Repeated views at the same render time do not advance the fade. */ + blend = 1.0f - (real)exp(-(double)PIN(now - emitter->last_time, 0.0f, 0.25f) / 0.08); + emitter->strength += (sample.strength - emitter->strength) * blend; + emitter->last_time = now; + if (sample.kind == EMITTER_FLAME) + { + /* Particle-only objects have no model pose to interpolate. Smooth + their bounded centroid with the same render-time response. */ + emitter->position.x += (sample.position.x - emitter->position.x) * blend; + emitter->position.y += (sample.position.y - emitter->position.y) * blend; + emitter->position.z += (sample.position.z - emitter->position.z) * blend; + sample.position = emitter->position; + } + emitter->radius = sample.radius; + if (sample.kind == 3 || sample.kind == 4) + { + emitter->position = sample.position; + emitter->direction = sample.direction; + } + if (emitter->strength < 0.002f) + { + if (sample.strength <= 0.0f) + emitter_release(emitter); + continue; + } + color.red = sample.color.red * emitter->strength * sample.view_gain; + color.green = sample.color.green * emitter->strength * sample.view_gain; + color.blue = sample.color.blue * emitter->strength * sample.view_gain; + if (emitter->light == NONE) + { + definition = light_port_glow_definition_get(); + if (definition != NONE) + emitter->light = light_new_unattached(definition, NONE, 0, &sample.position, global_forward3d, 0.0f); + } + if (!light_port_glow_set(emitter->light, NONE, &color, emitter->radius) || + !light_port_glow_move(emitter->light, &sample.position)) + { + emitter_release(emitter); + continue; + } + emitter->connected = TRUE; + } + for (i = 0; i < EMITTER_LIGHTS; i++) + if (emitters[i].active && !emitters[i].seen) + emitter_release(&emitters[i]); +} + +void covenant_emitter_lighting_frame_end(void) +{ + int i; + for (i = 0; i < EMITTER_LIGHTS; i++) + { + struct emitter_light *emitter = &emitters[i]; + if (!emitter->active) + continue; + if (!emitter_kind_enabled(emitter->kind)) + emitter_release(emitter); + else if (emitter->connected && light_port_glow_set(emitter->light, NONE, &emitter_black, 0.0f)) + { + light_disconnect_from_map(emitter->light); + emitter->connected = FALSE; + } + emitter->rasterizer = NONE; + } +} + +void covenant_emitter_lighting_forget(void) +{ + ammo_counter_lighting_forget(); + needler_lighting_forget(); + authored_emitter_lighting_forget(); + ambient_emitter_lighting_forget(); + memset(emitters, 0, sizeof(emitters)); +} + +void covenant_emitter_lighting_window_begin(void) +{ + int i; + for (i = 0; i < EMITTER_LIGHTS; i++) + emitters[i].rasterizer = NONE; +} + +void covenant_emitter_lighting_submitted(long light, long rasterizer) +{ + int i; + for (i = 0; i < EMITTER_LIGHTS; i++) + if (emitters[i].active && emitters[i].light == light && light != NONE) + { + emitters[i].rasterizer = rasterizer; + plasma_occlusion_submit(light, rasterizer); + } +} + +int covenant_emitter_lighting_selected(long rasterizer) +{ + int i; + if (rasterizer == NONE) + return FALSE; + for (i = 0; i < EMITTER_LIGHTS; i++) + if (emitters[i].active && emitters[i].rasterizer == rasterizer && emitter_kind_enabled(emitters[i].kind)) + return TRUE; + return FALSE; +} + +float covenant_emitter_lighting_radius(long light, float radius) +{ + int i; + for (i = 0; i < EMITTER_LIGHTS; i++) + if (emitters[i].active && emitters[i].light == light && light != NONE && emitter_kind_enabled(emitters[i].kind)) + return MAX(radius, emitters[i].radius); + return radius; +} + +long covenant_emitter_lighting_occlusion_ignore(long light) +{ + int i; + /* A luminous shield must not block its own point approximation. Other + scenery and machines still occlude it; bipeds/weapons are not blockers. */ + for (i = 0; i < EMITTER_LIGHTS; i++) + if (emitters[i].active && emitters[i].kind == 2 && emitters[i].light == light && + light != NONE && emitter_kind_enabled(2)) + return emitters[i].object; + return NONE; +} + +int covenant_emitter_lighting_cone(long rasterizer, float axis[3], float origin[3], float *radius) +{ + int i; + if (rasterizer == NONE) + return FALSE; + for (i = 0; i < EMITTER_LIGHTS; i++) + if (emitters[i].active && (emitters[i].kind == 3 || emitters[i].kind == 4) && + emitter_kind_enabled(emitters[i].kind) && emitters[i].rasterizer == rasterizer) + { + axis[0] = emitters[i].direction.i; + axis[1] = emitters[i].direction.j; + axis[2] = emitters[i].direction.k; + origin[0] = emitters[i].position.x; + origin[1] = emitters[i].position.y; + origin[2] = emitters[i].position.z; + *radius = emitters[i].radius; + return emitters[i].kind == 4 ? 2 : 1; + } + return FALSE; +} + +int covenant_emitter_lighting_vehicle_occlusion(long light) +{ + int i; + for (i = 0; i < EMITTER_LIGHTS; i++) + if (emitters[i].active && emitters[i].kind == EMITTER_VEHICLE && + emitters[i].light == light && light != NONE && emitter_kind_enabled(EMITTER_VEHICLE)) + return TRUE; + return FALSE; +} diff --git a/port/linux/game/covenant_emitter_lighting.h b/port/linux/game/covenant_emitter_lighting.h new file mode 100644 index 0000000000..58f5f7f7fb --- /dev/null +++ b/port/linux/game/covenant_emitter_lighting.h @@ -0,0 +1,18 @@ +#ifndef COVENANT_EMITTER_LIGHTING_H +#define COVENANT_EMITTER_LIGHTING_H + +int covenant_emitter_lighting_enabled(void); +void covenant_emitter_lighting_update(void); +void covenant_emitter_lighting_frame_end(void); +void covenant_emitter_lighting_forget(void); +void covenant_emitter_lighting_window_begin(void); +void covenant_emitter_lighting_submitted(long light, long rasterizer); +int covenant_emitter_lighting_selected(long rasterizer); +int covenant_emitter_lighting_vehicle_occlusion(long light); +long covenant_emitter_lighting_occlusion_ignore(long light); +float covenant_emitter_lighting_radius(long light, float radius); + +/* Returns 0 for no mask, 1 for the AR screen, 2 for exposed needles. */ +int covenant_emitter_lighting_cone(long rasterizer, float axis[3], float origin[3], float *radius); + +#endif diff --git a/port/linux/game/covenant_lighting.c b/port/linux/game/covenant_lighting.c new file mode 100644 index 0000000000..1adfc7c65b --- /dev/null +++ b/port/linux/game/covenant_lighting.c @@ -0,0 +1,264 @@ +/* Additional Covenant projectile policy and bounded missing-light fallbacks. + Authored attachments take precedence; effects and simulation stay stock. */ +#include "cseries.h" +#include "objects/objects.h" +#include "objects/object_definitions.h" +#include "objects/object_lights.h" +#include "tag_files/tag_files.h" +#include "camera/observer.h" +#include "game/players.h" +#include "covenant_lighting.h" +#include "plasma_occlusion.h" +#include + +#include "lighting_config.h" +long light_port_glow_definition_get(void); +boolean light_port_glow_set(long light_index, long object_index, real_rgb_color const *color, real radius); + +enum { COVENANT_LIGHTS = 8 }; +static struct covenant_light +{ + int active, connected, profile; + long object_index, light_index, rasterizer_index; +} covenant_lights[COVENANT_LIGHTS]; +static const struct covenant_profile +{ + const char *tag; + real scale, radius; /* radius zero: use authored lights only */ + real_rgb_color color; +} covenant_profiles[] = { + {"weapons\\needler\\needle", 1.5f, 1.0f, {0.85f, 0.2f, 1.0f}}, + {"weapons\\needler\\mp_needle", 1.5f, 1.0f, {0.85f, 0.2f, 1.0f}}, + {"vehicles\\ghost\\ghost bolt", 1.75f, 0.0f, {0.0f, 0.0f, 0.0f}}, + {"vehicles\\banshee\\banshee bolt", 1.75f, 0.0f, {0.0f, 0.0f, 0.0f}}, + {"vehicles\\banshee\\banshee fuel rod", 2.75f, 0.0f, {0.0f, 0.0f, 0.0f}}, + {"vehicles\\banshee\\mp_banshee fuel rod", 2.75f, 0.0f, {0.0f, 0.0f, 0.0f}}, + {"vehicles\\c gun turret\\c gun turret", 2.5f, 0.0f, {0.0f, 0.0f, 0.0f}}, + {"vehicles\\c gun turret\\mp gun turret", 2.0f, 0.0f, {0.0f, 0.0f, 0.0f}}, + {"weapons\\fuel rod gun\\fuel rod", 2.75f, 0.0f, {0.0f, 0.0f, 0.0f}}, + {"weapons\\plasma_cannon\\plasma_cannon", 2.75f, 0.0f, {0.0f, 0.0f, 0.0f}}, + {"vehicles\\wraith\\wraith mortar", 1.75f, 3.5f, {0.25f, 0.35f, 1.0f}}, +}; + +static int covenant_profile_index(const char *name) +{ + int i; + if (name) + for (i = 0; i < NUMBEROF(covenant_profiles); i++) + if (!strcmp(name, covenant_profiles[i].tag)) + return i; + return NONE; +} + +float covenant_lighting_scale(const char *name) +{ + int profile = covenant_profile_index(name); + return profile == NONE ? 0.0f : covenant_profiles[profile].scale; +} + +static const real_rgb_color covenant_black = {0.0f, 0.0f, 0.0f}; +static long covenant_fuel_exhaust = NONE - 1; + +/* Tint only the submitted copy of the shared Grunt/Hunter flight light. + Keep its green channel and authored modulation; reducing red and blue + removes the pale cast without brightening or recolouring stock effects. */ +void covenant_lighting_color(long object_index, long definition_index, real_rgb_color *color) +{ + struct object_datum *object; + const char *name; + if (!lighting_config_boolean("display.plasma_lighting")) + return; + object = object_try_and_get(object_index); + if (!object || object->object.type != _object_type_projectile) + return; + name = tag_get_name(object->definition_index); + if (!name || strcmp(name, "weapons\\fuel rod gun\\fuel rod")) + return; + if (covenant_fuel_exhaust == NONE - 1) + covenant_fuel_exhaust = tag_loaded('ligh', "weapons\\fuel rod gun\\fuel rod exhaust"); + if (covenant_fuel_exhaust == NONE || definition_index != covenant_fuel_exhaust) + return; + color->red *= 0.30f; + color->blue *= 0.20f; +} + +/* Return the validated profile so admission need not resolve the tag again. */ +static int covenant_visible_profile(long object_index) +{ + struct object_datum *object = object_try_and_get(object_index); + struct object_definition *definition; + const char *name; + short player; + int i, profile; + if (!object || object->object.type != _object_type_projectile || + object->object.node_matrices.size < sizeof(real_matrix4x3)) + return NONE; + name = tag_get_name(object->definition_index); + profile = covenant_profile_index(name); + if (profile == NONE || covenant_profiles[profile].radius <= 0.0f) + return NONE; + definition = object_definition_get(object->definition_index); + /* Model-less projectiles (the stock Wraith mortar) remain invisible in + object_set_visibility even while their particle attachments are visible. */ + if (TEST_FLAG(object->object.flags, _object_invisible_bit) && definition->object.model.index != NONE) + return NONE; + /* A custom map's authored attachment takes precedence over a new glow. */ + for (i = 0; i < definition->object.attachments.count && i < MAXIMUM_NUMBER_OF_ATTACHMENTS_PER_OBJECT; i++) + { + struct object_attachment_definition *attachment = + TAG_BLOCK_GET_ELEMENT(&definition->object.attachments, i, struct object_attachment_definition); + if (attachment->type.group_tag == 'ligh' && attachment->type.index != NONE) + return NONE; + } + for (player = local_player_get_next(NONE); player != NONE; player = local_player_get_next(player)) + { + const struct observer_result *camera = observer_get_camera(player); + if (camera && distance3d(&object->object.bounding_sphere_center, &camera->position) <= 25.0f) + return profile; + } + return NONE; +} + +static void covenant_release(struct covenant_light *light) +{ + /* The salted handle, owner and glow definition must still match. */ + if (light->active && light_port_glow_set(light->light_index, light->object_index, &covenant_black, 0.0f)) + light_delete(light->light_index); + memset(light, 0, sizeof(*light)); +} + +void covenant_lighting_update(void) +{ + struct object_iterator iterator; + int i, slot, profile; + int enabled = lighting_config_boolean("display.plasma_lighting"); + for (i = 0; i < COVENANT_LIGHTS; i++) + if (covenant_lights[i].active && (!enabled || covenant_visible_profile(covenant_lights[i].object_index) == NONE)) + covenant_release(&covenant_lights[i]); + if (!enabled) + return; + object_iterator_new(&iterator, _object_mask_projectile, 0); + while (object_iterator_next(&iterator)) + { + struct covenant_light *light; + long definition; + profile = covenant_visible_profile(iterator.index); + if (profile == NONE) + continue; + slot = NONE; + for (i = 0; i < COVENANT_LIGHTS; i++) + { + if (covenant_lights[i].active && covenant_lights[i].object_index == iterator.index) + { + slot = i; + break; + } + if (!covenant_lights[i].active && slot == NONE) + slot = i; + } + if (slot == NONE) + continue; + light = &covenant_lights[slot]; + light->profile = profile; + if (light->active && light_port_glow_set(light->light_index, iterator.index, &covenant_profiles[light->profile].color, covenant_profiles[light->profile].radius)) + { + if (!light->connected) + light_reconnect_to_map(light->light_index); + light->connected = TRUE; + continue; + } + memset(light, 0, sizeof(*light)); + light->profile = profile; + definition = light_port_glow_definition_get(); + if (definition == NONE) + continue; + light->light_index = light_new_unattached(definition, iterator.index, 0, + (real_point3d const *)global_zero_vector3d, global_forward3d, 0.0f); + if (light->light_index == NONE) + continue; + light->object_index = iterator.index; + light->rasterizer_index = NONE; + light->active = light->connected = TRUE; + light_port_glow_set(light->light_index, iterator.index, &covenant_profiles[light->profile].color, covenant_profiles[light->profile].radius); + } +} + +void covenant_lighting_frame_end(void) +{ + int i; + for (i = 0; i < COVENANT_LIGHTS; i++) + { + struct covenant_light *light = &covenant_lights[i]; + if (!light->active) + continue; + if (!lighting_config_boolean("display.plasma_lighting")) + covenant_release(light); + else if (light_port_glow_set(light->light_index, light->object_index, &covenant_black, 0.0f) && light->connected) + { + light_disconnect_from_map(light->light_index); + light->connected = FALSE; + } + light->rasterizer_index = NONE; + } +} + +void covenant_lighting_forget(void) +{ + /* Called only as the engine discards its entire light array/partition. */ + memset(covenant_lights, 0, sizeof(covenant_lights)); + covenant_fuel_exhaust = NONE - 1; +} + +void covenant_lighting_window_begin(void) +{ + int i; + for (i = 0; i < COVENANT_LIGHTS; i++) + covenant_lights[i].rasterizer_index = NONE; +} + +void covenant_lighting_submitted(long light_index, long rasterizer_index) +{ + int i; + for (i = 0; i < COVENANT_LIGHTS; i++) + if (covenant_lights[i].active && covenant_lights[i].light_index == light_index) + { + covenant_lights[i].rasterizer_index = rasterizer_index; + plasma_occlusion_submit(light_index, rasterizer_index); + return; + } +} + +int covenant_lighting_selected(long rasterizer_index) +{ + int i; + if (rasterizer_index == NONE || !lighting_config_boolean("display.plasma_lighting")) + return FALSE; + for (i = 0; i < COVENANT_LIGHTS; i++) + if (covenant_lights[i].active && covenant_lights[i].rasterizer_index == rasterizer_index) + return TRUE; + return FALSE; +} + +/* Visibility bounds must cover the owned flight glow, even when the map's + borrowed template describes a smaller muzzle flash. */ +float covenant_lighting_radius(long light_index, long object_index, float radius) +{ + int i; + if (!lighting_config_boolean("display.plasma_lighting")) + return radius; + for (i = 0; i < COVENANT_LIGHTS; i++) + if (covenant_lights[i].active && covenant_lights[i].light_index == light_index && + covenant_lights[i].object_index == object_index) + return MAX(radius, covenant_profiles[covenant_lights[i].profile].radius); + return radius; +} + +int covenant_lighting_owns(long light_index, long object_index) +{ + int i; + for (i = 0; i < COVENANT_LIGHTS; i++) + if (covenant_lights[i].active && covenant_lights[i].light_index == light_index && + covenant_lights[i].object_index == object_index) + return TRUE; + return FALSE; +} diff --git a/port/linux/game/covenant_lighting.h b/port/linux/game/covenant_lighting.h new file mode 100644 index 0000000000..f7d58dc788 --- /dev/null +++ b/port/linux/game/covenant_lighting.h @@ -0,0 +1,18 @@ +#ifndef COVENANT_LIGHTING_H +#define COVENANT_LIGHTING_H + +void covenant_lighting_update(void); +void covenant_lighting_forget(void); +void covenant_lighting_frame_end(void); +void covenant_lighting_window_begin(void); +void covenant_lighting_submitted(long light_index, long rasterizer_index); +int covenant_lighting_selected(long rasterizer_index); + +float covenant_lighting_radius(long light_index, long object_index, float radius); + +float covenant_lighting_scale(const char *name); +void covenant_lighting_color(long object_index, long definition_index, real_rgb_color *color); + +int covenant_lighting_owns(long light_index, long object_index); + +#endif diff --git a/port/linux/game/custom_edition_cache.c b/port/linux/game/custom_edition_cache.c index 7ac39c5da6..ee83cee2a3 100644 --- a/port/linux/game/custom_edition_cache.c +++ b/port/linux/game/custom_edition_cache.c @@ -29,6 +29,8 @@ where its offset falls in their combined offset space. #include "scenario/scenario_definitions.h" #include "cache_file_formats.h" #include "custom_edition_cache.h" +#include "custom_edition_errors.h" +#include "interface/ui_widget.h" #include "tag_schema.h" #include "map_share.h" @@ -96,6 +98,10 @@ struct custom_edition_cache_globals /* ---------- globals */ static struct custom_edition_cache_globals custom_edition_cache_globals; +/* Only an actual tag load writes this record. Admission/catalog probes use +their caller's buffer. No pointers into the failed map survive cleanup. */ +static char custom_edition_failure_name[64]; +static char custom_edition_failure_reason[320]; /* ---------- private code */ @@ -688,7 +694,7 @@ static boolean custom_edition_cache_tags_convert( "custom edition: %ld tags had their group (scrambled by map protection) taken from the references to them", regrouped); } - + custom_edition_cache_combine_resource_offsets( tag_cache, loaded_bytes, @@ -705,6 +711,8 @@ static boolean custom_edition_cache_tags_convert( "custom edition: cannot convert '%s': %s", custom_edition_cache_tag_name(tag_cache, loaded_bytes, conversion.problem_tag_index), cache_file_status_describe(status)); + snprintf(custom_edition_failure_reason, sizeof(custom_edition_failure_reason), "%s", + custom_edition_status_explanation(status)); return FALSE; } error( @@ -748,7 +756,7 @@ static boolean custom_edition_cache_tags_convert( { error( _error_silent, - "custom edition: %ld HUD elements drawn from Halo PC's double resolution bitmaps were given half their scale", + "custom edition: %ld HUD elements rescaled using Halo PC's placement and bitmap flags", (long)conversion.hud_placements_rescaled); } if (conversion.score_hint_converted) @@ -764,11 +772,28 @@ static boolean custom_edition_cache_tags_convert( conversion.pause_menu_trimmed ? "; the multiplayer pause menu is the Xbox's resume and quit" : ""); } - return custom_edition_cache_tags_validate(tag_cache, report) && - custom_edition_bitmaps_verify(tag_cache, loaded_bytes) && - custom_edition_reordered_bitmaps_find(tag_cache, loaded_bytes, custom_edition_cache_globals.behaviours) && - custom_edition_scripts_convert(tag_cache, loaded_bytes) && - custom_edition_cache_models_convert(tag_cache, report); + if (!custom_edition_cache_tags_validate(tag_cache, report)) + { + strcpy(custom_edition_failure_reason, "Its converted map data failed validation. See debug.txt for the failing check."); + return FALSE; + } + if (!custom_edition_bitmaps_verify(tag_cache, loaded_bytes) || + !custom_edition_reordered_bitmaps_find(tag_cache, loaded_bytes, custom_edition_cache_globals.behaviours)) + { + strcpy(custom_edition_failure_reason, "Its textures could not be prepared. See debug.txt for the failing texture check."); + return FALSE; + } + if (!custom_edition_scripts_convert(tag_cache, loaded_bytes)) + { + strcpy(custom_edition_failure_reason, "Its scripts could not be prepared. Check for an updated map; debug.txt has the failing check."); + return FALSE; + } + if (!custom_edition_cache_models_convert(tag_cache, report)) + { + strcpy(custom_edition_failure_reason, "Its models could not be prepared. See debug.txt for the failing geometry or memory check."); + return FALSE; + } + return TRUE; } /* Whether Custom Edition maps may run (game.custom_edition) and the map @@ -1039,8 +1064,7 @@ boolean custom_edition_cache_present( { error(_error_silent, "custom edition: the map '%s' cannot be played: %s", level_name, custom_edition_unavailable_reason()); - snprintf(message, message_size, "The map %.64s can't be played: Custom Edition maps can't run (see debug.txt).", - name); + custom_edition_error_message(name, custom_edition_unavailable_reason(), message, message_size); return FALSE; } if (custom_edition_file_open(&file, path)) @@ -1060,7 +1084,8 @@ boolean custom_edition_cache_present( error(_error_silent, "custom edition: '%s' cannot be played: %s", path, status != _cache_file_status_ok ? cache_file_status_describe(status) : "it is not a Halo Custom Edition cache"); - snprintf(message, message_size, "Your %.64s.map can't be played (debug.txt says why).", name); + custom_edition_error_message(name, status != _cache_file_status_ok ? custom_edition_status_explanation(status) : + "It is not a Halo Custom Edition map. Install a Custom Edition version in custom_maps.", message, message_size); return FALSE; } for (type = _resource_map_bitmaps; type < NUMBER_OF_RESOURCE_MAP_TYPES; type++) @@ -1096,6 +1121,39 @@ boolean custom_edition_cache_playable( return custom_edition_level_name(level_name) && custom_edition_cache_identify(level_name, &identity); } +/* Consumed only by the existing fatal load path, after its cleanup. */ +char const *custom_edition_cache_load_error(char const *level_name) +{ + static char message[512]; + char const *name; + char const *reason = "Its level could not be prepared. See debug.txt for the failing setup check."; + if (!custom_edition_level_name(level_name)) return "game_load() failed."; + name = tag_name_strip_path(level_name); + if (!csstrcasecmp(name, custom_edition_failure_name) && custom_edition_failure_reason[0]) + reason = custom_edition_failure_reason; + custom_edition_error_message(name, reason, message, sizeof(message)); + custom_edition_failure_name[0] = 0; + custom_edition_failure_reason[0] = 0; + return message; +} + +/* A precache refusal still uses the fatal media screen. Only its text changes. */ +boolean custom_edition_cache_display_error(char const *level_name) +{ + char message[512]; + wchar_t text[512]; + size_t i; + if (!custom_edition_level_name(level_name)) return FALSE; + if (custom_edition_cache_present(level_name, 0, message, sizeof(message))) + custom_edition_error_message(tag_name_strip_path(level_name), + "Its file could not be read during loading. Check that the complete map is accessible.", message, sizeof(message)); + for (i = 0; message[i] && i < NUMBEROF(text) - 1; i++) text[i] = (unsigned char)message[i]; + text[i] = 0; + error(_error_silent, "%s", message); + display_error_damaged_media_text(text); + return TRUE; +} + boolean custom_edition_cache_campaign( char const *map_name) { @@ -1127,14 +1185,18 @@ struct cache_file_tag_header *custom_edition_cache_tags_load( short type; assert(!globals->tags_loaded); + snprintf(custom_edition_failure_name, sizeof(custom_edition_failure_name), "%s", tag_name_strip_path(map_name)); + custom_edition_failure_reason[0] = 0; if (!tag_cache) { + snprintf(custom_edition_failure_reason, sizeof(custom_edition_failure_reason), "%s", custom_edition_unavailable_reason()); error(_error_silent, "custom edition: cannot load the map '%s': %s", map_name, custom_edition_unavailable_reason()); return NULL; } if (!custom_edition_map_path(map_name, path) || !custom_edition_file_open(&globals->map, path)) { + strcpy(custom_edition_failure_reason, "Its .map file is missing or unreadable. Check the complete map in custom_maps."); error(_error_silent, "custom edition: cannot open the map '%s' (it is looked for in the custom_maps folder)", map_name); return NULL; @@ -1147,6 +1209,9 @@ struct cache_file_tag_header *custom_edition_cache_tags_load( !globals->map.source.read(globals->map.source.context, 0, CACHE_FILE_HEADER_BYTES, header)) { error(_error_silent, "custom edition: '%s' is not a loadable cache (%s)", path, cache_file_status_describe(status)); + snprintf(custom_edition_failure_reason, sizeof(custom_edition_failure_reason), "%s", + status != _cache_file_status_ok ? custom_edition_status_explanation(status) : + "Its format or size is unsupported, or its header could not be read. See debug.txt for details."); custom_edition_cache_files_close(); return NULL; } @@ -1188,6 +1253,7 @@ struct cache_file_tag_header *custom_edition_cache_tags_load( globals->resource_files[_resource_map_sounds].source.size > COMBINED_OFFSET_LIMIT - COMBINED_SOUNDS_OFFSET)) { error(_error_silent, "custom edition: a resource map is too large for this loader"); + strcpy(custom_edition_failure_reason, "A resource file is larger than the Custom Edition loader supports."); custom_edition_cache_files_close(); return NULL; } @@ -1207,6 +1273,8 @@ struct cache_file_tag_header *custom_edition_cache_tags_load( cache_file_status_describe(status), (long)report.problem_tag_index, (unsigned long)report.problem_location); + snprintf(custom_edition_failure_reason, sizeof(custom_edition_failure_reason), "%s", + custom_edition_status_explanation(status)); custom_edition_cache_files_close(); return NULL; } @@ -1225,6 +1293,8 @@ struct cache_file_tag_header *custom_edition_cache_tags_load( globals->tag_cache_bytes = report.tag_cache_bytes; globals->file_length = report.identity.file_length; globals->tags_loaded = TRUE; + custom_edition_failure_name[0] = 0; + custom_edition_failure_reason[0] = 0; return (struct cache_file_tag_header *)tag_cache; } @@ -1265,6 +1335,17 @@ boolean custom_edition_structure_bsp_reference_valid( return TRUE; } +boolean custom_edition_cache_contains(void const *pointer, unsigned long bytes) +{ + struct custom_edition_cache_globals *globals = &custom_edition_cache_globals; + unsigned long base = (unsigned long)globals->tag_cache; + unsigned long address = (unsigned long)pointer; + + return globals->tags_loaded && address >= base && + address - base <= globals->loaded_bytes && + bytes <= globals->loaded_bytes - (address - base); +} + boolean custom_edition_cache_tags_loaded( void) { diff --git a/port/linux/game/custom_edition_cache.h b/port/linux/game/custom_edition_cache.h index e7dbf435af..970e4670c5 100644 --- a/port/linux/game/custom_edition_cache.h +++ b/port/linux/game/custom_edition_cache.h @@ -51,6 +51,11 @@ struct structure_bsp; /* ---------- prototypes/CUSTOM_EDITION_CACHE.C */ +/* Only bytes owned by the currently loaded CE tag cache. */ +boolean custom_edition_cache_contains(void const *pointer, unsigned long bytes); + +/* A bounded raw DXT layout that needs no Xbox swizzle or mip reordering. */ + /* Whether a tag of the Custom Edition map loaded is one of Halo PC's own, as it shipped: read from bitmaps.map, sounds.map or loc.map. FALSE when no Custom Edition map is loaded. */ @@ -80,6 +85,9 @@ boolean custom_edition_level_name( it is then read in place, never copied to the cache partition. */ boolean custom_edition_cache_playable( char const *level_name); +/* Existing fatal paths only: no recovery or validation policy changes. */ +boolean custom_edition_cache_display_error(char const *level_name); +char const *custom_edition_cache_load_error(char const *level_name); /* Whether the map `map_name` (a level name or a file name) has a file in the Custom Edition maps folders, whatever it holds. */ boolean custom_edition_map_file_present( diff --git a/port/linux/game/custom_edition_errors.c b/port/linux/game/custom_edition_errors.c new file mode 100644 index 0000000000..f5637c1041 --- /dev/null +++ b/port/linux/game/custom_edition_errors.c @@ -0,0 +1,49 @@ +#include "custom_edition_errors.h" +#include + +char const *custom_edition_status_explanation(enum cache_file_status status) +{ + switch (status) { + case _cache_file_status_ok: return ""; + case _cache_file_status_opensauce_cache: + return "It requires OpenSauce features that GulchCE does not support."; + case _cache_file_status_out_of_memory: + return "There is not enough memory to load it. Close other applications and try again."; + case _cache_file_status_tag_cache_overflow: + return "Its map data exceeds the Custom Edition tag-cache limit. It needs a version built within that limit."; + case _cache_file_status_file_too_large: + return "Its file is larger than the Custom Edition loader supports."; + case _cache_file_status_read_failed: + return "Its data could not be read. Check that the complete map and its resources are accessible."; + case _cache_file_status_unsupported_version: + return "It is not a supported Halo Custom Edition map. Install a Custom Edition version in custom_maps."; + case _cache_file_status_compressed_cache: + return "This compressed map format is not supported. Install an uncompressed Custom Edition version."; + case _cache_file_status_missing_resource_map: + return "A required Custom Edition resource is missing or unusable. Check bitmaps.map, sounds.map and loc.map in custom_maps."; + case _cache_file_status_missing_resource_item: + return "Its resource files do not contain the data it needs. Install the matching Custom Edition resources."; + case _cache_file_status_wrong_resource_map_type: + case _cache_file_status_bad_resource_map_header: + case _cache_file_status_bad_resource_item: + case _cache_file_status_bad_resource_layout: + case _cache_file_status_bad_resource_data_range: + return "A required resource file is invalid or incompatible. Reinstall the matching Custom Edition resources."; + case _cache_file_status_file_too_small: + case _cache_file_status_bad_file_length: + return "Its file is incomplete or has an invalid length. Reinstall the complete map."; + default: + return "Its map data is invalid or unsupported. Check for an updated map; debug.txt has the failing check."; + } +} + +void custom_edition_error_message(char const *map, char const *reason, char *out, size_t size) +{ + size_t i; + if (!out || !size) return; + snprintf(out, size, "Custom Edition map %.63s could not load. %.320s", + map ? map : "(unknown)", reason ? reason : "See debug.txt for details."); + /* Map and tag names are untrusted display text, never formatting or UI controls. */ + for (i = 0; out[i]; i++) + if ((unsigned char)out[i] < 32 || (unsigned char)out[i] >= 127) out[i] = '?'; +} diff --git a/port/linux/game/custom_edition_errors.h b/port/linux/game/custom_edition_errors.h new file mode 100644 index 0000000000..0d955c4690 --- /dev/null +++ b/port/linux/game/custom_edition_errors.h @@ -0,0 +1,10 @@ +/* Player-facing explanations for the existing Custom Edition loader. */ +#ifndef CUSTOM_EDITION_ERRORS_H +#define CUSTOM_EDITION_ERRORS_H + +#include "cache_file_formats.h" + +char const *custom_edition_status_explanation(enum cache_file_status status); +void custom_edition_error_message(char const *map, char const *reason, char *out, size_t size); + +#endif diff --git a/port/linux/game/custom_edition_hud_draw.c b/port/linux/game/custom_edition_hud_draw.c new file mode 100644 index 0000000000..3d61d31a74 --- /dev/null +++ b/port/linux/game/custom_edition_hud_draw.c @@ -0,0 +1,68 @@ +/* CE draws without a converted placement. Adapted from ChupathingyCE + * #352, by Boom Pen / ugoboom, and #545, by Milenko (GPL-3.0-or-later). See + * docs/custom_edition_caches.md for provenance and the map-family boundary. + */ +#include "cseries.h" +#include "bitmaps/bitmap_group.h" +#include "cache_file_formats.h" +#include "custom_edition_cache.h" +#include "custom_edition_hud_scale.h" +#include "custom_edition_hud_draw.h" + +enum { _bitmap_linear_bit = 4 }; + +real custom_edition_hud_bitmap_scale(long bitmap_group_index) +{ + if (!custom_edition_cache_tags_loaded() || bitmap_group_index == NONE) + return 1.0f; + return custom_edition_hud_scale(bitmap_group_get(bitmap_group_index)->flags, FALSE); +} + +real custom_edition_hud_number_scale(long bitmap_group_index, unsigned short placement_flags) +{ + boolean high_resolution; + + if (!custom_edition_cache_tags_loaded() || bitmap_group_index == NONE) + return 1.0f; + /* The known-map number fix already halves the digit metrics and sets + the bitmap's half-scale flag. Its placement must not halve them again. */ + high_resolution = (placement_flags & 4) && + !custom_edition_cache_relies_on(_custom_edition_behaviour_hud_number_scale); + return custom_edition_hud_scale(bitmap_group_get(bitmap_group_index)->flags, high_resolution); +} + +/* Borrowed only across interface_draw_screen's synchronous screen-effect +draw. End the scope before another view, cinematic or map can draw. */ +static struct bitmap_data const *hud_mask; +static real hud_mask_scale = 1.0f; + +void custom_edition_hud_mask_begin(struct bitmap_data const *bitmap) +{ + hud_mask = custom_edition_cache_tags_loaded() ? bitmap : NULL; + hud_mask_scale = hud_mask ? custom_edition_hud_bitmap_scale(hud_mask->tag_index) : 1.0f; +} + +void custom_edition_hud_mask_end(void) +{ + hud_mask = NULL; + hud_mask_scale = 1.0f; +} + +void custom_edition_hud_mask_transform(struct bitmap_data const *bitmap, + real_vector2d *size, real_vector2d *scale) +{ + if (!custom_edition_cache_tags_loaded() || !bitmap || bitmap != hud_mask || hud_mask_scale == 1.0f) + return; + size->i *= hud_mask_scale; + size->j *= hud_mask_scale; + if (TEST_FLAG(bitmap->flags, _bitmap_linear_bit)) + { + scale->i = 1.0f / hud_mask_scale; + scale->j = 1.0f / hud_mask_scale; + } + else + { + scale->i = 1.0f / size->i; + scale->j = 1.0f / size->j; + } +} diff --git a/port/linux/game/custom_edition_hud_draw.h b/port/linux/game/custom_edition_hud_draw.h new file mode 100644 index 0000000000..b62353e5bc --- /dev/null +++ b/port/linux/game/custom_edition_hud_draw.h @@ -0,0 +1,15 @@ +#ifndef CUSTOM_EDITION_HUD_DRAW_H +#define CUSTOM_EDITION_HUD_DRAW_H + +#include "math/real_math.h" + +struct bitmap_data; + +real custom_edition_hud_bitmap_scale(long bitmap_group_index); +real custom_edition_hud_number_scale(long bitmap_group_index, unsigned short placement_flags); +void custom_edition_hud_mask_begin(struct bitmap_data const *bitmap); +void custom_edition_hud_mask_end(void); +void custom_edition_hud_mask_transform(struct bitmap_data const *bitmap, + real_vector2d *size, real_vector2d *scale); + +#endif diff --git a/port/linux/game/custom_edition_hud_scale.h b/port/linux/game/custom_edition_hud_scale.h new file mode 100644 index 0000000000..bf220b340b --- /dev/null +++ b/port/linux/game/custom_edition_hud_scale.h @@ -0,0 +1,21 @@ +/* SPDX-License-Identifier: GPL-3.0-only + * HUD flag composition adapted from SnowyMouse/Chimera's + * src/chimera/fix/hud_bitmap_scale.cpp, check_half_scale_bitmap_flag. + * ChupathingyCE #352 (Boom Pen / ugoboom) applies these rules to the + * decompilation. Kept here for CE conversion and CE drawing only. + */ +#ifndef CUSTOM_EDITION_HUD_SCALE_H +#define CUSTOM_EDITION_HUD_SCALE_H + +static float custom_edition_hud_scale(unsigned short bitmap_flags, int high_resolution) +{ + float scale = (high_resolution || (bitmap_flags & 0x80)) ? 0.5f : 1.0f; + + /* The bitmap's half-scale flag compounds with the high-resolution + choice; forcing that choice does not apply it twice. */ + if (bitmap_flags & 0x10) + scale *= 0.5f; + return scale; +} + +#endif diff --git a/port/linux/game/dualsense_game.c b/port/linux/game/dualsense_game.c new file mode 100644 index 0000000000..cee67be3e6 --- /dev/null +++ b/port/linux/game/dualsense_game.c @@ -0,0 +1,329 @@ +/* +DUALSENSE_GAME.C + +Each local player's DualSense wish (dualsense_game.h), for a controller port whose pad is a DualSense the platform side +can drive (port/linux/src/dualsense.c): +- the lightbar in the player's colour (the team's in a team game, the armour's otherwise; a campaign's Chief green), + and the player lights the split-screen number; +- the physical trigger mapped to fire by the weapon in hand: its profile (dualsense_rules.c) from the tag's own numbers, and the weapon's state each + frame; each new round (the weapon's last-fired game time moved) is a shot the platform side turns into a kick. In a + vehicle, a gunner's seat takes the vehicle's weapon; any other seat has none; +- the grenade/zoom trigger a light resistance while zoomed, or a hair trigger while there are grenades to throw. +Only L2 and R2 have actuators. Other mapped actions leave them free; non-playing contexts release both. +*/ + +#include + +#include "cseries.h" +#include "real_math.h" +#include "tag_files/tag_groups.h" +#include "game/game.h" +#include "game/game_engine.h" +#include "game/players.h" +#include "camera/director.h" +#include "controller_remap.h" +#include "controller_buttons.h" +#include "items/weapon_definitions.h" +#include "items/weapons.h" +#include "items/weapon_datum_flags.h" +#include "objects/objects.h" +#include "units/units.h" +#include "units/unit_definitions.h" +#include "../src/dualsense.h" +#include "dualsense_game.h" + +static unsigned char channel(real value) +{ + if (value <= 0.0f) + return 0; + if (value >= 1.0f) + return 255; + return (unsigned char)(value * 255.0f + 0.5f); +} + +/* a round in this many ticks counts as firing (the slowest automatic, 6 rounds a second, fires every 5) */ +#define FIRING_TICKS 5 + +/* Game-thread history is separate from checkpoint data. Context changes discard old shots. */ +static struct +{ + int valid; + long player_index, unit_index, weapon_index, last_fired; + unsigned int instance; + unsigned long context, kicks; + int percent; + unsigned char layout[CONTROLLER_REMAP_ACTIONS]; + float last_charge; + unsigned char kick[DUALSENSE_EFFECT_SIZE]; + int kick_ms; +} rounds[MAXIMUM_LOCAL_PLAYERS]; +static unsigned long next_context; +static int tracking; + +static void clear_round(short port) +{ + memset(&rounds[port], 0, sizeof(rounds[port])); + rounds[port].context = ++next_context; +} + +void dualsense_game_reset(void) +{ + short port; + + for (port = 0; port < MAXIMUM_LOCAL_PLAYERS; port++) + clear_round(port); + dualsense_clear(); + tracking = 0; +} + +/* a weapon definition's kind from its tag's numbers (and its first trigger, NULL: none) */ +static enum dualsense_weapon_kind definition_kind(long definition_index, float *rate_of_fire, + struct weapon_trigger_definition **first_trigger) +{ + struct weapon_definition *definition = weapon_definition_get(definition_index); + struct weapon_trigger_definition *first = NULL; + float rate = 0.0f, charging = 0.0f; + int projectiles = 0; + long trigger; + + for (trigger = 0; trigger < definition->weapon.triggers.count; trigger++) + { + struct weapon_trigger_definition *trigger_definition = + TAG_BLOCK_GET_ELEMENT(&definition->weapon.triggers, trigger, struct weapon_trigger_definition); + + if (trigger == 0) + { + first = trigger_definition; + rate = trigger_definition->initial_rate_of_fire > trigger_definition->final_rate_of_fire ? + trigger_definition->initial_rate_of_fire : trigger_definition->final_rate_of_fire; + } + if (trigger_definition->charging_time > charging) + charging = trigger_definition->charging_time; + if (trigger_definition->projectile.index != NONE) + projectiles++; + } + *rate_of_fire = rate; + if (first_trigger) + *first_trigger = first; + return dualsense_weapon_kind(definition->weapon.weapon_type == _weapon_type_needler, rate, charging, + first ? first->heat_generated_per_round : 0.0f, definition->weapon.zoom_level_count, projectiles == 0, + definition->weapon.weapon_type == _weapon_type_plasma_rifle); +} + +/* the weapon in hand now: its kind from the tag's numbers, its heat, charge, firing and magazine */ +static void weapon_state(long weapon_index, struct dualsense_weapon_state *state) +{ + struct weapon_datum *weapon; + struct weapon_definition *definition; + struct weapon_trigger_definition *first = NULL; + float rate = 0.0f; + long trigger; + long now = game_time_get(); + + memset(state, 0, sizeof(*state)); + if (weapon_index == NONE) + return; + weapon = weapon_get(weapon_index); + definition = weapon_definition_get(weapon->definition_index); + state->kind = definition_kind(weapon->definition_index, &rate, &first); + state->rate_of_fire = rate; + /* (the charge: a trigger charging counts its timer down from charging_time) */ + for (trigger = 0; trigger < definition->weapon.triggers.count && trigger < 2; trigger++) + { + struct weapon_trigger_definition *trigger_definition = + TAG_BLOCK_GET_ELEMENT(&definition->weapon.triggers, trigger, struct weapon_trigger_definition); + + if (weapon->weapon.triggers[trigger].state == _trigger_charged) + state->charge = 1.0f; + else if (weapon->weapon.triggers[trigger].state == _trigger_charging && trigger_definition->charging_time > 0.0f && + state->charge < 1.0f) + { + float left = (float)weapon->weapon.triggers[trigger].state_timer / + (trigger_definition->charging_time * (float)TICKS_PER_SECOND); + float charge = 1.0f - (left < 0.0f ? 0.0f : left > 1.0f ? 1.0f : left); + + if (charge > state->charge) + state->charge = charge; + } + } + state->heat = weapon->weapon.heat; + /* (the game's own overheated flag, which weapons.c clears as the heat falls under the recovery threshold) */ + state->overheated = TEST_FLAG(weapon->weapon.flags, _weapon_overheated_bit) && weapon->weapon.heat > 0.0f ? 1 : 0; + state->firing = weapon->weapon.game_time_last_fired > 0 && now - weapon->weapon.game_time_last_fired <= FIRING_TICKS; + /* (switching weapons: the readying and putting-away states, or the player asked to switch) */ + state->readying = weapon->weapon.state == _weapon_state_ready || weapon->weapon.state == _weapon_state_put_away || + TEST_FLAG(weapon->weapon.control_flags, _weapon_control_user_switching_weapons_bit); + state->reloading = weapon->weapon.state == _weapon_state_primary_reload || + weapon->weapon.state == _weapon_state_secondary_reload; + /* (empty: a battery spent, as weapon_useful reads it, or a magazine that holds rounds with none loaded) */ + state->empty = weapon->weapon.age >= 1.0f; + if (first && first->magazine_index >= 0 && first->magazine_index < 2 && + first->magazine_index < definition->weapon.magazines.count) + { + struct weapon_magazine const *magazine = &weapon->weapon.magazines[first->magazine_index]; + struct weapon_magazine_definition const *magazine_definition = TAG_BLOCK_GET_ELEMENT( + &definition->weapon.magazines, first->magazine_index, struct weapon_magazine_definition); + + if (magazine_definition->rounds_loaded_maximum > 0) + { + if (magazine->state == _magazine_reloading) + state->reloading = 1; + if (magazine->rounds_loaded <= 0) + state->empty = 1; + } + } +} + +/* the weapon the player fires: in a vehicle's seat, the vehicle's weapon when the vehicle says this unit is its +gunner (its gunner_object_index: the ghost's driver, the warthog's gunner), none in any other seat; on foot, the one +in hand */ +static long seated_weapon(long unit_index, long weapon_index) +{ + struct unit_datum *unit; + struct unit_datum *parent; + + if (unit_index == NONE) + return weapon_index; + unit = unit_get(unit_index); + if (unit->object.parent_object_index == NONE || unit->unit.parent_seat_index == NONE) + return weapon_index; + parent = unit_try_and_get(unit->object.parent_object_index); + if (!parent || parent->unit.gunner_object_index != unit_index) + return NONE; + return unit_inventory_get_weapon(unit->object.parent_object_index, parent->unit.current_weapon_index); +} + +/* Only physical triggers can produce resistance. Other actions leave them free. */ +static void mapped_effect(unsigned char *effect, int button, unsigned char const *layout, + struct dualsense_weapon_state const *state, int zoomed, int grenades, int winding, int percent) +{ + if (layout[PAD_FIRE] == button) + dualsense_right_held(effect, state, percent); + else if (layout[PAD_GRENADE] == button) + dualsense_left_effect(effect, zoomed, grenades, winding, percent); + else if (layout[PAD_ZOOM] == button && zoomed) + dualsense_left_effect(effect, 1, 0, 0, percent); + else + dualsense_effect_off(effect); +} + +static void dualsense_player(short port, short local, struct dualsense_settings const *settings) +{ + struct dualsense_wish wish; + struct dualsense_weapon_state state; + struct controller_device device; + unsigned char layout[CONTROLLER_REMAP_ACTIONS]; + long player_index = local_player_get_player_index(local); + long unit_index = player_get(player_index)->unit_index; + long weapon_index = NONE; + struct unit_datum *unit = unit_index != NONE ? unit_get(unit_index) : NULL; + real_rgb_color color; + int winding, grenades, zoomed; + + memset(&wish, 0, sizeof(wish)); + dualsense_effect_off(wish.right); + dualsense_effect_off(wish.left); + wish.player_lights = dualsense_player_lights(local + 1); + if (game_engine_running()) + game_engine_player_get_change_color(&color, player_index); + else + { + color.red = 0.25f; + color.green = 0.45f; + color.blue = 0.15f; + } + wish.red = channel(color.red); + wish.green = channel(color.green); + wish.blue = channel(color.blue); + wish.playing = settings->triggers && unit && controller_remap_playing(port) && + !game_time_get_paused() && !director_inhibited_input(local); + if (!wish.playing) + { + if (rounds[port].valid) + clear_round(port); + wish.context = rounds[port].context; + dualsense_wish_set(port, &wish); + return; + } + + if (!controller_remap_read(port, layout)) + controller_remap_profile(port, layout); + controller_device_get(port, &device); + weapon_index = seated_weapon(unit_index, unit_inventory_get_weapon(unit_index, unit->unit.current_weapon_index)); + if (!rounds[port].valid || rounds[port].player_index != player_index || rounds[port].unit_index != unit_index || + rounds[port].weapon_index != weapon_index || rounds[port].instance != device.instance || + rounds[port].percent != settings->percent || memcmp(rounds[port].layout, layout, sizeof(layout))) + { + clear_round(port); + rounds[port].player_index = player_index; + rounds[port].unit_index = unit_index; + rounds[port].weapon_index = weapon_index; + rounds[port].instance = device.instance; + rounds[port].percent = settings->percent; + memcpy(rounds[port].layout, layout, sizeof(layout)); + } + weapon_state(weapon_index, &state); + state.ticks = game_time_get(); + zoomed = player_control_get_zoom_level(local) != NONE; + winding = unit->unit.grenade_throw_state == _unit_grenade_throw_wind_up || + unit->unit.grenade_throw_state == _unit_grenade_throw_in_hand; + grenades = unit->unit.current_grenade_index >= 0 ? unit_get_grenade_count(unit_index, unit->unit.current_grenade_index) : 0; + mapped_effect(wish.right, 7, layout, &state, zoomed, grenades, winding, settings->percent); + mapped_effect(wish.left, 6, layout, &state, zoomed, grenades, winding, settings->percent); + if (!state.readying && !state.reloading && !state.overheated) + wish.kick_trigger = layout[PAD_FIRE] == 7 ? 1 : layout[PAD_FIRE] == 6 ? 2 : 0; + if (weapon_index != NONE) + { + long last_fired = weapon_get(weapon_index)->weapon.game_time_last_fired; + + if (rounds[port].valid && last_fired > rounds[port].last_fired && wish.kick_trigger) + { + rounds[port].kick_ms = dualsense_event(rounds[port].kick, state.kind, + rounds[port].last_charge >= 0.95f ? DUALSENSE_EVENT_SHOT_CHARGED : DUALSENSE_EVENT_SHOT, settings->percent); + if (rounds[port].kick_ms > 0) + rounds[port].kicks++; + } + rounds[port].last_fired = last_fired; + } + rounds[port].valid = 1; + rounds[port].last_charge = state.charge; + wish.context = rounds[port].context; + memcpy(wish.kick, rounds[port].kick, sizeof(wish.kick)); + wish.kick_ms = rounds[port].kick_ms; + wish.kicks = rounds[port].kicks; + dualsense_wish_set(port, &wish); +} + +/* After every local player's input update, including dead players and menus. */ +void dualsense_game_update(void) +{ + struct dualsense_settings settings = dualsense_settings_get(); + short port; + + if ((!settings.triggers && !settings.lights) || !game_time_initialized() || !game_in_progress() || main_menu_is_active()) + { + if (tracking) + dualsense_game_reset(); + return; + } + tracking = 1; + for (port = 0; port < MAXIMUM_LOCAL_PLAYERS; port++) + { + short local = controller_remap_local_player(port); + + if (local != NONE && dualsense_port_active(port)) + dualsense_player(port, local, &settings); + else + { + struct dualsense_wish wish; + + if (rounds[port].valid) + clear_round(port); + memset(&wish, 0, sizeof(wish)); + wish.context = rounds[port].context; + dualsense_effect_off(wish.right); + dualsense_effect_off(wish.left); + dualsense_wish_set(port, &wish); + } + } +} diff --git a/port/linux/game/dualsense_game.h b/port/linux/game/dualsense_game.h new file mode 100644 index 0000000000..55a73f126b --- /dev/null +++ b/port/linux/game/dualsense_game.h @@ -0,0 +1,15 @@ +/* +DUALSENSE_GAME.H + +What each local player wants on a DualSense, from the game (the platform side, port/linux/src/dualsense.c, sends it; +input.adaptive_triggers, input.trigger_strength and input.lightbar). Plain types only. +*/ + +#ifndef __DUALSENSE_GAME_H +#define __DUALSENSE_GAME_H + +/* Called after input updates, and at map/checkpoint boundaries. */ +void dualsense_game_update(void); +void dualsense_game_reset(void); + +#endif diff --git a/port/linux/game/enhanced_bots.c b/port/linux/game/enhanced_bots.c new file mode 100644 index 0000000000..69201d8c6d --- /dev/null +++ b/port/linux/game/enhanced_bots.c @@ -0,0 +1,744 @@ +/* Optional bot objectives, adapted from thelinkin3000/halo-ce-universal +d92cc93385edf03d0a4a21cfe4c58dd578a3e786 (AGPL-3.0-or-later, with inherited GPL-3.0-only tactics). Its CTF and hill +decisions draw on id Software's and ioquake3 contributors' Quake III Arena bot rules. Precision-weapon +classification and tactics derive from BirchWoodGod/halo-ce-vita. +See docs/reading/bots_and_android_features.md for the provenance chain. + +The standalone enhanced controller owns combat and navigation. This module +selects destinations; it never changes engine rules or replicated state. */ +#include "cseries.h" +#include "game/game.h" +#include "game/game_engine.h" +#include "game/players.h" +#include "memory/data.h" +#include "scenario/scenario.h" +#include "scenario/scenario_definitions.h" +#include "objects/objects.h" +#include "physics/collisions.h" +#include "items/weapons.h" +#include "items/weapon_definitions.h" +#include "items/projectile_definitions.h" +#include "items/equipment_definitions.h" +#include "units/units.h" +#include "tag_files/tag_groups.h" +#include "networking/network_game_globals.h" +#include "bots.h" +#include "bots_combat.h" +#include "bots_objectives.h" +#include "bots_tactics.h" +#include "bots_vehicles.h" +#include "enhanced_bots.h" +#include "infection.h" +#include "game_modes.h" +#include +#include + +long config_integer(char const *name); + +enum { _bots_goal_none, _bots_goal_objective }; +struct bots_bot +{ + long player_index; + unsigned long random; + short goal_kind; + real_point3d goal_point; + long goal_surface_index; + real_point3d guard_point; + long guard_until_tick; + real_point3d hill_point; + long hill_id; + long hill_until_tick; + long aim_target, aim_until; + boolean aim_head, aim_feet; +}; + +static struct +{ + struct bots_bot bots[BOTS_MAXIMUM]; + long roam_point_count; + real_point3d const *roam_points; + struct + { + long tick; + boolean present[2], at_home[2], home_to_score; + real_point3d position[2], home[2]; + long carrier_player_index[2]; + } ctf; + struct + { + long tick, point_count, hill_id; + boolean present; + real_point3d points[12], center; + real bottom, top; + } king; +} bots_globals; + +static boolean bots_king_guard(struct bots_bot *bot, struct player_datum *player); +static boolean bots_king_active(void); + +/* BirchWoodGod/thelinkin3000 difficulty rules, kept separate from stock bots. + * Preserve the four named levels when using OpenCE's six-level ordering. + * Recruit shares Easy's enhanced tactics; its base combat is weaker. + * Veteran interpolates Heroic and Legendary, as the base skill table does. */ +static struct +{ + real head, feet, heal, heal_fighting, powerup_reach; +} const enhanced_skills[NUMBER_OF_BOTS_SKILLS] = +{ + { 0.15f, 0.0f, 0.35f, 0.00f, 15.0f }, /* Recruit */ + { 0.15f, 0.0f, 0.35f, 0.00f, 15.0f }, /* Easy */ + { 0.40f, 0.4f, 0.50f, 0.25f, 25.0f }, + { 0.70f, 0.8f, 0.65f, 0.35f, 30.0f }, + { 0.85f, 0.9f, 0.725f, 0.40f, 35.0f }, /* Veteran */ + { 1.00f, 1.0f, 0.80f, 0.45f, 40.0f }, +}; + +boolean bots_trace_enabled(void) +{ + return config_integer("debug.bot_trace") > 0; +} + +static long bots_surface_below(real_point3d const *point, real_point3d *ground) +{ + return bots_routes_ground(point, ground); +} + +static void bots_set_goal(struct bots_bot *bot, short kind, real_point3d const *point, long surface) +{ + bot->goal_kind = kind; + bot->goal_point = *point; + bot->goal_surface_index = surface; +} + +static unsigned long bots_random(struct bots_bot *bot) +{ + /* (xorshift32) */ + unsigned long x = bot->random ? bot->random : 0x9E3779B9UL; + + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + x &= 0xFFFFFFFFUL; + bot->random = x; + return x; +} + +static real bots_random_real(struct bots_bot *bot) +{ + return (real)(bots_random(bot) & 0xFFFFFF) / (real)0x1000000; +} + +static real bots_distance2d(real_point3d const *a, real_point3d const *b) +{ + real dx = a->x - b->x, dy = a->y - b->y; + + return (real)sqrt(dx * dx + dy * dy); +} + +static real bots_distance3d(real_point3d const *a, real_point3d const *b) +{ + real dx = a->x - b->x, dy = a->y - b->y, dz = a->z - b->z; + + return (real)sqrt(dx * dx + dy * dy + dz * dz); +} + +static boolean bots_ctf_active(void) +{ + return game_engine_running() && game_engine_get_variant()->game_engine_index == game_engine_ctf; +} + +static boolean bots_ctf_stand(long team, real_point3d *point) +{ + struct scenario *scenario = global_scenario_get(); + long index; + if (game_engine_get_variant()->game_engine_variant.ctf.assault) + team = 1 - team; + for (index = 0; scenario && index < scenario->netgame_flags.count; index++) + { + struct scenario_netgame_flag *flag = + TAG_BLOCK_GET_ELEMENT(&scenario->netgame_flags, index, struct scenario_netgame_flag); + if (flag->type == _netgame_flag_ctf_flag && flag->team_index == team) + { + *point = flag->position; + return TRUE; + } + } + return FALSE; +} + +static void bots_ctf_update(void) +{ + long now = game_time_get(); + long team; + + if (bots_globals.ctf.tick == now) + return; + bots_globals.ctf.tick = now; + bots_globals.ctf.home_to_score = game_engine_get_variant()->game_engine_variant.ctf.flag_at_home_to_score && + game_engine_get_variant()->game_engine_variant.ctf.single_flag_time == 0; + for (team = 0; team < 2; team++) + { + bots_globals.ctf.present[team] = game_engine_ctf_flag_state(team, &bots_globals.ctf.position[team], + &bots_globals.ctf.carrier_player_index[team], &bots_globals.ctf.at_home[team], &bots_globals.ctf.home[team]); + if (!bots_globals.ctf.present[team]) + bots_ctf_stand(team, &bots_globals.ctf.home[team]); + } +} + +static boolean bots_ctf_carrying(struct bots_bot *bot) +{ + long team; + + if (!bots_ctf_active()) + return FALSE; + bots_ctf_update(); + for (team = 0; team < 2; team++) + { + if (bots_globals.ctf.present[team] && bots_globals.ctf.carrier_player_index[team] == bot->player_index) + return TRUE; + } + return FALSE; +} + +static boolean bots_ctf_defender(struct bots_bot *bot, struct player_datum *player) +{ + long team = player->team_index; + long own_bot_index = (long)(bot - bots_globals.bots); + struct data_iterator iterator; + struct player_datum *other; + long team_size = 0; + long rank = 0; + long defenders; + + /* (one flag's assault: the team without one attacks it, the other defends) */ + if (!bots_globals.ctf.present[team]) + return FALSE; + if (!bots_globals.ctf.present[1 - team]) + return TRUE; + data_iterator_new(&iterator, player_data); + while ((other = (struct player_datum *)data_iterator_next(&iterator)) != NULL) + { + if (other->team_index != team) + continue; + team_size++; + if (bots_player_owned(other->network_player_data.machine_index) && + other->network_player_data.machine_index - BOTS_FIRST_MACHINE < own_bot_index) + { + rank++; + } + } + defenders = team_size >= 2 ? MAX(1, team_size * 2 / 5) : 0; + return rank < defenders; +} + +static boolean bots_ctf_set_goal(struct bots_bot *bot, real_point3d const *point, real moved) +{ + real_point3d ground; + long surface_index; + + if (bot->goal_kind == _bots_goal_objective && bots_distance3d(&bot->goal_point, point) < moved) + return TRUE; + surface_index = bots_surface_below(point, &ground); + if (surface_index == NONE) + return FALSE; + bots_set_goal(bot, _bots_goal_objective, &ground, surface_index); + return TRUE; +} + +static boolean bots_ctf_urgent_goal(struct bots_bot *bot, struct player_datum *player, real_point3d const *position) +{ + long team = player->team_index; + long other = 1 - team; + boolean defender; + + if (team != 0 && team != 1) + return FALSE; + bots_ctf_update(); + defender = bots_ctf_defender(bot, player); + /* carrying theirs: home */ + if (bots_globals.ctf.present[other] && bots_globals.ctf.carrier_player_index[other] == bot->player_index) + return bots_ctf_set_goal(bot, &bots_globals.ctf.home[team], 1.0f); + /* (a gametype whose captures need the team's own flag at home, ours + carried off while a team mate carries theirs: everyone after our flag, + or the carrier waits at home for ever, Quake III's flag standoff) */ + if (bots_globals.ctf.home_to_score && bots_globals.ctf.present[team] && bots_globals.ctf.present[other] && + bots_globals.ctf.carrier_player_index[team] != NONE && bots_globals.ctf.carrier_player_index[other] != NONE) + { + return bots_ctf_set_goal(bot, &bots_globals.ctf.position[team], 4.0f); + } + if (bots_globals.ctf.present[team] && !bots_globals.ctf.at_home[team]) + { + real distance = bots_distance3d(position, &bots_globals.ctf.position[team]); + + /* its own carried off: after the carrier */ + if (bots_globals.ctf.carrier_player_index[team] != NONE && (defender || distance < 25.0f)) + return bots_ctf_set_goal(bot, &bots_globals.ctf.position[team], 4.0f); + /* dropped: to it (to touch it home, or to guard it) */ + if (bots_globals.ctf.carrier_player_index[team] == NONE && (defender || distance < 30.0f)) + return bots_ctf_set_goal(bot, &bots_globals.ctf.position[team], 1.5f); + } + return FALSE; +} + +static boolean bots_ctf_choose_goal(struct bots_bot *bot, struct player_datum *player, real_point3d const *position) +{ + long team = player->team_index; + long other = 1 - team; + long now = game_time_get(); + boolean defender; + + if (team != 0 && team != 1) + return FALSE; + if (bots_ctf_urgent_goal(bot, player, position)) + return TRUE; + defender = bots_ctf_defender(bot, player); + if (!defender && bots_globals.ctf.present[other]) + { + long carrier = bots_globals.ctf.carrier_player_index[other]; + + /* a team mate has it: with the carrier */ + if (carrier != NONE) + return bots_ctf_set_goal(bot, &bots_globals.ctf.position[other], 4.0f); + /* at home or dropped: to it */ + return bots_ctf_set_goal(bot, &bots_globals.ctf.position[other], 1.5f); + } + if (defender && bots_globals.ctf.present[team]) + { + /* about its flag: a roaming place near it at a time, or the flag's place */ + if (now >= bot->guard_until_tick || bots_distance2d(&bot->guard_point, &bots_globals.ctf.home[team]) > 16.0f) + { + long index, tries; + + bot->guard_point = bots_globals.ctf.home[team]; + for (tries = 0; tries < 8 && bots_globals.roam_point_count > 0; tries++) + { + index = (long)(bots_random(bot) % (unsigned long)bots_globals.roam_point_count); + if (bots_distance2d(&bots_globals.roam_points[index], &bots_globals.ctf.home[team]) < 14.0f) + { + bot->guard_point = bots_globals.roam_points[index]; + break; + } + } + bot->guard_until_tick = now + TICKS_PER_SECOND * (6 + (long)(bots_random(bot) % 6)); + } + return bots_ctf_set_goal(bot, &bot->guard_point, 1.5f); + } + return FALSE; +} + +boolean bots_quake_defender(long bot_index) +{ + struct bots_bot *bot; + struct player_datum *player; + + if (bot_index < 0 || bot_index >= BOTS_MAXIMUM) + return FALSE; + bot = &bots_globals.bots[bot_index]; + if (bot->player_index == NONE || (player = player_try_and_get(bot->player_index)) == NULL) + return FALSE; + if (bots_ctf_active()) + { + if (player->team_index != 0 && player->team_index != 1) + return FALSE; + bots_ctf_update(); + return bots_ctf_defender(bot, player); + } + if (bots_king_active()) + return bots_king_guard(bot, player); + return FALSE; +} + +static boolean bots_king_active(void) +{ + return game_engine_running() && game_engine_get_variant()->game_engine_index == game_engine_king; +} + +static void bots_king_update(void) +{ + long now = game_time_get(); + + if (bots_globals.king.tick == now) + return; + bots_globals.king.tick = now; + bots_globals.king.present = game_engine_king_hill(bots_globals.king.points, + (long)NUMBEROF(bots_globals.king.points), &bots_globals.king.point_count, &bots_globals.king.bottom, + &bots_globals.king.top, &bots_globals.king.center, &bots_globals.king.hill_id); +} + +static boolean bots_king_on_hill(long unit_index) +{ + bots_king_update(); + return bots_globals.king.present && unit_index != NONE && + game_engine_king_point_on_hill(&object_get(unit_index)->object.bounding_sphere_center); +} + +static boolean bots_king_guard(struct bots_bot *bot, struct player_datum *player) +{ + long own_bot_index = (long)(bot - bots_globals.bots); + struct data_iterator iterator; + struct player_datum *other; + long team_size = 0; + long rank = 0; + + if (!game_engine_has_teams()) + return FALSE; + data_iterator_new(&iterator, player_data); + while ((other = (struct player_datum *)data_iterator_next(&iterator)) != NULL) + { + if (other->team_index != player->team_index) + continue; + team_size++; + if (bots_player_owned(other->network_player_data.machine_index) && + other->network_player_data.machine_index - BOTS_FIRST_MACHINE < own_bot_index) + { + rank++; + } + } + return rank < (team_size >= 8 ? 2 : team_size >= 5 ? 1 : 0); +} + +static boolean bots_king_place(struct bots_bot *bot, real_point3d *place) +{ + long tries; + + for (tries = 0; tries < 6; tries++) + { + real_point3d const *corner = &bots_globals.king.points[bots_random(bot) % + (unsigned long)bots_globals.king.point_count]; + real along = bots_random_real(bot) * 0.75f; + real_point3d probe; + + probe.x = bots_globals.king.center.x + (corner->x - bots_globals.king.center.x) * along; + probe.y = bots_globals.king.center.y + (corner->y - bots_globals.king.center.y) * along; + probe.z = bots_globals.king.center.z + (corner->z - bots_globals.king.center.z) * along + 0.5f; + if (bots_surface_below(&probe, place) != NONE) + { + /* (a place the game counts: a player's middle half a unit up) */ + real_point3d middle = *place; + + middle.z += 0.5f; + if (game_engine_king_point_on_hill(&middle)) + return TRUE; + } + } + return FALSE; +} + +static boolean bots_king_choose_goal(struct bots_bot *bot, struct player_datum *player, real_point3d const *position) +{ + long now = game_time_get(); + real_point3d ground; + long surface_index; + + bots_king_update(); + if (!bots_globals.king.present || bots_globals.king.point_count <= 0) + return FALSE; + if (bots_king_guard(bot, player)) + { + if (now >= bot->guard_until_tick || bots_distance2d(&bot->guard_point, &bots_globals.king.center) > 18.0f) + { + long index, tries; + + bot->guard_point = bots_globals.king.center; + for (tries = 0; tries < 10 && bots_globals.roam_point_count > 0; tries++) + { + real distance; + + index = (long)(bots_random(bot) % (unsigned long)bots_globals.roam_point_count); + distance = bots_distance2d(&bots_globals.roam_points[index], &bots_globals.king.center); + if (distance >= 8.0f && distance <= 16.0f) + { + bot->guard_point = bots_globals.roam_points[index]; + break; + } + } + bot->guard_until_tick = now + TICKS_PER_SECOND * (8 + (long)(bots_random(bot) % 7)); + } + surface_index = bots_surface_below(&bot->guard_point, &ground); + if (surface_index == NONE) + return FALSE; + bots_set_goal(bot, _bots_goal_objective, &ground, surface_index); + return TRUE; + } + /* (a new place: the hill moved, this one reached, or its time up: a few + seconds on the hill, longer on the way) */ + if (bot->hill_id != bots_globals.king.hill_id || now >= bot->hill_until_tick || + bot->goal_kind != _bots_goal_objective || bots_distance2d(position, &bot->hill_point) < 1.0f) + { + boolean on_hill = bots_king_on_hill(player->unit_index); + + if (!bots_king_place(bot, &bot->hill_point)) + bot->hill_point = bots_globals.king.center; + bot->hill_id = bots_globals.king.hill_id; + bot->hill_until_tick = now + TICKS_PER_SECOND * (on_hill ? 2 + (long)(bots_random(bot) % 3) : 12); + } + surface_index = bots_surface_below(&bot->hill_point, &ground); + if (surface_index == NONE) + return FALSE; + bots_set_goal(bot, _bots_goal_objective, &ground, surface_index); + return TRUE; +} + +#define BOTS_PRECISION_SPEED 6.0f +#define BOTS_PRECISION_ERROR 0.0175f +#define BOTS_PRECISION_SCOPE 4.0f +#define BOTS_HEAVY_SPEED 1.0f +static short bots_weapon_precision_compute(long definition_index) +{ + struct weapon_definition *definition = weapon_definition_get(definition_index); + struct weapon_trigger_definition *trigger; + struct projectile_definition *projectile; + real speed; + + if (definition->weapon.triggers.count <= 0) + return _bots_precision_none; + trigger = TAG_BLOCK_GET_ELEMENT(&definition->weapon.triggers, 0, struct weapon_trigger_definition); + if (trigger->projectile.index == NONE) + return _bots_precision_none; + projectile = projectile_definition_get(trigger->projectile.index); + speed = 0.5f * (projectile->projectile.initial_velocity + projectile->projectile.final_velocity); + if (definition->weapon.zoom_level_count < 1 || trigger->projectiles_per_shot > 1) + return _bots_precision_none; + if (speed >= BOTS_PRECISION_SPEED && trigger->projectile_error_angle_lower_bound <= BOTS_PRECISION_ERROR) + { + return definition->weapon.zoom_level_count >= 2 || + definition->weapon.zoom_magnification_maximum >= BOTS_PRECISION_SCOPE ? _bots_precision_long : _bots_precision_mid; + } + return speed > 0.0f && speed < BOTS_HEAVY_SPEED ? _bots_precision_heavy : _bots_precision_none; +} + +static struct +{ + long count; + long definitions[32]; + short precision[32]; +} precision_cache; + +short bots_weapon_precision(long weapon_index) +{ + struct weapon_datum *weapon; + long index; + short precision; + if (weapon_index == NONE) + return _bots_precision_none; + weapon = weapon_get(weapon_index); + for (index = 0; index < precision_cache.count; index++) + if (precision_cache.definitions[index] == weapon->definition_index) + return precision_cache.precision[index]; + precision = bots_weapon_precision_compute(weapon->definition_index); + if (precision_cache.count < (long)NUMBEROF(precision_cache.definitions)) + { + index = precision_cache.count++; + precision_cache.definitions[index] = weapon->definition_index; + precision_cache.precision[index] = precision; + } + return precision; +} + +#include "bots_infection.inl" + +void enhanced_bots_dispose_from_old_map(void) +{ + bots_tactics_dispose_from_old_map(); + bots_vehicles_reset(); + precision_cache.count = 0; + csmemset(&bots_infection, 0, sizeof(bots_infection)); + csmemset(&bots_globals, 0, sizeof(bots_globals)); +} + +void enhanced_bots_initialize_for_new_map(void) +{ + long index; + csmemset(&bots_globals, 0, sizeof(bots_globals)); + precision_cache.count = 0; + csmemset(&bots_infection, 0, sizeof(bots_infection)); + bots_vehicles_reset(); + bots_tactics_initialize_for_new_map(); + bots_globals.ctf.tick = bots_globals.king.tick = NONE; + for (index = 0; index < BOTS_MAXIMUM; index++) + bots_globals.bots[index].player_index = NONE; +} + +void enhanced_bots_update(long count, real_point3d const *points) +{ + bots_globals.roam_point_count = count; + bots_globals.roam_points = points; + bots_tactics_update(); +} + +void enhanced_bots_reset(long index, long player_index) +{ + struct bots_bot *bot = &bots_globals.bots[index]; + csmemset(bot, 0, sizeof(*bot)); + bot->player_index = player_index; + bot->hill_id = NONE; + bot->aim_target = NONE; + bot->random = 0x2545F491UL * (unsigned long)(index + 1) ^ (unsigned long)network_game_get_random_seed(); + bots_tactics_bot_reset(index, player_index); +} + +boolean enhanced_bots_goal(long index, long player_index, real_point3d const *position, + boolean urgent_only, real_point3d *goal, long *surface) +{ + struct bots_bot *bot = &bots_globals.bots[index]; + struct player_datum *player = player_get(player_index); + boolean found = FALSE; + + bots_tactics_check(index, player_index); + if (bots_ctf_active()) + found = bots_ctf_urgent_goal(bot, player, position); + if (bots_king_active()) + found = bots_king_choose_goal(bot, player, position); + if (infection_enabled() && (!urgent_only || infection_unit_is_zombie(player->unit_index))) + found = bots_infection_goal(bot, player, position); + if (found) + bots_tactics_objective(index); + if (!found && !urgent_only) + { + /* Attackers keep a flag destination even with a precision weapon. + Defenders may cover their stand from a vantage point. */ + if (bots_ctf_active() && !bots_ctf_defender(bot, player)) + found = bots_ctf_choose_goal(bot, player, position); + if (!found && bots_tactics_goal(index, player_index, position, goal, surface)) + return TRUE; + if (!found && bots_ctf_active()) + found = bots_ctf_choose_goal(bot, player, position); + } + if (found) + { + *goal = bot->goal_point; + *surface = bot->goal_surface_index; + } + return found; +} + +boolean enhanced_bots_advancing(long index, long unit_index) +{ + struct bots_bot *bot = &bots_globals.bots[index]; + return bots_ctf_carrying(bot) || + (bots_ctf_active() && bot->goal_kind == _bots_goal_objective && + !bots_ctf_defender(bot, player_get(bot->player_index))) || + (bots_king_active() && !bots_king_on_hill(unit_index)) || + (infection_enabled() && infection_unit_is_zombie(unit_index)); +} + +boolean enhanced_bots_carrying(long index) +{ + return bots_ctf_carrying(&bots_globals.bots[index]); +} + +real enhanced_bots_target_priority(struct player_datum *player, long target_index) +{ + struct player_datum *target = player_get(target_index); + if (bots_ctf_active() && (player->team_index == 0 || player->team_index == 1)) + { + bots_ctf_update(); + if (bots_globals.ctf.present[player->team_index] && + bots_globals.ctf.carrier_player_index[player->team_index] == target_index) return 30.0f; + } + return bots_king_active() && bots_king_on_hill(target->unit_index) ? 20.0f : 0.0f; +} + +void enhanced_bots_aim(long index, short skill, long target_index, long weapon_index, + real_point3d const *eye, real_point3d *point) +{ + struct bots_bot *bot = &bots_globals.bots[index]; + long now = game_time_get(); + struct player_datum *target = player_get(target_index); + struct object_datum *object = object_get(target->unit_index); + char const *name = weapon_index != NONE ? tag_get_name(weapon_get(weapon_index)->definition_index) : NULL; + boolean precision = name && (strstr(name, "sniper") || (strstr(name, "pistol") && !strstr(name, "plasma"))); + boolean explosive = name && (strstr(name, "rocket") || strstr(name, "fuel rod") || strstr(name, "plasma_cannon")); + skill = PIN(skill, _bots_skill_recruit, _bots_skill_legendary); + if (bot->aim_target != target_index || now >= bot->aim_until) + { + bot->aim_target = target_index; + bot->aim_until = now + TICKS_PER_SECOND * 2 + bots_random(bot) % TICKS_PER_SECOND; + bot->aim_head = bots_random_real(bot) < enhanced_skills[skill].head; + bot->aim_feet = bots_random_real(bot) < enhanced_skills[skill].feet; + } + if (bot->aim_head && (game_modes_mode() == _game_mode_swat || (precision && object->object.shield_vitality <= 0.0f))) + unit_get_head_position(target->unit_index, point); + else if (bot->aim_feet && explosive && point->z <= eye->z + 0.3f) + { + real_point3d ground; + if (bots_surface_below(&object->object.position, &ground) != NONE && object->object.position.z - ground.z < 1.5f) + { + *point = ground; + point->z += 0.1f; + } + } +} + +boolean enhanced_bots_holding_hill(long unit_index) +{ + return bots_king_active() && bots_king_on_hill(unit_index); +} + +boolean enhanced_bots_retreat(struct unit_datum *unit, short skill, long hurt_tick) +{ + return game_time_get() - hurt_tick < TICKS_PER_SECOND && unit->object.shield_vitality <= 0.05f && + unit->object.body_vitality < enhanced_skills[PIN(skill, _bots_skill_recruit, _bots_skill_legendary)].heal_fighting + 0.1f; +} + +/* BirchWoodGod's health/overshield/camouflage priorities, using the base +bot's item scan, unreachable-item memory and pickup lifecycle. */ +real enhanced_bots_powerup_score(struct unit_datum *unit, long definition_index, real distance, + short skill, boolean fighting, boolean holding) +{ + real threshold, reach = fighting ? 10.0f : enhanced_skills[PIN(skill, _bots_skill_recruit, _bots_skill_legendary)].powerup_reach; + if (game_engine_get_variant()->game_engine_index != game_engine_slayer) reach = MIN(reach, 12.0f); + if (holding) reach = MIN(reach, 6.0f); + switch (equipment_definition_get(definition_index)->equipment.powerup_type) + { + case _equipment_powerup_health: + threshold = fighting ? enhanced_skills[PIN(skill, _bots_skill_recruit, _bots_skill_legendary)].heal_fighting : enhanced_skills[PIN(skill, _bots_skill_recruit, _bots_skill_legendary)].heal; + if (unit->object.body_vitality < threshold && distance <= (fighting ? 15.0f : 45.0f)) + return distance - (threshold - unit->object.body_vitality) * 40.0f; + break; + case _equipment_powerup_overshield: + if (unit->object.shield_vitality <= 1.0f && distance <= reach) + return distance - 6.0f; + break; + case _equipment_powerup_active_camouflage: + if (!TEST_FLAG(unit->unit.flags, _unit_active_camouflaged_bit) && distance <= reach) + return distance - 6.0f; + break; + } + return REAL_MAX; +} + +void enhanced_bots_failed(long index) +{ + bots_globals.bots[index].goal_kind = _bots_goal_none; + bots_tactics_objective(index); +} + +boolean enhanced_bots_capture_approach(long index, real_point3d const *position, real *direction, unsigned long *flags) +{ + struct bots_bot *bot = &bots_globals.bots[index]; + struct player_datum *player; + real_point3d const *home; + real_point3d start, finish; + real_vector3d delta; + struct collision_result hit; + unsigned long collision_flags; + if (!bots_ctf_carrying(bot)) return FALSE; + player = player_get(bot->player_index); + if (player->team_index < 0 || player->team_index > 1) return FALSE; + home = &bots_globals.ctf.home[player->team_index]; + if (bots_distance2d(position, home) >= 4.0f || fabs(home->z - position->z) >= 2.5f) return FALSE; + /* Being close in XY is not permission to cut through the base wall. + Keep the route around entrances until the final approach is visible. */ + start = *position; finish = *home; + start.z += 0.6f; finish.z += 0.6f; + vector_from_points3d(&start, &finish, &delta); + collision_flags = FLAG(_collision_test_structure_bit) | FLAG(_collision_test_front_facing_surfaces_bit) | + FLAG(_collision_test_objects_bit) | FLAG(_collision_test_objects_scenery_bit) | + FLAG(_collision_test_objects_machines_bit) | FLAG(_collision_test_objects_vehicles_bit); + if (collision_test_vector(collision_flags, &start, &delta, player->unit_index, &hit)) return FALSE; + *direction = (real)atan2(home->y - position->y, home->x - position->x); + if (home->z > position->z + 0.4f && bots_distance2d(position, home) < 1.5f && !(game_time_get() & 15)) + *flags |= FLAG(_unit_control_jump_bit); + return TRUE; +} diff --git a/port/linux/game/enhanced_bots.h b/port/linux/game/enhanced_bots.h new file mode 100644 index 0000000000..74499ffc66 --- /dev/null +++ b/port/linux/game/enhanced_bots.h @@ -0,0 +1,23 @@ +/* Optional destinations and tactics; combat and path ownership stay in bots.c. */ +#ifndef HALO_ENHANCED_BOTS_H +#define HALO_ENHANCED_BOTS_H +struct unit_datum; +struct player_datum; +void enhanced_bots_initialize_for_new_map(void); +void enhanced_bots_dispose_from_old_map(void); +void enhanced_bots_update(long count, real_point3d const *points); +void enhanced_bots_reset(long index, long player_index); +boolean enhanced_bots_goal(long index, long player_index, real_point3d const *position, + boolean urgent_only, real_point3d *goal, long *surface); +boolean enhanced_bots_advancing(long index, long unit_index); +boolean enhanced_bots_holding_hill(long unit_index); +boolean enhanced_bots_retreat(struct unit_datum *unit, short skill, long hurt_tick); +boolean enhanced_bots_carrying(long index); +real enhanced_bots_target_priority(struct player_datum *player, long target_index); +void enhanced_bots_aim(long index, short skill, long target_index, long weapon_index, + real_point3d const *eye, real_point3d *point); +real enhanced_bots_powerup_score(struct unit_datum *unit, long definition_index, real distance, + short skill, boolean fighting, boolean holding); +void enhanced_bots_failed(long index); +boolean enhanced_bots_capture_approach(long index, real_point3d const *position, real *direction, unsigned long *flags); +#endif diff --git a/port/linux/game/enhanced_bots_controller.c b/port/linux/game/enhanced_bots_controller.c new file mode 100644 index 0000000000..7e3b592a83 --- /dev/null +++ b/port/linux/game/enhanced_bots_controller.c @@ -0,0 +1,3261 @@ +/* Standalone enhanced bot controller. Derived from the OpenCE bot core +(BirchWoodGod, through 7ea7b0bf7) and GulchCE adaptations. Enhanced navigation and +vehicle tactics retain their notices in their owned modules. Stock bots.c +never executes this controller's decisions or owns its state. */ +#include "cseries.h" +#include "game/game.h" +#include "game/game_engine.h" +#include "game/players.h" +#include "objects/objects.h" +#include "units/units.h" +#include "units/bipeds.h" +#include "units/unit_definitions.h" +#include "items/items.h" +#include "items/weapons.h" +#include "items/weapon_definitions.h" +#include "items/projectile_definitions.h" +#include "physics/collisions.h" +#include "scenario/scenario.h" +#include "scenario/scenario_definitions.h" +#include "structures/structure_bsp_definitions.h" +#include "physics/collision_bsp_definitions.h" +#include "networking/network_game_globals.h" +#include "ai/path.h" +#include "devices/devices.h" +#include "devices/device_definitions.h" +#include "tag_files/tag_groups.h" +#include "tag_files/tag_files.h" + +#include "bots.h" +#include "enhanced_bots_controller.h" +#include "enhanced_bots.h" +#include "bots_tactics.h" +#include "bots_vehicles.h" +#include "infection.h" +#include "items/equipment_definitions.h" +#include "bots_combat.h" + +#include +#include +#include +#include + +/* port/linux/src/port_config.c */ +const char *config_string(char const *name); +long config_integer(char const *name); +int config_boolean(char const *name); +void platform_log(char const *format, ...); + +struct bots_bot; +static int bots_worker_enabled; +static void bots_navigation_prepare(void); +static void bots_navigation_reset(void); +static void bots_navigation_close_surface(long surface); +static void bots_powerups_reset(void); +static void bots_worker_stop(void); +static void bots_navigation_reset_bot(long index); +static void bots_goal_failed(struct bots_bot *bot); + +/* ---------- constants */ + +#define BOTS_PI 3.14159265f +#define BOTS_DEGREES (BOTS_PI / 180.0f) +/* the most places a bot roams to (player starting locations, item spawns) */ +#define BOTS_MAXIMUM_ROAM_POINTS 96 +/* the path searches the bots make in one tick (each up to the engine's +1024 surfaces); a bot whose search waits asks again next tick */ +#define BOTS_SEARCHES_A_TICK 3 +/* the bots' size as the path searches know it (a biped's radius) */ +#define BOTS_PATH_RADIUS 0.25f +/* how near a path's step a bot is when it has reached it (across) */ +#define BOTS_STEP_REACHED 0.35f +/* a pathfinding surface's flag: walkable (path.c's) */ +#define BOTS_PATHFINDING_WALKABLE_BIT 6 +/* the items a bot remembers it found no way to, at once */ +#define BOTS_UNREACHABLE_ITEMS 8 + +/* where a bot is going */ +enum +{ + _bots_goal_none = 0, + _bots_goal_enemy, + _bots_goal_roam, + /* a better weapon to pick up */ + _bots_goal_item, + _bots_goal_enhanced, + _bots_goal_vehicle, +}; + +/* the fight's counts in halo.log's minute line */ +enum +{ + _bots_combat_count_grenades = 0, + _bots_combat_count_blows, + _bots_combat_count_blows_held, + _bots_combat_count_retreats, + _bots_combat_count_charges, + _bots_combat_count_jumps, + _bots_combat_count_halts, + _bots_combat_count_paced, + _bots_combat_count_rescopes, + _bots_combat_count_prenades, + _bots_combat_count_high_ground, + _bots_combat_count_out_of_view, + NUMBER_OF_BOTS_COMBAT_COUNTS, +}; + +/* ---------- structures */ + +struct bots_skill_definition +{ + char const *name; + /* seconds from first seeing an enemy to firing */ + real reaction_seconds; + /* how far it sees an enemy (world units), and how wide (degrees) */ + real sight_distance; + real field_of_view_degrees; + /* the aim error on taking a target (degrees), and the seconds it takes + to settle to a third */ + real aim_error_degrees; + real aim_settle_seconds; + /* the most it turns a tick (degrees) */ + real turn_degrees_per_tick; + /* fires while the aim is within this many times the target's size */ + real fire_cone; + /* how much of a moving target's lead it takes (0 none, 1 all) */ + real lead; + /* the chance a second of throwing a grenade at middle range (normal's; + bots_combat_grenade's rules start from it) */ + real grenade_chance; + /* the ticks of a burst, and of a pause between bursts */ + short burst_ticks; + short pause_ticks; +}; + +/* the levels (bots_combat.h's order): easy, normal, heroic and legendary +are the bots' first levels as they were (their jumps in a fight are now +bots_combat_jump_delay's); recruit is below easy, and veteran halfway from +heroic to legendary in every number */ +static struct bots_skill_definition const bots_skills[NUMBER_OF_BOTS_SKILLS] = +{ + { "recruit", 1.4f, 16.0f, 80.0f, 22.0f, 2.5f, 5.0f, 2.6f, 0.0f, 0.0f, 4, 24 }, + { "easy", 0.75f, 22.0f, 100.0f, 12.0f, 1.4f, 8.0f, 2.2f, 0.3f, 0.04f, 6, 14 }, + { "normal", 0.45f, 32.0f, 120.0f, 7.0f, 0.9f, 13.0f, 1.8f, 0.7f, 0.10f, 9, 9 }, + { "heroic", 0.30f, 42.0f, 140.0f, 4.0f, 0.6f, 20.0f, 1.5f, 0.8f, 0.16f, 12, 6 }, + { "veteran", 0.24f, 48.0f, 150.0f, 3.1f, 0.48f, 25.0f, 1.4f, 0.9f, 0.19f, 14, 5 }, + { "legendary", 0.18f, 55.0f, 160.0f, 2.2f, 0.35f, 30.0f, 1.25f, 1.0f, 0.22f, 16, 4 }, +}; + +/* the ticks of its target's places a bot keeps (the aim that trails it) */ +#define BOTS_TRACK_TICKS 16 + +/* a bot's fight by level, started over at each spawn */ +struct bots_bot_combat +{ + struct bots_combat_retreat retreat; + struct bots_combat_crouch crouch; + /* the end of the strafe it last saw (a new strafe: a halt, maybe), and + the halt's end */ + long last_strafe_until_tick; + long halt_until_tick; + /* the fight's last tick (a new fight after 2 s without one), and its + next jump */ + long last_fight_tick; + long next_jump_tick; + /* the tick it strikes, waiting within reach (NONE: not waiting) */ + long melee_ready_tick; + /* it runs in to finish its target */ + boolean charging; + /* it aims at its target's head */ + /* a grenade in its hand until then: the aim leads the target's path by + this much */ + long throw_until_tick; + real throw_lead; + /* a hit knocked its zoom out: no zoom (and past 10 units no shot) until + then */ + long rescope_until_tick; + /* the tick it began holding a shot for its weapon's error to settle + (NONE: not holding) */ + long pace_since_tick; + /* the throw at the spot its target was last seen: the sighting it was + weighed for, and the aim held on the spot until then */ + long prenade_seen_tick; + long prenade_until_tick; + real_point3d prenade_point; + /* its target's places, a tick each */ + struct + { + long tick; + long player_index; + real_point3d point; + } track[BOTS_TRACK_TICKS]; +}; + +struct bots_bot +{ + long player_index; + long unit_index; + unsigned long random; + + /* where it looks (radians) */ + real yaw; + real pitch; + + /* its target */ + long target_player_index; + long target_seen_tick; + long target_first_seen_tick; + real_point3d target_last_position; + long target_last_surface_index; + real aim_error_yaw; + real aim_error_pitch; + long next_look_tick; + /* the last time it was hurt, and its vitality then */ + real last_vitality; + long hurt_tick; + + /* where it is going */ + short goal_kind; + real_point3d goal_point; + long goal_surface_index; + long goal_tick; + short roam_index; + /* the roaming place is towards an enemy (looked at again sooner) */ + boolean hunting; + /* the item it fetches (_bots_goal_item), and when it last pressed the + action button for it; when it first pressed it for this item */ + long item_index; + long item_press_tick; + long item_first_press_tick; + /* the path there (steps of the engine's path), and when it was found */ + struct path_result path; + long path_tick; + long path_failures; + long goal_serial, navigation_parent, navigation_seat; + long objective_retry_tick; + real_point3d intent_point; + /* off a surface closed to the searches (beside a door): away from what + closed it, until then */ + long escape_until_tick; + real escape_direction; + /* its path ends short of the goal (the search found no way there: a + platform the walkable surfaces do not reach); at its end, straight on + with jumps until then */ + boolean path_short; + long climb_until_tick; + long climb_start_tick; + real climb_best_distance; + /* where it was last tick (a teleporter's jump) */ + real_point3d last_position; + /* an item it found no way to (on a ledge), not fetched again until then */ + long unreachable_item_indices[BOTS_UNREACHABLE_ITEMS]; + long unreachable_item_until_ticks[BOTS_UNREACHABLE_ITEMS]; + long unreachable_item_next; + /* whether it moves, checked once a second */ + real_point3d stuck_position; + long stuck_tick; + short stuck_count; + long unstick_until_tick; + real unstick_direction; + + /* fighting: the side it strafes to and until when; bursts */ + real strafe_sign; + long strafe_until_tick; + long burst_until_tick; + long pause_until_tick; + long grenade_tick; + long melee_tick; + long item_check_tick; + long powerup_index, powerup_deadline, powerup_arrived, powerup_check; + real powerup_distance; + + /* the buttons held last tick (a press is a tick held, then released) */ + unsigned long previous_control_flags; + + struct bots_bot_combat combat; + + /* (debug.bot_trace) its path searches */ + long searches; +}; + +/* ---------- globals */ + +static struct +{ + boolean map_ready; + long roam_point_count; + real_point3d roam_points[BOTS_MAXIMUM_ROAM_POINTS]; + long roam_surfaces[BOTS_MAXIMUM_ROAM_POINTS]; + struct bots_bot bots[BOTS_MAXIMUM]; + /* the skill setting, read once a tick for every bot */ + short skill; + /* the fight's counts for halo.log */ + long combat_counts[NUMBER_OF_BOTS_COMBAT_COUNTS]; + /* the path search's state (80 KB: the engine's 1024 nodes, heap and + table), allocated once a game has bots; the searches made this tick */ + struct path_state *search; + long tick_searches; + long search_cursor; + long search_wait[BOTS_MAXIMUM], search_seen[BOTS_MAXIMUM]; + + /* the statistics of halo.log's line */ + long ticks; + long searches; + long search_failures; + /* searches that stopped short of the goal (a path to as near as they + came), and those that ran out of nodes */ + long search_partials; + long search_overflows; + /* paths taken without the obstacle avoidance, which found no way */ + long search_unavoided; + /* the paths whose smoothing went nowhere, taken unsmoothed */ + long search_unsmoothed; + /* the times a bot stood stuck while it walked, and the goals given up + after three */ + long stuck_events; + long stuck_giveups; + long last_report_tick; +} bots_globals; + +/* the walkable surfaces the bots' searches read: a copy of the structure's +pathfinding surfaces, less those learnt to be in the way (scenery and +machines) and those with no room above them */ +static struct +{ + struct structure_bsp const *source; + struct structure_bsp structure; + byte *walkable; + /* the objects whose surfaces are closed */ + long learned[32]; + long learned_count; + long closed_count; + /* the surfaces looked at for room above them, and those closed */ + long scan_index; + boolean scan_done; + long roofed_count; + long scan_ticks; +} bots_paths; + +/* ---------- settings */ + +/* ---------- small helpers */ + +static unsigned long bots_random(struct bots_bot *bot) +{ + /* (xorshift32) */ + unsigned long x = bot->random ? bot->random : 0x9E3779B9UL; + + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + x &= 0xFFFFFFFFUL; + bot->random = x; + return x; +} + +/* 0 to 1 */ +static real bots_random_real(struct bots_bot *bot) +{ + return (real)(bots_random(bot) & 0xFFFFFF) / (real)0x1000000; +} + +/* -1 to 1 */ +static real bots_random_signed(struct bots_bot *bot) +{ + return bots_random_real(bot) * 2.0f - 1.0f; +} + +static real bots_angle_difference(real a, real b) +{ + real difference = (real)fmod(a - b, 2.0f * BOTS_PI); + + if (difference > BOTS_PI) + difference -= 2.0f * BOTS_PI; + else if (difference < -BOTS_PI) + difference += 2.0f * BOTS_PI; + return difference; +} + +static real bots_distance2d(real_point3d const *a, real_point3d const *b) +{ + real dx = a->x - b->x, dy = a->y - b->y; + + return (real)sqrt(dx * dx + dy * dy); +} + +static real bots_distance3d(real_point3d const *a, real_point3d const *b) +{ + real dx = a->x - b->x, dy = a->y - b->y, dz = a->z - b->z; + + return (real)sqrt(dx * dx + dy * dy + dz * dz); +} + +/* the surface of the level under a point (a step up included), and the +ground point there; NONE over nothing */ +static long bots_surface_below(real_point3d const *point, real_point3d *ground) +{ + struct collision_result collision; + real_point3d start = *point; + real_vector3d down = {0.0f, 0.0f, -6.0f}; + + start.z += 0.4f; + if (collision_test_vector(FLAG(_collision_test_structure_bit) | FLAG(_collision_test_front_facing_surfaces_bit), + &start, &down, NONE, &collision) && + collision.type == _collision_result_structure) + { + if (ground) + *ground = collision.point; + return collision.surface_index; + } + return NONE; +} + +/* the surface a unit stands on (a biped's support surface), and its point */ +static long bots_unit_surface(long unit_index, real_point3d *point) +{ + struct object_datum *object = object_get(unit_index); + struct biped_datum *biped = biped_try_and_get(unit_index); + + *point = object->object.position; + if (object->object.parent_object_index != NONE) + return NONE; + if (biped && biped->biped.support_surface_index != NONE) + return biped->biped.support_surface_index; + return bots_surface_below(&object->object.position, point); +} + +/* the unit's current weapon, NONE without one */ +static long bots_current_weapon(struct unit_datum *unit) +{ + if (unit->unit.current_weapon_index < 0 || unit->unit.current_weapon_index >= MAXIMUM_WEAPONS_PER_UNIT) + return NONE; + return unit->unit.weapon_object_indices[unit->unit.current_weapon_index]; +} + +/* whether a weapon has no rounds left (one with magazines) */ +static boolean bots_weapon_empty(long weapon_index) +{ + struct weapon_datum *weapon = weapon_get(weapon_index); + struct weapon_definition *definition = weapon_definition_get(weapon->definition_index); + + if (definition->weapon.magazines.count <= 0) + return FALSE; + return weapon->weapon.magazines[0].rounds_loaded + weapon->weapon.magazines[0].rounds_total <= 0; +} + +/* how full the weapon's magazine is, 0 to 1 (1 for one without) */ +static real bots_weapon_loaded(long weapon_index) +{ + struct weapon_datum *weapon = weapon_get(weapon_index); + struct weapon_definition *definition = weapon_definition_get(weapon->definition_index); + struct weapon_magazine_definition *magazine; + + if (definition->weapon.magazines.count <= 0) + return 1.0f; + magazine = TAG_BLOCK_GET_ELEMENT(&definition->weapon.magazines, 0, struct weapon_magazine_definition); + if (magazine->rounds_loaded_maximum <= 0) + return 1.0f; + return (real)weapon->weapon.magazines[0].rounds_loaded / (real)magazine->rounds_loaded_maximum; +} + +/* the speed of the weapon's projectile (world units a tick; 0 for one +that hits at once or none) */ +static real bots_projectile_speed_compute(long definition_index) +{ + struct weapon_definition *definition = weapon_definition_get(definition_index); + + if (definition->weapon.triggers.count > 0) + { + struct weapon_trigger_definition *trigger = + TAG_BLOCK_GET_ELEMENT(&definition->weapon.triggers, 0, struct weapon_trigger_definition); + + if (trigger->projectile.index != NONE) + { + struct projectile_definition *projectile = projectile_definition_get(trigger->projectile.index); + + return 0.5f * (projectile->projectile.initial_velocity + projectile->projectile.final_velocity); + } + } + return 0.0f; +} + +/* how much a bot wants a weapon (the stock weapons, by their tags' names), +-1 for the game's own (a flag, a ball) */ +static short bots_weapon_value_compute(long definition_index) +{ + static struct + { + char const *name; + short value; + } const values[] = { + {"rocket", 9}, {"sniper", 8}, {"shotgun", 8}, {"fuel rod", 7}, {"plasma_cannon", 7}, + {"plasma pistol", 3}, {"pistol", 7}, {"assault rifle", 6}, {"needler", 5}, {"plasma rifle", 5}, + {"flamethrower", 4}, {"flag", -1}, {"ball", -1}, {"skull", -1}, + }; + char const *name = tag_get_name(definition_index); + long index; + + if (!name) + return 4; + for (index = 0; index < (long)NUMBEROF(values); index++) + { + if (strstr(name, values[index].name)) + return values[index].value; + } + return 4; +} + +/* how a bot fires the weapon: the ticks between presses of a weapon fired a +press at a time (a latched trigger: the pistols, the sniper rifle, the +rocket launcher; or one that charges while held: the plasma pistol), 0 for +one held down in bursts */ +static short bots_weapon_tap_ticks_compute(long definition_index) +{ + struct weapon_definition *definition = weapon_definition_get(definition_index); + struct weapon_trigger_definition *trigger; + real rate; + + if (definition->weapon.triggers.count <= 0) + return 0; + trigger = TAG_BLOCK_GET_ELEMENT(&definition->weapon.triggers, 0, struct weapon_trigger_definition); + if (!TEST_FLAG(trigger->flags, _weapon_trigger_latched_bit) && trigger->charging_time <= 0.0f) + return 0; + rate = trigger->initial_rate_of_fire > 0.0f ? trigger->initial_rate_of_fire : 3.0f; + return (short)PIN((long)((real)TICKS_PER_SECOND / rate + 0.5f), 2, TICKS_PER_SECOND * 2); +} + +/* the distance a bot keeps from its enemy with the weapon */ +static real bots_weapon_range_compute(long definition_index) +{ + char const *name = tag_get_name(definition_index); + + if (!name) + return 6.0f; + if (strstr(name, "shotgun") || strstr(name, "flamethrower")) + return 2.0f; + if (strstr(name, "sniper")) + return 18.0f; + if (strstr(name, "rocket") || strstr(name, "fuel rod") || strstr(name, "plasma_cannon")) + return 12.0f; + if (strstr(name, "plasma pistol") || strstr(name, "needler")) + return 5.0f; + if (strstr(name, "pistol")) + return 9.0f; + return 7.0f; +} + +/* how a weapon definition aims (the fight by level): whether it kills with +a shot to the head (the pistol, the sniper rifle), whether its shots are +true only zoomed (the sniper rifle: its trigger's error when unzoomed), and +whether its error grows as it fires (the pistol) */ +static void bots_weapon_aim_compute(long definition_index, boolean *precision, boolean *sniper, boolean *blooms) +{ + struct weapon_definition *definition = weapon_definition_get(definition_index); + char const *name = tag_get_name(definition_index); + + *precision = name && ((strstr(name, "pistol") && !strstr(name, "plasma")) || strstr(name, "sniper")); + *sniper = FALSE; + *blooms = FALSE; + if (definition->weapon.triggers.count > 0) + { + struct weapon_trigger_definition *trigger = + TAG_BLOCK_GET_ELEMENT(&definition->weapon.triggers, 0, struct weapon_trigger_definition); + + *sniper = TEST_FLAG(trigger->flags, _weapon_trigger_use_error_when_unzoomed_bit) && + definition->weapon.zoom_level_count > 0; + *blooms = trigger->projectile_error_angle_upper_bound > trigger->projectile_error_angle_lower_bound + 0.001f; + } +} + +/* what the bots know of a weapon definition (its value, the distance kept +with it, how it fires, its projectile's speed, how it aims), made once a map: the +functions above read only its tag, its name and its trigger, which a map +never changes (a bot asked them of its weapon every tick: a dozen name +searches and a few tag lookups) */ +#define BOTS_WEAPON_KINDS 32 +struct bots_weapon_kind +{ + long definition_index; + short value; + short tap_ticks; + real range; + real projectile_speed; + boolean precision; + boolean sniper; + boolean blooms; +}; + +static struct +{ + long count; + struct bots_weapon_kind kinds[BOTS_WEAPON_KINDS]; + /* (the one made when the table is full) */ + struct bots_weapon_kind spare; +} bots_weapon_kinds; + +static struct bots_weapon_kind const *bots_weapon_kind(long definition_index) +{ + struct bots_weapon_kind *kind; + long index; + + for (index = 0; index < bots_weapon_kinds.count; index++) + { + if (bots_weapon_kinds.kinds[index].definition_index == definition_index) + return &bots_weapon_kinds.kinds[index]; + } + kind = bots_weapon_kinds.count < BOTS_WEAPON_KINDS ? &bots_weapon_kinds.kinds[bots_weapon_kinds.count++] + : &bots_weapon_kinds.spare; + kind->definition_index = definition_index; + kind->value = bots_weapon_value_compute(definition_index); + kind->tap_ticks = bots_weapon_tap_ticks_compute(definition_index); + kind->range = bots_weapon_range_compute(definition_index); + kind->projectile_speed = bots_projectile_speed_compute(definition_index); + bots_weapon_aim_compute(definition_index, &kind->precision, &kind->sniper, &kind->blooms); + return kind; +} + +static short bots_weapon_value(long definition_index) +{ + return bots_weapon_kind(definition_index)->value; +} + +static real bots_projectile_speed(long weapon_index) +{ + return bots_weapon_kind(weapon_get(weapon_index)->definition_index)->projectile_speed; +} + +static short bots_weapon_tap_ticks(long weapon_index) +{ + return bots_weapon_kind(weapon_get(weapon_index)->definition_index)->tap_ticks; +} + +static real bots_weapon_range(long weapon_index) +{ + return weapon_index != NONE ? bots_weapon_kind(weapon_get(weapon_index)->definition_index)->range : 6.0f; +} + +/* whether the bot found no way to the item a while ago (left be thirty +seconds), and the item so remembered (the oldest of those kept forgotten) */ +static boolean bots_item_unreachable(struct bots_bot const *bot, long item_index) +{ + long index; + + for (index = 0; index < BOTS_UNREACHABLE_ITEMS; index++) + { + if (bot->unreachable_item_indices[index] == item_index && + game_time_get() < bot->unreachable_item_until_ticks[index]) + return TRUE; + } + return FALSE; +} + +static void bots_item_set_unreachable(struct bots_bot *bot, long item_index) +{ + long slot; + + /* (one remembered already: kept longer) */ + for (slot = 0; slot < BOTS_UNREACHABLE_ITEMS; slot++) + { + if (bot->unreachable_item_indices[slot] == item_index && + game_time_get() < bot->unreachable_item_until_ticks[slot]) + { + bot->unreachable_item_until_ticks[slot] = game_time_get() + TICKS_PER_SECOND * 30; + return; + } + } + slot = bot->unreachable_item_next; + bot->unreachable_item_indices[slot] = item_index; + bot->unreachable_item_until_ticks[slot] = game_time_get() + TICKS_PER_SECOND * 30; + bot->unreachable_item_next = (slot + 1) % BOTS_UNREACHABLE_ITEMS; +} + +/* a weapon lying near the bot worth fetching: one better than the one it +holds; NONE for none */ +static long bots_find_item(struct bots_bot *bot, struct unit_datum *unit, real_point3d const *position, + real maximum_distance) +{ + struct object_iterator iterator; + long best_index = NONE; + real best_score = REAL_MAX; + long current = bots_current_weapon(unit); + short current_value = current != NONE ? bots_weapon_value(weapon_get(current)->definition_index) : 0; + + object_iterator_new(&iterator, _object_mask_weapon, 0); + while (object_iterator_next(&iterator)) + { + struct item_datum *item = item_get(iterator.index); + real distance, score; + short value; + short slot; + boolean held = FALSE; + + if (item->object.parent_object_index != NONE || bots_item_unreachable(bot, iterator.index) || + !TEST_FLAG(item->object.flags, _object_connected_to_map_bit) || + TEST_FLAG(item->item.flags, _item_attached_to_unit_bit)) + { + continue; + } + distance = bots_distance3d(&item->object.position, position); + if (distance > maximum_distance) + continue; + value = bots_weapon_value(item->definition_index); + /* (one it holds already: only its ammunition, which walking over + takes) */ + for (slot = 0; slot < MAXIMUM_WEAPONS_PER_UNIT; slot++) + { + long other = unit->unit.weapon_object_indices[slot]; + + if (other != NONE && weapon_get(other)->definition_index == item->definition_index) + held = TRUE; + } + if (held || value <= current_value) + continue; + score = distance - (real)(value - current_value) * 3.0f; + if (score < best_score) + { + best_score = score; + best_index = iterator.index; + } + } + return best_index; +} + +/* ---------- the map */ + +static void bots_add_roam_point(real_point3d const *point) +{ + real_point3d ground; + long surface_index; + + if (bots_globals.roam_point_count >= BOTS_MAXIMUM_ROAM_POINTS) + return; + surface_index = bots_surface_below(point, &ground); + if (surface_index == NONE) + return; + bots_globals.roam_points[bots_globals.roam_point_count] = ground; + bots_globals.roam_surfaces[bots_globals.roam_point_count] = surface_index; + bots_globals.roam_point_count++; +} + +/* the bots' walkable surfaces let go */ +static void bots_paths_release(void) +{ + if (bots_paths.walkable) + free(bots_paths.walkable); + csmemset(&bots_paths, 0, sizeof(bots_paths)); +} + +/* the surface's corners (at most BOTS_SURFACE_CORNERS), from its ring of +edges; 0 for one not the bsp's */ +#define BOTS_SURFACE_CORNERS 16 +static long bots_surface_corners(struct collision_bsp const *bsp, long surface_index, real_point3d *corners) +{ + struct collision_surface const *surface; + long edge_index, count = 0; + + if (surface_index < 0 || surface_index >= bsp->surfaces.count) + return 0; + surface = TAG_BLOCK_GET_ELEMENT(&bsp->surfaces, surface_index, struct collision_surface); + edge_index = surface->first_edge_index; + do + { + struct collision_edge const *edge; + boolean right; + + if (edge_index < 0 || edge_index >= bsp->edges.count) + return 0; + edge = TAG_BLOCK_GET_ELEMENT(&bsp->edges, edge_index, struct collision_edge); + right = edge->surface_indices[1] == surface_index; + if (!VALID_INDEX(edge->vertex_indices[right], bsp->vertices.count)) + return 0; + corners[count++] = + TAG_BLOCK_GET_ELEMENT(&bsp->vertices, edge->vertex_indices[right], struct collision_vertex)->point; + edge_index = edge->edge_indices[right]; + } while (edge_index != surface->first_edge_index && count < BOTS_SURFACE_CORNERS); + return count; +} + +/* whether the object stands across the surface: a line over it at a biped's +knees or chest, from its middle to a little past an edge's, meets it, or +its middle is under it */ +static boolean bots_surface_blocked(long object_index, real_point3d const *corners, long corner_count, + real_point3d const *middle) +{ + static real const heights[] = {0.35f, 1.0f}; + unsigned long flags = FLAG(_collision_test_front_facing_surfaces_bit) | + FLAG(_collision_test_back_facing_surfaces_bit) | FLAG(_collision_test_objects_bit) | + FLAG(_collision_test_objects_scenery_bit) | FLAG(_collision_test_objects_machines_bit); + struct collision_result collision; + real_point3d start = *middle; + real_vector3d up = {0.0f, 0.0f, 1.6f}; + long height, corner; + + start.z += 0.05f; + if (collision_test_vector(flags, &start, &up, NONE, &collision) && collision.type == _collision_result_object && + collision.object_index == object_index) + { + return TRUE; + } + for (height = 0; height < (long)NUMBEROF(heights); height++) + { + start.z = middle->z + heights[height]; + for (corner = 0; corner < corner_count; corner++) + { + real_point3d const *a = &corners[corner], *b = &corners[(corner + 1) % corner_count]; + real_vector3d vector; + real length, past; + + vector.i = 0.5f * (a->x + b->x) - start.x; + vector.j = 0.5f * (a->y + b->y) - start.y; + vector.k = 0.5f * (a->z + b->z) + heights[height] - start.z; + /* (on a little past the edge: a door may stand on it) */ + length = (real)sqrt(vector.i * vector.i + vector.j * vector.j + vector.k * vector.k); + if (length < 0.01f) + continue; + past = (length + 0.4f) / length; + vector.i *= past; + vector.j *= past; + vector.k *= past; + if (collision_test_vector(flags, &start, &vector, NONE, &collision) && + collision.type == _collision_result_object && collision.object_index == object_index) + { + return TRUE; + } + } + } + return FALSE; +} + +/* the bots' copy of the structure's walkable surfaces, made (the searches +take it from then on); FALSE without one */ +static boolean bots_paths_copy(void) +{ + struct structure_bsp *structure = global_structure_bsp_get(); + long count; + + if (!structure || structure->pathfinding_surfaces.count <= 0 || structure->collision_bsp.count <= 0 || + (bots_paths.source && bots_paths.source != structure)) + { + return FALSE; + } + if (bots_paths.walkable) + return TRUE; + count = structure->pathfinding_surfaces.count; + bots_paths.walkable = (byte *)malloc((size_t)count); + if (!bots_paths.walkable) + return FALSE; + csmemcpy(bots_paths.walkable, structure->pathfinding_surfaces.address, (size_t)count); + bots_paths.structure = *structure; + bots_paths.structure.pathfinding_surfaces.address = bots_paths.walkable; + bots_paths.source = structure; + return TRUE; +} + +/* a walkable surface of the bots' copy: its corners, its middle and how far +its corners are from it; FALSE for one not walkable (or not the bsp's) */ +static boolean bots_paths_walkable_surface(struct collision_bsp const *bsp, long surface_index, real_point3d *corners, + long *corner_count, real_point3d *middle, real *reach) +{ + long corner; + + if (surface_index >= bots_paths.structure.pathfinding_surfaces.count || + !TEST_FLAG(bots_paths.walkable[surface_index], BOTS_PATHFINDING_WALKABLE_BIT)) + { + return FALSE; + } + *corner_count = bots_surface_corners(bsp, surface_index, corners); + if (*corner_count < 3) + return FALSE; + middle->x = middle->y = middle->z = 0.0f; + for (corner = 0; corner < *corner_count; corner++) + { + middle->x += corners[corner].x / (real)*corner_count; + middle->y += corners[corner].y / (real)*corner_count; + middle->z += corners[corner].z / (real)*corner_count; + } + *reach = 0.0f; + for (corner = 0; corner < *corner_count; corner++) + *reach = MAX(*reach, bots_distance3d(middle, &corners[corner])); + return TRUE; +} + +/* the walkable surfaces an object stands across closed to the bots' searches */ +static void bots_paths_close_object(long object_index, char const *why) +{ + struct object_datum *object = object_get(object_index); + struct collision_bsp const *bsp; + long surface_index, closed = 0; + + if (bots_paths.learned_count >= (long)NUMBEROF(bots_paths.learned) || !bots_paths_copy()) + return; + bots_paths.learned[bots_paths.learned_count++] = object_index; + bsp = TAG_BLOCK_GET_ELEMENT(&bots_paths.structure.collision_bsp, 0, struct collision_bsp); + for (surface_index = 0; surface_index < bsp->surfaces.count; surface_index++) + { + real_point3d corners[BOTS_SURFACE_CORNERS], middle; + real reach; + long corner_count; + + if (bots_paths_walkable_surface(bsp, surface_index, corners, &corner_count, &middle, &reach) && + bots_distance3d(&middle, &object->object.bounding_sphere_center) < + object->object.bounding_sphere_radius + reach + 0.5f && + bots_surface_blocked(object_index, corners, corner_count, &middle)) + { + bots_paths.walkable[surface_index] &= (byte)~FLAG(BOTS_PATHFINDING_WALKABLE_BIT); + bots_navigation_close_surface(surface_index); + closed++; + } + } + bots_paths.closed_count += closed; + platform_log("bots: %s %s at (%.1f %.1f %.1f): %ld walkable surfaces closed", why, + tag_get_name(object->definition_index), object->object.bounding_sphere_center.x, + object->object.bounding_sphere_center.y, object->object.bounding_sphere_center.z, closed); +} + +/* the walkable surfaces with no room above them closed, a few a tick from +the game's start: a floor that goes on under a wall (Longest's bases: the +floor's strips under the walls joined the rooms either side, and a team's +bots walked into the wall a whole game). A surface is closed whose middle, +or most of the points halfway from it to its corners, have the level less +than half a biped's height above them */ +#define BOTS_PATHS_SCAN_A_TICK 32 +static void bots_paths_scan(void) +{ + struct collision_bsp const *bsp; + long scanned; + + if (bots_paths.scan_done || !bots_paths_copy()) + return; + bots_paths.scan_ticks++; + bsp = TAG_BLOCK_GET_ELEMENT(&bots_paths.structure.collision_bsp, 0, struct collision_bsp); + for (scanned = 0; scanned < BOTS_PATHS_SCAN_A_TICK; scanned++) + { + long surface_index = bots_paths.scan_index++; + real_point3d corners[BOTS_SURFACE_CORNERS], middle; + real reach; + long corner_count, sample, covered = 0; + + if (surface_index >= bsp->surfaces.count || surface_index >= bots_paths.structure.pathfinding_surfaces.count) + { + bots_paths.scan_done = TRUE; + platform_log("bots: %ld walkable surfaces with no room above closed (%ld ticks, %d surfaces a tick)", + bots_paths.roofed_count, bots_paths.scan_ticks, BOTS_PATHS_SCAN_A_TICK); + return; + } + if (!bots_paths_walkable_surface(bsp, surface_index, corners, &corner_count, &middle, &reach)) + continue; + /* (the middle first: covered, the surface is; else most of the + points between it and the corners) */ + for (sample = -1; sample < corner_count; sample++) + { + unsigned long flags = FLAG(_collision_test_structure_bit) | + FLAG(_collision_test_front_facing_surfaces_bit) | + FLAG(_collision_test_back_facing_surfaces_bit); + real_vector3d up = {0.0f, 0.0f, 0.35f}; + struct collision_result collision; + real_point3d point = middle; + + if (sample >= 0) + { + point.x = 0.5f * (middle.x + corners[sample].x); + point.y = 0.5f * (middle.y + corners[sample].y); + point.z = 0.5f * (middle.z + corners[sample].z); + } + point.z += 0.05f; + if (collision_test_vector(flags, &point, &up, NONE, &collision)) + { + if (sample < 0) + { + covered = corner_count; + break; + } + covered++; + } + } + if (covered * 2 > corner_count) + { + bots_paths.walkable[surface_index] &= (byte)~FLAG(BOTS_PATHFINDING_WALKABLE_BIT); + bots_navigation_close_surface(surface_index); + bots_paths.roofed_count++; + } + } +} + +static boolean bots_paths_learned(long object_index) +{ + long index; + + for (index = 0; index < bots_paths.learned_count; index++) + { + if (bots_paths.learned[index] == object_index) + return TRUE; + } + return FALSE; +} + +/* whether the point is on or in the object (by its bounding sphere) */ +static boolean bots_object_holds(struct object_datum *object, real_point3d const *point) +{ + return bots_distance2d(&object->object.bounding_sphere_center, point) < + object->object.bounding_sphere_radius + 0.4f && + fabs(object->object.bounding_sphere_center.z - point->z) < object->object.bounding_sphere_radius + 1.0f; +} + +/* the scenery or machine (with a collision model) the point is on or in, +the nearest; NONE for none */ +static long bots_object_at(real_point3d const *point) +{ + struct object_iterator iterator; + long best_index = NONE; + real best_distance = REAL_MAX; + + object_iterator_new(&iterator, _object_mask_scenery | _object_mask_machine, 0); + while (object_iterator_next(&iterator)) + { + struct object_datum *object = object_get(iterator.index); + real distance; + + if (object_definition_get(object->definition_index)->object.collision_model.index == NONE || + !bots_object_holds(object, point)) + { + continue; + } + distance = bots_distance3d(&object->object.bounding_sphere_center, point); + if (distance < best_distance) + { + best_distance = distance; + best_index = iterator.index; + } + } + return best_index; +} + +/* whether one of the map's game places (a flag's stand, a teleporter, a +hill's corner, a ball's spawn) is on or in the object: never in the way */ +static boolean bots_object_marks_place(struct object_datum *object) +{ + struct scenario *scenario = global_scenario_get(); + long index; + + for (index = 0; scenario && index < scenario->netgame_flags.count; index++) + { + struct scenario_netgame_flag *flag = + TAG_BLOCK_GET_ELEMENT(&scenario->netgame_flags, index, struct scenario_netgame_flag); + + if (bots_object_holds(object, &flag->position)) + return TRUE; + } + return FALSE; +} + +/* whether the point stands on the object (the level or another object +under it first) */ +static boolean bots_object_supports(long object_index, real_point3d const *point) +{ + struct collision_result collision; + real_point3d start = *point; + real_vector3d down = {0.0f, 0.0f, -1.2f}; + + start.z += 0.4f; + return collision_test_vector(FLAG(_collision_test_structure_bit) | FLAG(_collision_test_front_facing_surfaces_bit) | + FLAG(_collision_test_objects_bit) | FLAG(_collision_test_objects_scenery_bit) | + FLAG(_collision_test_objects_machines_bit), + &start, &down, NONE, &collision) && + collision.type == _collision_result_object && collision.object_index == object_index; +} + +/* a path's obstacle avoidance found no way past where the bot is: the +scenery and machines about it (not the bipeds and vehicles, which move) are +in the way, their surfaces closed to the searches from now on (Sidewinder's +blast door between the bases is scenery: the search, over the structure +alone, goes through it, the shortest way, and the avoidance then finds no +way past; more than half of the searches across that map failed so). A +rock or a tree the avoidance goes around is never in the way. How many +were learnt */ +static long bots_paths_learn(real_point3d const *position, real_point3d const *goal) +{ + struct object_iterator iterator; + long learned = 0; + + object_iterator_new(&iterator, _object_mask_scenery | _object_mask_machine, 0); + while (object_iterator_next(&iterator)) + { + struct object_datum *object = object_get(iterator.index); + struct object_definition *definition = object_definition_get(object->definition_index); + + /* (not what the bot or its goal stands on or in: a flag's stand, a + teleporter's base; what the bot stands beside, within its bounding + sphere but on the level, is learnt: a bot pressed against + Sidewinder's blast door before it was learnt never learnt it) */ + if (definition->object.collision_model.index == NONE || + bots_distance2d(&object->object.bounding_sphere_center, position) > + object->object.bounding_sphere_radius + 4.5f || + fabs(object->object.bounding_sphere_center.z - position->z) > + object->object.bounding_sphere_radius + 2.0f || + (bots_object_holds(object, position) && bots_object_supports(iterator.index, position)) || + bots_object_holds(object, goal) || bots_paths_learned(iterator.index) || bots_object_marks_place(object)) + { + continue; + } + bots_paths_close_object(iterator.index, "in the way:"); + learned++; + } + return learned; +} + +/* the way off a closed surface: away from the nearest of what closed it */ +static boolean bots_paths_escape_direction(real_point3d const *position, real *direction) +{ + long index, nearest = NONE; + real nearest_distance = REAL_MAX; + + for (index = 0; index < bots_paths.learned_count; index++) + { + struct object_datum *object = object_try_and_get(bots_paths.learned[index]); + real distance; + + if (!object) + continue; + distance = bots_distance2d(&object->object.bounding_sphere_center, position); + if (distance < nearest_distance && distance < object->object.bounding_sphere_radius + 4.0f) + { + nearest_distance = distance; + nearest = index; + } + } + if (nearest == NONE) + return FALSE; + { + struct object_datum *object = object_get(bots_paths.learned[nearest]); + + *direction = (real)atan2(position->y - object->object.bounding_sphere_center.y, + position->x - object->object.bounding_sphere_center.x); + } + return TRUE; +} + +/* the bots' searches' walkable surfaces, the structure's to begin with, +less those of a machine its definition calls a pathfinding obstacle (not an +elevator, nor a door open now that is none open) */ +static void bots_prepare_paths(void) +{ + struct object_iterator iterator; + + bots_paths_release(); + object_iterator_new(&iterator, _object_mask_machine, 0); + while (object_iterator_next(&iterator)) + { + struct object_datum *object = object_get(iterator.index); + struct machine_definition *definition = machine_definition_get(object->definition_index); + + if (!TEST_FLAG(definition->machine.flags, _machine_is_pathfinding_obstacle_bit) || + TEST_FLAG(definition->machine.flags, _machine_is_elevator_bit) || + (device_get_position(iterator.index) > 0.5f && + TEST_FLAG(definition->machine.flags, _machine_is_not_pathfinding_obstacle_when_open_bit))) + { + continue; + } + bots_paths_close_object(iterator.index, "a machine in the way:"); + } +} + +/* the places a bot roams to: the item spawns and the player starting +locations (once the level's BSP is in) */ +static void bots_prepare_map(void) +{ + struct scenario *scenario = global_scenario_get(); + long index; + + bots_globals.map_ready = TRUE; + bots_globals.roam_point_count = 0; + bots_prepare_paths(); + bots_navigation_prepare(); + if (!scenario) + return; + for (index = 0; index < scenario->netgame_equipment.count; index++) + { + struct scenario_netgame_equipment *equipment = + TAG_BLOCK_GET_ELEMENT(&scenario->netgame_equipment, index, struct scenario_netgame_equipment); + + bots_add_roam_point(&equipment->position); + } + for (index = 0; index < scenario->players.count; index += 2) + { + struct player_starting_location *location = + TAG_BLOCK_GET_ELEMENT(&scenario->players, index, struct player_starting_location); + + bots_add_roam_point(&location->position); + } + { + real_point3d low = {REAL_MAX, REAL_MAX, REAL_MAX}, high = {-REAL_MAX, -REAL_MAX, -REAL_MAX}; + + for (index = 0; index < bots_globals.roam_point_count; index++) + { + low.x = MIN(low.x, bots_globals.roam_points[index].x); + low.y = MIN(low.y, bots_globals.roam_points[index].y); + high.x = MAX(high.x, bots_globals.roam_points[index].x); + high.y = MAX(high.y, bots_globals.roam_points[index].y); + } + platform_log("bots: %ld places to roam on this map, over %.0f units", bots_globals.roam_point_count, + bots_globals.roam_point_count > 0 ? (double)bots_distance2d(&low, &high) : 0.0); + } +} + +void enhanced_controller_initialize(void) +{ + long index; + + bots_worker_stop(); + bots_navigation_reset(); + bots_powerups_reset(); + bots_worker_enabled = config_boolean("bots.thread"); + enhanced_bots_initialize_for_new_map(); + csmemset(bots_globals.bots, 0, sizeof(bots_globals.bots)); + for (index = 0; index < BOTS_MAXIMUM; index++) + bots_globals.bots[index].player_index = NONE; + bots_globals.search_cursor = 0; + csmemset(bots_globals.search_wait, 0, sizeof(bots_globals.search_wait)); + csmemset(bots_globals.search_seen, 0, sizeof(bots_globals.search_seen)); + bots_globals.map_ready = FALSE; + bots_globals.roam_point_count = 0; + bots_globals.ticks = 0; + bots_globals.searches = 0; + bots_globals.search_failures = 0; + bots_globals.search_partials = 0; + bots_globals.search_overflows = 0; + bots_globals.search_unavoided = 0; + bots_globals.search_unsmoothed = 0; + bots_globals.stuck_events = 0; + bots_globals.stuck_giveups = 0; + csmemset(bots_globals.combat_counts, 0, sizeof(bots_globals.combat_counts)); + /* (the first line a minute into the game) */ + bots_globals.last_report_tick = 0; + /* (the weapon definitions are the new map's) */ + bots_weapon_kinds.count = 0; +} + +void enhanced_controller_dispose(void) +{ + bots_worker_stop(); + bots_navigation_reset(); + bots_powerups_reset(); + enhanced_bots_dispose_from_old_map(); + bots_paths_release(); + if (bots_globals.search) + free(bots_globals.search); + bots_globals.search = NULL; + bots_globals.map_ready = FALSE; +} + +/* ---------- path searches */ + +/* the search's way to its destination (or as near as it came): each +surface's entry point (path_state_build_path's raw steps, at most 64), the +endpoint last. TRUE with steps */ +static boolean bots_path_raw_steps(struct path_state *state, struct path_step *raw_steps, short *raw_step_count, + boolean *steps_finish_path, real_point3d *endpoint) +{ + short node_index, child_index = NONE; + + *steps_finish_path = TRUE; + *raw_step_count = 0; + if (!state->destination_valid || state->node_count <= 0) + return FALSE; + node_index = path_node_from_hash_table(state, state->destination.surface_index); + *endpoint = state->destination.point; + if (node_index == NONE) + { + node_index = state->closest_node_index; + *endpoint = state->closest_point; + } + if (node_index < 0 || node_index >= state->node_count) + return FALSE; + *raw_step_count = (short)MIN(state->node_list[node_index].depth + 1, 64); + while (node_index != NONE) + { + struct path_node *node; + + if (node_index < 0 || node_index >= state->node_count) + return FALSE; + node = &state->node_list[node_index]; + if (node->depth >= 64) + *steps_finish_path = FALSE; + else if (node->depth >= 0 && node->depth < *raw_step_count) + { + raw_steps[node->depth].surface_index = node->surface_index; + raw_steps[node->depth].point = child_index == NONE ? *endpoint : state->node_list[child_index].entry_point; + } + else + return FALSE; + child_index = node_index; + node_index = node->parent_node_index; + } + return *raw_step_count > 0; +} + +/* the path as path_state_build_path makes it, the steps smoothed, but not +taken round the objects about (the obstacle avoidance found no way round: +the other bots crowding a narrow way out of a base, Longest's, all waiting +on each other); the bots push past each other, and one that stops moving +sidesteps and jumps. TRUE with a path */ +static boolean bots_build_path_unavoided(struct path_state *state, struct path_result *path) +{ + struct path_step raw_steps[64]; + struct path_step smoothed_steps[MAXIMUM_SMOOTHED_PATH_STEPS]; + short raw_step_count, smoothed_step_count = 0; + boolean steps_finish_path; + real_point3d endpoint; + + csmemset(path, 0, sizeof(*path)); + if (!bots_path_raw_steps(state, raw_steps, &raw_step_count, &steps_finish_path, &endpoint)) + return FALSE; + path_smooth(state, raw_step_count, raw_steps, &smoothed_step_count, smoothed_steps, &steps_finish_path); + if (smoothed_step_count <= 0) + return FALSE; + smoothed_step_count = MIN(smoothed_step_count, MAXIMUM_SMOOTHED_PATH_STEPS); + path->valid = TRUE; + path->endpoint.point = endpoint; + path->endpoint.surface_index = smoothed_steps[smoothed_step_count - 1].surface_index; + path->steps_finish_path = steps_finish_path; + path->step_count = (char)smoothed_step_count; + path->step_index = 0; + csmemcpy(path->steps, smoothed_steps, smoothed_step_count * sizeof(struct path_step)); + return TRUE; +} + +/* a path that goes nowhere: short of its end, every step where the bot +stands. The smoothing (path_smooth) gave one at the foot of a steep bank: +all four of its steps the same point a few centimetres from the bot, which +it took as reached at once and searched again, the same, while it slid +about (Sidewinder's banks up to the side ledges) */ +static boolean bots_path_stalls(struct path_result const *path, real_point3d const *start) +{ + return path->valid && !path->steps_finish_path && path->step_count > 0 && + bots_distance2d(&path->steps[path->step_count - 1].point, start) <= BOTS_STEP_REACHED; +} + +/* a stalling path's steps instead the search's own, unsmoothed: the next +surfaces' entry points beyond where the bot stands (up the bank), four at +most. TRUE when made */ +static boolean bots_path_unsmoothed(struct path_state *state, real_point3d const *start, struct path_result *path) +{ + struct path_step raw_steps[64]; + short raw_step_count, step, count = 0; + boolean steps_finish_path; + real_point3d endpoint; + struct path_result result; + + if (!bots_path_raw_steps(state, raw_steps, &raw_step_count, &steps_finish_path, &endpoint)) + return FALSE; + csmemset(&result, 0, sizeof(result)); + for (step = 0; step < raw_step_count && count < (short)NUMBEROF(result.steps); step++) + { + if (!count && bots_distance2d(&raw_steps[step].point, start) <= BOTS_STEP_REACHED) + continue; + result.steps[count++] = raw_steps[step]; + } + if (!count) + return FALSE; + result.valid = TRUE; + result.steps_finish_path = steps_finish_path && step >= raw_step_count; + result.step_count = (char)count; + result.endpoint.point = endpoint; + result.endpoint.surface_index = result.steps[count - 1].surface_index; + *path = result; + return TRUE; +} + +/* a search's answer made a path: the way to the goal (or as near as the +search came); when the path's obstacle avoidance finds no way, again with +what the goal or the bot stands on (a flag's stand, a teleporter's base) no +obstacle, and failing that, the scenery and machines about the bot are +learnt to be in the way (the next searches go round them) and this once the +path is taken without the avoidance. TRUE with a path */ +static boolean bots_search_build(struct path_state *state, real_point3d const *start, real_point3d const *goal, + struct path_result *path) +{ + long object_index; + + if (state->node_count <= 0) + return FALSE; + if (path_state_build_path(state, path) && path->step_count > 0) + return TRUE; + object_index = bots_object_at(goal); + if (object_index == NONE) + object_index = bots_object_at(start); + if (object_index != NONE) + { + state->input.ignore_target_object_index = object_index; + csmemset(path, 0, sizeof(*path)); + if (path_state_build_path(state, path) && path->step_count > 0) + return TRUE; + } + /* (something new learnt: a new search, round it) */ + if (bots_paths_learn(start, goal) > 0) + return FALSE; + if (!bots_build_path_unavoided(state, path)) + return FALSE; + bots_globals.search_unavoided++; + return TRUE; +} + +#include "bots_navigation.inl" +#include "bots_worker.inl" + +/* a path from where the bot's unit is to its goal, searched now (a few a +tick: a bot past them asks again next tick), into the bot's path */ +/* Requests expire when a bot stops asking (combat, death or removal). +Oldest requests win; the rotating cursor breaks equal-age ties. */ +static boolean bots_search_turn(long bot_index) +{ + long offset, first = NONE, now = game_time_get(); + bots_globals.search_seen[bot_index] = now; + if (!bots_globals.search_wait[bot_index]) bots_globals.search_wait[bot_index] = now + 1; + for (offset = 0; offset < BOTS_MAXIMUM; offset++) + { + long candidate = (bots_globals.search_cursor + offset) % BOTS_MAXIMUM; + if (now - bots_globals.search_seen[candidate] > 1) bots_globals.search_wait[candidate] = 0; + if (bots_globals.search_wait[candidate] && (first == NONE || + bots_globals.search_wait[candidate] < bots_globals.search_wait[first])) first = candidate; + } + if (bots_globals.tick_searches >= BOTS_SEARCHES_A_TICK || first != bot_index) return FALSE; + bots_globals.search_wait[bot_index] = 0; + bots_globals.search_cursor = (bot_index + 1) % BOTS_MAXIMUM; + return TRUE; +} + +static void bots_search(struct bots_bot *bot, long unit_index) +{ + struct path_state *state; + struct path_input input; + struct path_result path; + real_point3d start, goal = bot->goal_point; + long start_surface_index, goal_surface = bot->goal_surface_index; + long bot_index = (long)(bot - bots_globals.bots); + boolean reached, waypoint = FALSE, navigation = FALSE; + real radius = BOTS_PATH_RADIUS; + struct bots_path_job *job = bots_worker_job(bot); + + if (bot->goal_surface_index == NONE) + return; + if (!job && !bots_search_turn(bot_index)) return; + if (!bots_globals.search) + { + bots_globals.search = (struct path_state *)malloc(sizeof(struct path_state)); + if (!bots_globals.search) + return; + } + state = bots_globals.search; + if (job) + { + if (WaitForSingleObject(job->done, 0) != WAIT_OBJECT_0) + return; + *state = job->state; + state->structure = job->original_structure; + start = job->start; + goal = job->goal; + goal_surface = job->goal_surface; + waypoint = job->waypoint; + navigation = job->navigation; + radius = job->radius; + job->pending = FALSE; + goto answered; + } + unit_index = bots_vehicle_navigation(unit_index, &radius); + start_surface_index = bots_unit_surface(unit_index, &start); + if (start_surface_index == NONE) + return; + /* (on a surface closed to the searches, whose way out may be closed + too: away from what closed it first, a second) */ + if (bots_paths.walkable && start_surface_index < bots_paths.structure.pathfinding_surfaces.count && + !TEST_FLAG(bots_paths.walkable[start_surface_index], BOTS_PATHFINDING_WALKABLE_BIT) && + bots_paths_escape_direction(&start, &bot->escape_direction)) + { + bot->escape_until_tick = game_time_get() + TICKS_PER_SECOND; + bot->path.valid = FALSE; + bot->path_tick = game_time_get(); + return; + } + bots_globals.tick_searches++; + bots_globals.searches++; + bot->searches++; + if (bot->goal_kind != _bots_goal_item && bot->goal_kind != _bots_goal_vehicle && radius == BOTS_PATH_RADIUS) + waypoint = bots_routes_search_goal(bot_index, &start, &goal, &goal_surface); + if (radius == BOTS_PATH_RADIUS) + navigation = bots_navigation_query(bot, &start, &start_surface_index, &goal, &goal_surface); + path_input_new(&input, radius, FALSE, unit_index); + if (bot->goal_kind == _bots_goal_vehicle) + input.ignore_target_object_index = bots_vehicle_sought(bot_index); + path_input_set_start(&input, &start, start_surface_index); + path_state_new(&input, state, NULL); + /* (the walkable surfaces less those closed by what is in the way) */ + if (bots_paths_copy() && state->structure == bots_paths.source) + state->structure = &bots_paths.structure; + if (radius > BOTS_PATH_RADIUS) + { + struct structure_bsp *vehicle_structure = bots_navigation_vehicle_structure(); + if (vehicle_structure) + state->structure = vehicle_structure; + } + /* (a path to as near the goal as the search reaches: a long way across a + large level is more surfaces than a search holds, and the bot searches + again from there) */ + path_state_destination(state, &goal, goal_surface, 1000.0f); + if (bots_worker_submit(bot, state, &start, &goal, goal_surface, waypoint, navigation, radius)) + return; + path_state_find(state); +answered: + reached = state->node_count > 0 && path_node_from_hash_table(state, goal_surface) != NONE; + if (state->node_count >= PATH_NODE_LIST_SIZE) + bots_globals.search_overflows++; + if (!reached) + bots_globals.search_partials++; + if (bots_navigation_answer(bot, state, &start, reached, waypoint, radius)) + return; + csmemset(&path, 0, sizeof(path)); + if (bots_search_build(state, &start, &goal, &path)) + { + if (bots_path_stalls(&path, &start) && bots_path_unsmoothed(state, &start, &path)) + bots_globals.search_unsmoothed++; + bot->path = path; + bot->path.step_index = 0; + bot->path_failures = 0; + bot->path_short = !reached && !waypoint && !navigation; + if (!bot->path_short) + bot->climb_until_tick = 0; + } + else + { + bot->path.valid = FALSE; + bot->path_failures++; + bots_globals.search_failures++; + if (bot->path_failures >= 3) + bots_goal_failed(bot); + } + if (!navigation && bots_tactics_search_answer(bot_index, &goal, reached, state->node_count < PATH_NODE_LIST_SIZE)) + bot->path.valid = FALSE; + /* (an item it finds no way to: another, and not this one a while) */ + if (bot->goal_kind == _bots_goal_item && !reached) + { + bots_item_set_unreachable(bot, bot->item_index); + bot->goal_kind = _bots_goal_none; + bot->path.valid = FALSE; + } + bot->path_tick = game_time_get(); + if ((bots_navigation.routes[bot_index].phase == _bots_nav_exit || + bots_navigation.routes[bot_index].phase == _bots_nav_entry)) + bot->path_tick -= 4 * TICKS_PER_SECOND + 1; +} + +/* ---------- perception */ + +/* whether the bot sees the point from its eyes (the AI's sight test) */ +static boolean bots_line_of_sight(long unit_index, real_point3d const *eye, real_point3d const *point, + long target_unit_index) +{ + struct collision_result collision; + real_vector3d vector; + + vector.i = point->x - eye->x; + vector.j = point->y - eye->y; + vector.k = point->z - eye->z; + if (!collision_test_vector(_collision_test_for_line_of_sight_flags, eye, &vector, unit_index, &collision)) + return TRUE; + /* (the target's vehicle: seen) */ + if (collision.type == _collision_result_object && target_unit_index != NONE && + (collision.object_index == target_unit_index || + collision.object_index == object_get(target_unit_index)->object.parent_object_index)) + { + return TRUE; + } + return FALSE; +} + +static boolean bots_is_enemy(struct player_datum *player, struct player_datum *other) +{ + if (player == other || other->unit_index == NONE) + return FALSE; + if (game_engine_has_teams() && player->team_index == other->team_index) + return FALSE; + return TRUE; +} + +/* the enemy the bot sees best now, NONE for none: of the enemies in its +sight's reach and view, the one of the least score (nearest, most ahead, the +one it fights favoured) a line of sight reaches, the first in the players' +order of those of that score. The enemies are scored first and their lines +of sight cast from the least score up, until one reaches its enemy, which is +the answer. A score that is not a number (none is: the players' positions +are), or more enemies than kept, take the players' order */ +struct bots_target_candidate +{ + long player_index; + long unit_index; + real score; + real_point3d point; +}; + +/* an enemy's score as a target (its point the bounding sphere's centre); +FALSE for one out of reach or view, or not an enemy */ +static boolean bots_target_score(struct bots_bot *bot, struct player_datum *player, struct player_datum *other, + long player_index, real_point3d const *eye, struct bots_skill_definition const *skill, + boolean hurt, struct bots_target_candidate *candidate) +{ + struct object_datum *object; + struct unit_datum *other_unit; + real distance, reach, bearing; + real half_view = 0.5f * skill->field_of_view_degrees * BOTS_DEGREES; + + if (!bots_is_enemy(player, other)) + return FALSE; + object = object_get(other->unit_index); + other_unit = unit_get(other->unit_index); + if (TEST_FLAG(object->object.damage_flags, _object_dead_bit)) + return FALSE; + candidate->point = object->object.bounding_sphere_center; + distance = bots_distance3d(eye, &candidate->point); + reach = skill->sight_distance; + reach *= bots_tactics_sight_scale((long)(bot - bots_globals.bots)); + /* (active camouflage: seen only close) */ + if (TEST_FLAG(other_unit->unit.flags, _unit_active_camouflaged_bit)) + reach *= 0.3f; + /* (the one it fights: a little further) */ + if (player_index == bot->target_player_index) + reach *= 1.25f; + if (distance > reach) + return FALSE; + bearing = (real)fabs( + bots_angle_difference((real)atan2(candidate->point.y - eye->y, candidate->point.x - eye->x), bot->yaw)); + /* (out of view: unless close by, it shot the bot, or it is the one + the bot fights) */ + if (bearing > half_view && distance > 3.0f && !hurt && player_index != bot->target_player_index) + return FALSE; + /* (nor far above or below where it looks, on the same terms: a player + running by looks ahead, not up) */ + if (distance > 3.0f && !hurt && player_index != bot->target_player_index) + { + real dx = candidate->point.x - eye->x, dy = candidate->point.y - eye->y; + real elevation = (real)atan2(candidate->point.z - eye->z, (real)sqrt(dx * dx + dy * dy)); + + if (!bots_combat_in_vertical_view(bots_globals.skill, elevation / BOTS_DEGREES, bot->pitch / BOTS_DEGREES)) + { + bots_globals.combat_counts[_bots_combat_count_out_of_view]++; + return FALSE; + } + } + candidate->player_index = player_index; + candidate->unit_index = other->unit_index; + candidate->score = distance + bearing * 4.0f - (player_index == bot->target_player_index ? 6.0f : 0.0f); + candidate->score -= enhanced_bots_target_priority(player, player_index); + return TRUE; +} + +static long bots_find_target(struct bots_bot *bot, struct player_datum *player, real_point3d const *eye) +{ + struct bots_skill_definition const *skill = &bots_skills[bots_globals.skill]; + struct data_iterator iterator; + struct player_datum *other; + boolean hurt = game_time_get() - bot->hurt_tick < TICKS_PER_SECOND * 2; + struct bots_target_candidate candidates[BOTS_MAXIMUM + MAXIMUM_LOCAL_PLAYERS]; + long candidate_count = 0, index; + boolean ordered = TRUE; + + data_iterator_new(&iterator, player_data); + while ((other = (struct player_datum *)data_iterator_next(&iterator)) != NULL && ordered) + { + if (candidate_count >= (long)NUMBEROF(candidates)) + ordered = FALSE; + else if (bots_target_score(bot, player, other, iterator.datum_index, eye, skill, hurt, + &candidates[candidate_count])) + { + real score = candidates[candidate_count].score; + + if (score != score) + ordered = FALSE; + else if (score < REAL_MAX) + candidate_count++; + } + } + if (!ordered) + { + /* (the players' order, each scoring less than the best so far) */ + struct bots_target_candidate candidate; + long best_index = NONE; + real best_score = REAL_MAX; + + data_iterator_new(&iterator, player_data); + while ((other = (struct player_datum *)data_iterator_next(&iterator)) != NULL) + { + if (!bots_target_score(bot, player, other, iterator.datum_index, eye, skill, hurt, &candidate) || + candidate.score >= best_score || + !bots_line_of_sight(player->unit_index, eye, &candidate.point, candidate.unit_index)) + { + continue; + } + best_score = candidate.score; + best_index = candidate.player_index; + } + return best_index; + } + while (candidate_count > 0) + { + long least = 0; + + /* (the least score, the first of it in the players' order) */ + for (index = 1; index < candidate_count; index++) + { + if (candidates[index].score < candidates[least].score) + least = index; + } + if (bots_line_of_sight(player->unit_index, eye, &candidates[least].point, candidates[least].unit_index)) + return candidates[least].player_index; + /* (out, the others kept in their order) */ + candidate_count--; + for (index = least; index < candidate_count; index++) + candidates[index] = candidates[index + 1]; + } + return NONE; +} + +/* ---------- moving */ + +static void bots_set_goal(struct bots_bot *bot, short kind, real_point3d const *point, long surface_index) +{ + /* (the same goal, near enough: the path stands) */ + if (bot->goal_kind == kind && bot->goal_surface_index == surface_index && + bots_distance3d(&bot->goal_point, point) < 1.5f) + { + return; + } + if (kind != _bots_goal_vehicle) + { + bot->intent_point = *point; + } + bot->goal_serial++; + bot->goal_kind = kind; + bot->goal_point = *point; + bot->goal_surface_index = surface_index; + bot->goal_tick = game_time_get(); + bot->path.valid = FALSE; + bot->path_failures = 0; + bot->climb_until_tick = 0; +} + +static void bots_goal_failed(struct bots_bot *bot) +{ + long index = (long)(bot - bots_globals.bots); + if (bot->goal_kind == _bots_goal_enhanced) + { + bot->objective_retry_tick = game_time_get() + 10 * TICKS_PER_SECOND; + enhanced_bots_failed(index); + } + if (bot->goal_kind == _bots_goal_vehicle) + bots_vehicle_cancel(index); + bot->goal_serial++; + bot->goal_kind = _bots_goal_none; + bot->path.valid = FALSE; + bots_navigation_reset_bot(index); +} + +/* a roaming place picked at random (index), or a higher one (VETERAN and +up): two more places at random, not within 6 units, +and the one of the most credit for its height above the bot */ +static short bots_roam_higher(struct bots_bot *bot, real_point3d const *position, short index) +{ + short best = index, tries; + real best_credit = bots_combat_high_ground(bots_globals.skill, bots_globals.roam_points[index].z - position->z); + + if (bots_globals.skill < _bots_skill_veteran) + return index; + for (tries = 0; tries < 2; tries++) + { + short other = (short)(bots_random(bot) % (unsigned long)bots_globals.roam_point_count); + real credit; + + if (bots_distance2d(&bots_globals.roam_points[other], position) < 6.0f) + continue; + credit = bots_combat_high_ground(bots_globals.skill, bots_globals.roam_points[other].z - position->z); + if (credit > best_credit) + { + best_credit = credit; + best = other; + } + } + if (best != index) + bots_globals.combat_counts[_bots_combat_count_high_ground]++; + return best; +} + +/* the next place to roam to: most often towards an enemy (the roaming place +nearest a living enemy, as a player knows where the other team's base is +and reads the motion tracker), else anywhere */ +static void bots_pick_roam_goal(struct bots_bot *bot, real_point3d const *position) +{ + long tries; + + if (bots_globals.roam_point_count <= 0) + return; + bot->hunting = FALSE; + if (bots_random_real(bot) < bots_combat_hunt_chance(bots_globals.skill)) + { + struct player_datum *player = player_get(bot->player_index); + struct data_iterator iterator; + struct player_datum *other; + long enemies[BOTS_MAXIMUM + MAXIMUM_LOCAL_PLAYERS]; + long enemy_count = 0; + + data_iterator_new(&iterator, player_data); + while ((other = (struct player_datum *)data_iterator_next(&iterator)) != NULL && + enemy_count < (long)NUMBEROF(enemies)) + { + if (bots_is_enemy(player, other)) + enemies[enemy_count++] = other->unit_index; + } + if (enemy_count > 0) + { + struct object_datum *enemy = object_get(enemies[bots_random(bot) % (unsigned long)enemy_count]); + long index, nearest = NONE; + real nearest_distance = REAL_MAX; + + for (index = 0; index < bots_globals.roam_point_count; index++) + { + real distance = bots_distance2d(&bots_globals.roam_points[index], &enemy->object.position) + + bots_random_real(bot) * 6.0f; + + /* (a place above the enemy counts as nearer, from veteran) */ + distance -= bots_combat_high_ground(bots_globals.skill, + bots_globals.roam_points[index].z - enemy->object.position.z); + + if (distance < nearest_distance && bots_distance2d(&bots_globals.roam_points[index], position) > 4.0f) + { + nearest_distance = distance; + nearest = index; + } + } + if (nearest != NONE) + { + bot->roam_index = (short)nearest; + bot->hunting = TRUE; + bots_set_goal(bot, _bots_goal_roam, &bots_globals.roam_points[nearest], + bots_globals.roam_surfaces[nearest]); + return; + } + } + } + for (tries = 0; tries < 6; tries++) + { + short index = (short)(bots_random(bot) % (unsigned long)bots_globals.roam_point_count); + + /* (not where it is) */ + if (bots_distance2d(&bots_globals.roam_points[index], position) < 6.0f && tries < 5) + continue; + index = bots_roam_higher(bot, position, index); + bot->roam_index = index; + bots_set_goal(bot, _bots_goal_roam, &bots_globals.roam_points[index], bots_globals.roam_surfaces[index]); + return; + } +} + +#include "bots_powerups.inl" + +/* where the bot goes: the enemy last seen, a better weapon near, or about +the map */ +static void bots_choose_goal(struct bots_bot *bot, long player_index, real_point3d const *position, boolean fighting) +{ + long now = game_time_get(); + real_point3d goal; + long surface; + long index = (long)(bot - bots_globals.bots); + + if (enhanced_bots_carrying(index)) + bots_vehicle_cancel(index); + else if (bots_vehicle_seeking(index)) + { + if (bots_vehicle_goal(index, player_get(player_index)->unit_index, &bot->intent_point, &goal, &surface)) + { + bots_set_goal(bot, _bots_goal_vehicle, &goal, surface); + return; + } + } + if (!enhanced_bots_carrying(index) && !enhanced_bots_holding_hill(player_get(player_index)->unit_index) && + bots_vehicle_parent(player_get(player_index)->unit_index) == NONE && + bots_vehicle_player_goal(index, player_get(player_index)->unit_index, &bot->intent_point, &goal, &surface)) + { + bots_set_goal(bot, _bots_goal_vehicle, &goal, surface); + return; + } + if (!enhanced_bots_carrying(index) && !enhanced_bots_holding_hill(player_get(player_index)->unit_index) && + bots_vehicle_parent(player_get(player_index)->unit_index) == NONE && + bots_powerup_goal(bot, unit_get(player_get(player_index)->unit_index), position, fighting)) + return; + if ((now >= bot->objective_retry_tick || enhanced_bots_carrying(index)) && + enhanced_bots_goal(index, player_index, position, TRUE, &goal, &surface) && + (!bots_vehicle_seeking(index) || enhanced_bots_carrying(index))) + { + bots_set_goal(bot, _bots_goal_enhanced, &goal, surface); + return; + } + if (game_engine_get_variant()->game_engine_index == game_engine_slayer && !fighting && + bot->target_player_index != NONE && bot->target_last_surface_index != NONE && + now - bot->target_seen_tick < TICKS_PER_SECOND * 8) + { + bots_set_goal(bot, _bots_goal_enemy, &bot->target_last_position, bot->target_last_surface_index); + return; + } + /* a better weapon near (looked for once a second; given up after a + while) */ + if (bot->goal_kind == _bots_goal_item) + { + struct item_datum *item = + (struct item_datum *)object_try_and_get_and_verify_type(bot->item_index, _object_mask_item); + + if (item && item->object.parent_object_index == NONE && now - bot->goal_tick < TICKS_PER_SECOND * 15 && + (bot->item_first_press_tick < bot->goal_tick || now - bot->item_first_press_tick < TICKS_PER_SECOND * 3)) + { + return; + } + /* (one it did not get, standing on it or not: left be a while) */ + if (item && item->object.parent_object_index == NONE) + bots_item_set_unreachable(bot, bot->item_index); + bot->goal_kind = _bots_goal_none; + bot->item_check_tick = now + TICKS_PER_SECOND * 2; + } + if (now >= bot->item_check_tick && (bots_vehicle_parent(player_get(player_index)->unit_index) == NONE)) + { + long item_index = + bots_find_item(bot, unit_get(player_get(player_index)->unit_index), position, fighting ? 8.0f : 20.0f); + + bot->item_check_tick = now + TICKS_PER_SECOND; + if (item_index != NONE) + { + real_point3d ground; + long surface_index = bots_surface_below(&object_get(item_index)->object.position, &ground); + + if (surface_index != NONE) + { + bots_set_goal(bot, _bots_goal_item, &ground, surface_index); + bot->item_index = item_index; + return; + } + } + } + if (!fighting && now >= bot->objective_retry_tick && + enhanced_bots_goal(index, player_index, position, FALSE, &goal, &surface)) + { + bots_set_goal(bot, _bots_goal_enhanced, &goal, surface); + return; + } + if (fighting && bot->goal_kind != _bots_goal_none) + return; + if (bot->goal_kind != _bots_goal_roam || bots_distance2d(&bot->goal_point, position) < 1.5f || + now - bot->goal_tick > TICKS_PER_SECOND * (bot->hunting ? 12 : 40)) + { + bots_pick_roam_goal(bot, position); + } +} + +/* the direction the bot walks (radians), following its path; FALSE when +it has nowhere to go */ +static boolean bots_follow_path(struct bots_bot *bot, long unit_index, real_point3d const *position, real *direction) +{ + long now = game_time_get(); + real step_reached = BOTS_STEP_REACHED, radius = BOTS_PATH_RADIUS; + if (bots_vehicle_navigation(unit_index, &radius) != unit_index) + step_reached = 2.5f; + else if (bots_vehicle_parent(unit_index) != NONE) + return FALSE; /* Passengers do not request pedestrian paths. */ + + if (bot->goal_kind == _bots_goal_none || bots_vehicle_flying(unit_index)) + return FALSE; + if (bots_routes_waypoint_reached((long)(bot - bots_globals.bots), position)) + { + bot->path.valid = FALSE; + bot->path_tick = now - TICKS_PER_SECOND; + } + if (bots_navigation_follow(bot, position, direction)) + return TRUE; + if (now < bot->escape_until_tick) + { + *direction = bot->escape_direction; + return TRUE; + } + /* (at the end of a path short of its goal: straight on, jumping, while + it comes nearer (the walkable surfaces miss ramps a biped walks up: + Prisoner's, Wizard's); then somewhere else) */ + if (radius == BOTS_PATH_RADIUS && bot->climb_until_tick) + { + real distance = bots_distance3d(&bot->goal_point, position); + + if (distance < bot->climb_best_distance - 0.5f && now - bot->climb_start_tick < TICKS_PER_SECOND * 20) + { + bot->climb_best_distance = distance; + bot->climb_until_tick = now + TICKS_PER_SECOND * 3; + } + if (now < bot->climb_until_tick && distance > 1.0f) + { + *direction = (real)atan2(bot->goal_point.y - position->y, bot->goal_point.x - position->x); + return TRUE; + } + bot->climb_until_tick = 0; + if (distance > 1.0f) + { + bots_goal_failed(bot); + return FALSE; + } + } + /* (a new path now and then: the objects about move, and the goal) */ + if ((!bot->path.valid || now - bot->path_tick > TICKS_PER_SECOND * 4) && + now - bot->path_tick > TICKS_PER_SECOND / 3) + { + bots_search(bot, unit_index); + } + if (bot->path.valid) + { + while (bot->path.step_index < bot->path.step_count) + { + struct path_step *step = &bot->path.steps[(long)bot->path.step_index]; + + if (bots_distance2d(&step->point, position) > step_reached || fabs(step->point.z - position->z) > MAX(1.5f, radius)) + break; + bot->path.step_index++; + } + if (bot->path.step_index >= bot->path.step_count) + { + bot->path.valid = FALSE; + /* (as near as the search came, the goal on above or beyond: + on towards it) */ + if (radius == BOTS_PATH_RADIUS && bot->path.steps_finish_path && bot->path_short && + bots_distance3d(&bot->goal_point, position) > 1.5f && !bot->climb_until_tick) + { + bot->climb_start_tick = now; + bot->climb_until_tick = now + TICKS_PER_SECOND * 3; + bot->climb_best_distance = bots_distance3d(&bot->goal_point, position); + *direction = (real)atan2(bot->goal_point.y - position->y, bot->goal_point.x - position->x); + return TRUE; + } + /* (the whole way walked: there) */ + if (bot->path.steps_finish_path) + { + if (bots_navigation_follow(bot, position, direction)) + return TRUE; + return FALSE; + } + bots_search(bot, unit_index); + } + else + { + struct path_step *step = &bot->path.steps[(long)bot->path.step_index]; + + *direction = (real)atan2(step->point.y - position->y, step->point.x - position->x); + return TRUE; + } + } + /* A ground vehicle waits for a usable route; pedestrian recovery must + not drive a wide hull directly through blocked terrain. */ + if (radius != BOTS_PATH_RADIUS) return FALSE; + /* (no path yet, or none found: straight there) */ + { + struct bots_nav_route *route = &bots_navigation.routes[bot - bots_globals.bots]; + if (route->phase == _bots_nav_going) + { + real_point3d const *entry = &bots_navigation.links[route->link].entrance; + *direction = (real)atan2(entry->y - position->y, entry->x - position->x); + return TRUE; + } + } + if (bots_distance2d(&bot->goal_point, position) < 1.0f) + return FALSE; + *direction = (real)atan2(bot->goal_point.y - position->y, bot->goal_point.x - position->x); + return TRUE; +} + +/* ---------- a bot's tick */ + +static void bots_bot_reset(struct bots_bot *bot, long player_index, long bot_index) +{ + csmemset(bot, 0, sizeof(*bot)); + bot->player_index = player_index; + bot->unit_index = NONE; + bot->powerup_index = NONE; + bot->target_player_index = NONE; + bot->target_last_surface_index = NONE; + bot->goal_surface_index = NONE; + bot->random = 0x2545F491UL * (unsigned long)(bot_index + 1) ^ (unsigned long)network_game_get_random_seed(); + bot->strafe_sign = 1.0f; + enhanced_bots_reset(bot_index, player_index); +} + +/* a bot's tick: what it knows of itself, and the controls it builds */ +struct bots_tick +{ + struct bots_skill_definition const *skill; + struct player_datum *player; + struct unit_datum *unit; + struct object_datum *object; + long now; + /* the unit's eyes (its head marker), found when first needed: the look + (every third tick) and the fight (bots_tick_eye) */ + boolean eye_found; + real_point3d eye; + real_point3d position; + long weapon_index; + /* the controls: buttons, where it walks, how hard */ + unsigned long flags; + boolean moving; + real move_direction; + real throttle_scale; + /* it has a target in sight, this far away */ + boolean fighting; + real target_distance; + struct player_action *action; +}; + +/* the unit's eyes: its head marker, as unit_get_head_position finds it +(the marker's matrix from the object's node matrices, which nothing in the +bot's tick changes, so it is the same found now or at the tick's start) */ +static real_point3d const *bots_tick_eye(struct bots_tick *tick) +{ + if (!tick->eye_found) + { + unit_get_head_position(tick->player->unit_index, &tick->eye); + tick->eye_found = TRUE; + } + return &tick->eye; +} + +/* ---------- fighting by level (bots_combat.c's rules) */ + +/* a bot's fight started over (a spawn) */ +static void bots_level_reset(struct bots_bot_combat *combat) +{ + long index; + + csmemset(combat, 0, sizeof(*combat)); + bots_combat_retreat_reset(&combat->retreat); + combat->last_fight_tick = -TICKS_PER_SECOND * 10; + combat->melee_ready_tick = NONE; + combat->pace_since_tick = NONE; + combat->prenade_seen_tick = NONE; + for (index = 0; index < BOTS_TRACK_TICKS; index++) + combat->track[index].tick = NONE; +} + +/* the aim point (its target's middle now) where the target was the level's +delay ago (RECRUIT and EASY), so that a target that turns back is missed a +moment, as a person misses it; the places kept a tick each */ +static void bots_level_trail(struct bots_bot *bot, long now, real_point3d *aim_point) +{ + struct bots_bot_combat *combat = &bot->combat; + long delay = bots_combat_track_delay_ticks(bots_globals.skill); + long slot; + + if (now < 0) + return; + slot = now % BOTS_TRACK_TICKS; + combat->track[slot].tick = now; + combat->track[slot].player_index = bot->target_player_index; + combat->track[slot].point = *aim_point; + if (delay <= 0 || delay >= BOTS_TRACK_TICKS || now < delay) + return; + slot = (now - delay) % BOTS_TRACK_TICKS; + if (combat->track[slot].tick == now - delay && combat->track[slot].player_index == bot->target_player_index) + *aim_point = combat->track[slot].point; +} + +/* With a grenade in hand, lead the target by its flight, at most 3.5 units. +Enhanced aiming owns head and feet selection separately. */ +static void bots_level_aim_point(struct bots_bot *bot, struct bots_tick *tick, long target_unit_index, + real_point3d *aim_point) +{ + struct bots_bot_combat *combat = &bot->combat; + struct object_datum *target = object_get(target_unit_index); + /* Enhanced head/SWAT/feet policy owns the aim override. */ + if (tick->now < combat->throw_until_tick && combat->throw_lead > 0.0f) + { + struct unit_definition *definition = unit_definition_get(tick->object->definition_index); + real speed = definition->unit.grenade_velocity / (real)TICKS_PER_SECOND; + real ticks, dx, dy, lead; + + if (speed < 0.05f) + speed = 0.6f; + ticks = MIN(8.0f + bots_distance2d(bots_tick_eye(tick), aim_point) / speed, 60.0f) * combat->throw_lead; + dx = target->object.translational_velocity.i * ticks; + dy = target->object.translational_velocity.j * ticks; + lead = (real)sqrt(dx * dx + dy * dy); + if (lead > 3.5f) + { + dx *= 3.5f / lead; + dy *= 3.5f / lead; + } + aim_point->x += dx; + aim_point->y += dy; + } +} + +/* the aim error once settled: RECRUIT's wander that never settles; and, +for a far target, at least the level's floor (pushed out to 0 to 30% past it, +on its side), so that a shot from far off misses about half the time */ +static void bots_level_aim_error(struct bots_bot *bot, struct bots_tick *tick) +{ + real *errors[2]; + real const scale[2] = { 1.0f, 0.6f }; + real floor = bots_combat_range_error_floor(bots_globals.skill, tick->target_distance) * BOTS_DEGREES; + short index; + + errors[0] = &bot->aim_error_yaw; + errors[1] = &bot->aim_error_pitch; + for (index = 0; index < 2; index++) + { + real random = bots_random_signed(bot); + + *errors[index] = bots_combat_aim_wander(bots_globals.skill, *errors[index] / BOTS_DEGREES, scale[index], random) * + BOTS_DEGREES; + if (floor > 0.0f && (real)fabs(*errors[index]) < floor * scale[index]) + { + real sign = *errors[index] > 0.0f ? 1.0f : *errors[index] < 0.0f ? -1.0f : random < 0.0f ? -1.0f : 1.0f; + + *errors[index] = sign * floor * scale[index] * (1.0f + 0.3f * (real)fabs(random)); + } + } +} + +/* whether the bot may fire now (NORMAL and up): the sniper rifle zoomed at +a target past 6 units, zoomed again a moment after a hit took the zoom (and +not fired past 10 units meanwhile); the pistol paced at range, its shot held +while its error is over the level's limit, a few ticks at most */ +static boolean bots_level_may_fire(struct bots_bot *bot, struct bots_tick *tick) +{ + struct bots_bot_combat *combat = &bot->combat; + struct bots_weapon_kind const *kind; + short skill = bots_globals.skill; + + /* (a vehicle's gun: as ever) */ + if (tick->weapon_index == NONE || tick->object->object.parent_object_index != NONE) + return TRUE; + kind = bots_weapon_kind(weapon_get(tick->weapon_index)->definition_index); + if (kind->sniper) + { + boolean zooms = bots_combat_zooms(skill, tick->target_distance); + + /* (hurt while zoomed: the game took the zoom) */ + if (bot->hurt_tick == tick->now && tick->unit->unit.current_zoom_level == NONE && + tick->now >= combat->rescope_until_tick && zooms) + { + combat->rescope_until_tick = tick->now + bots_combat_rescope_ticks(skill, bots_random_real(bot)); + bots_globals.combat_counts[_bots_combat_count_rescopes]++; + } + if (tick->now < combat->rescope_until_tick) + return (boolean)!bots_combat_unzoomed_holds_fire(tick->target_distance); + if (zooms) + tick->action->desired_zoom_level = 0; + return TRUE; + } + if (kind->precision && kind->blooms && + bots_combat_pace_holds(skill, tick->target_distance, weapon_get(tick->weapon_index)->weapon.triggers[0].error, + combat->pace_since_tick == NONE ? 0 : tick->now - combat->pace_since_tick)) + { + if (combat->pace_since_tick == NONE) + { + combat->pace_since_tick = tick->now; + bots_globals.combat_counts[_bots_combat_count_paced]++; + } + return FALSE; + } + combat->pace_since_tick = NONE; + return TRUE; +} + +/* whether a unit has its back to a point (it faces more than 114.6 degrees +away from it) */ +static boolean bots_unit_back_turned(long unit_index, real_point3d const *point) +{ + struct object_datum *object = (struct object_datum *)object_try_and_get_and_verify_type(unit_index, _object_mask_unit); + real dx, dy, length, forward_length; + + if (!object) + return FALSE; + dx = point->x - object->object.position.x; + dy = point->y - object->object.position.y; + length = (real)sqrt(dx * dx + dy * dy); + forward_length = (real)sqrt(object->object.forward.i * object->object.forward.i + + object->object.forward.j * object->object.forward.j); + if (length < 0.01f || forward_length < 0.01f) + return FALSE; + return (dx * object->object.forward.i + dy * object->object.forward.j) / (length * forward_length) < -0.416f; +} + +/* whether the bot strikes now: within the level's reach it waits the +level's moment first; a blow it chose not to strike is asked again a second +later */ +static boolean bots_level_melee(struct bots_bot *bot, struct bots_tick *tick, long target_unit_index) +{ + struct bots_bot_combat *combat = &bot->combat; + int choice = bots_combat_melee(bots_globals.skill, tick->target_distance, tick->now >= bot->melee_tick, + bots_unit_back_turned(target_unit_index, &tick->position), object_get(target_unit_index)->object.shield_vitality, + combat->charging, bots_random_real(bot)); + + if (choice == 0) + { + combat->melee_ready_tick = NONE; + return FALSE; + } + if (combat->melee_ready_tick == NONE) + combat->melee_ready_tick = tick->now + bots_combat_melee_delay(bots_globals.skill, bots_random_real(bot)); + if (tick->now < combat->melee_ready_tick) + return FALSE; + combat->melee_ready_tick = NONE; + if (choice == 2) + { + bot->melee_tick = tick->now + TICKS_PER_SECOND; + bots_globals.combat_counts[_bots_combat_count_blows_held]++; + return FALSE; + } + bots_globals.combat_counts[_bots_combat_count_blows]++; + return TRUE; +} + +/* a grenade by the level's rules (the throw's aim leads the target's path +while it is in the hand, from HEROIC) */ +static void bots_level_grenade(struct bots_bot *bot, struct bots_tick *tick, long reaction_ticks) +{ + struct bots_bot_combat *combat = &bot->combat; + short skill = bots_globals.skill; + long now = tick->now; + boolean has = tick->unit->unit.grenade_counts[0] > 0 || tick->unit->unit.grenade_counts[1] > 0; + + if (now < bot->grenade_tick || !has) + return; + if (!bots_combat_grenade(skill, tick->target_distance, has, now - bot->target_first_seen_tick >= reaction_ticks, + now - bot->target_first_seen_tick < TICKS_PER_SECOND * 3 / 2, + bots_combat_about_to_die(tick->object->object.shield_vitality, tick->object->object.body_vitality), + bots_skills[skill].grenade_chance, bots_random_real(bot))) + { + return; + } + tick->flags |= FLAG(_unit_control_throw_grenade_bit); + if (tick->unit->unit.grenade_counts[(long)tick->unit->unit.current_grenade_index] <= 0) + tick->action->desired_grenade_index = tick->unit->unit.grenade_counts[0] > 0 ? 0 : 1; + bot->grenade_tick = now + bots_combat_grenade_cooldown(skill, bots_random_real(bot)); + combat->throw_until_tick = now + TICKS_PER_SECOND / 2; + combat->throw_lead = bots_combat_grenade_lead(skill); + bots_globals.combat_counts[_bots_combat_count_grenades]++; +} + +/* a place to back off to: a roaming place 5 to 35 units off, not towards the +target, the furthest from the target for the least way; FALSE for none */ +static boolean bots_level_retreat_goal(struct bots_bot *bot, struct bots_tick *tick, real_point3d const *target) +{ + long index, best = NONE; + real best_score = -REAL_MAX; + real tx = target->x - tick->position.x, ty = target->y - tick->position.y; + real target_distance = (real)sqrt(tx * tx + ty * ty); + + for (index = 0; index < bots_globals.roam_point_count; index++) + { + real_point3d const *point = &bots_globals.roam_points[index]; + real px = point->x - tick->position.x, py = point->y - tick->position.y; + real distance = (real)sqrt(px * px + py * py); + real score; + + if (distance < 5.0f || distance > 35.0f || bots_globals.roam_surfaces[index] == NONE) + continue; + if (target_distance > 0.01f && (px * tx + py * ty) > 0.3f * distance * target_distance) + continue; + score = bots_distance2d(point, target) - 0.6f * distance; + if (score > best_score) + { + best_score = score; + best = index; + } + } + if (best == NONE) + return FALSE; + bot->roam_index = (short)best; + bot->hunting = FALSE; + bots_set_goal(bot, _bots_goal_roam, &bots_globals.roam_points[best], bots_globals.roam_surfaces[best]); + return TRUE; +} + +/* the fight's moves by level, after the strafe: halts (it stands, keeping +its weapon's distance, at a fight's start and now and then at a new strafe), +a retreat along a path when losing (still shooting; not back to where the +enemy was), a run in to finish a won fight, a step in for a blow, jumps at +the level's rhythm */ +static void bots_level_move(struct bots_bot *bot, struct bots_tick *tick, struct object_datum *target) +{ + struct bots_bot_combat *combat = &bot->combat; + short skill = bots_globals.skill; + long now = tick->now; + real_point3d const *target_point = &target->object.bounding_sphere_center; + real to_target = (real)atan2(target_point->y - tick->position.y, target_point->x - tick->position.x); + real own_shield = tick->object->object.shield_vitality; + real target_shield = target->object.shield_vitality; + real confidence = bots_combat_confidence(own_shield, tick->object->object.body_vitality, target_shield, + target->object.body_vitality, tick->target_distance, bots_weapon_range(tick->weapon_index), + tick->weapon_index != NONE ? bots_weapon_loaded(tick->weapon_index) : 1.0f, + tick->object->object.bounding_sphere_center.z - target_point->z); + boolean new_fight = now - combat->last_fight_tick > TICKS_PER_SECOND * 2 || now < combat->last_fight_tick; + int started, ended; + boolean retreating = bots_combat_retreat_step(&combat->retreat, skill, confidence, own_shield, now, + bots_combat_hash01((unsigned long)bot->player_index, (unsigned long)combat->retreat.next_allowed), &started, &ended); + + if (new_fight) + { + combat->halt_until_tick = bot->target_first_seen_tick + bots_combat_initial_halt_ticks(skill, + bots_combat_hash01((unsigned long)bot->player_index ^ 0x27D4EB2DUL, (unsigned long)bot->target_first_seen_tick)); + combat->next_jump_tick = now + bots_combat_jump_delay(skill, bots_random_real(bot)); + combat->last_strafe_until_tick = bot->strafe_until_tick; + } + else if (bot->strafe_until_tick != combat->last_strafe_until_tick) + { + long halt = bots_combat_halt_ticks(skill, bots_random_real(bot), bots_random_real(bot)); + + combat->last_strafe_until_tick = bot->strafe_until_tick; + if (halt > 0) + { + combat->halt_until_tick = now + halt; + bots_globals.combat_counts[_bots_combat_count_halts]++; + } + } + combat->last_fight_tick = now; + if (now < combat->halt_until_tick) + { + real range = bots_weapon_range(tick->weapon_index); + + if (tick->target_distance > range * 1.3f) + tick->move_direction = to_target; + else if (tick->target_distance < range * 0.6f) + tick->move_direction = to_target + BOTS_PI; + else + tick->moving = FALSE; + } + if (started) + { + bots_level_retreat_goal(bot, tick, target_point); + bots_globals.combat_counts[_bots_combat_count_retreats]++; + } + if (ended) + bot->goal_kind = _bots_goal_none; + if (retreating) + { + real direction; + + bot->target_last_surface_index = NONE; + bot->item_check_tick = MAX(bot->item_check_tick, now + TICKS_PER_SECOND); + if (bot->goal_kind == _bots_goal_roam && + bots_follow_path(bot, tick->player->unit_index, &tick->position, &direction)) + { + tick->move_direction = direction; + } + else + tick->move_direction = to_target + BOTS_PI + bot->strafe_sign * 0.5f; + tick->moving = TRUE; + tick->throttle_scale = 1.0f; + combat->charging = FALSE; + } + else + { + boolean charge = bots_combat_charge(skill, confidence, target_shield, target->object.body_vitality, + tick->target_distance); + + if (charge) + { + tick->move_direction = to_target + bot->strafe_sign * 0.25f; + tick->moving = TRUE; + tick->throttle_scale = 1.0f; + if (!combat->charging) + bots_globals.combat_counts[_bots_combat_count_charges]++; + } + else if (bots_combat_step_in(skill, tick->target_distance, target_shield)) + { + tick->move_direction = to_target + bot->strafe_sign * 0.3f; + tick->moving = TRUE; + tick->throttle_scale = 1.0f; + } + combat->charging = charge; + } + if (combat->next_jump_tick > 0 && now >= combat->next_jump_tick) + { + long delay = bots_combat_jump_delay(skill, bots_random_real(bot)); + + combat->next_jump_tick = delay > 0 ? now + delay : 0; + if (delay > 0) + { + tick->flags |= FLAG(_unit_control_jump_bit); + bots_globals.combat_counts[_bots_combat_count_jumps]++; + } + } +} + +/* out of a fight (VETERAN and up): once a lost contact, a grenade at the +spot its target was last seen, 0.6 to 3 s after, the spot 5 to 20 units off +and in its line of sight; the aim held on the spot for the throw (half a +second) */ +static void bots_level_prenade(struct bots_bot *bot, struct bots_tick *tick) +{ + struct bots_bot_combat *combat = &bot->combat; + short skill = bots_globals.skill; + boolean has = tick->unit->unit.grenade_counts[0] > 0 || tick->unit->unit.grenade_counts[1] > 0; + struct player_datum *target; + real_point3d point; + real seconds, distance; + + if (tick->now < combat->prenade_until_tick) + { + real_point3d const *eye = bots_tick_eye(tick); + real dx = combat->prenade_point.x - eye->x, dy = combat->prenade_point.y - eye->y; + real turn = bots_skills[skill].turn_degrees_per_tick * BOTS_DEGREES; + real yaw_off = bots_angle_difference((real)atan2(dy, dx), bot->yaw); + real pitch_off = (real)atan2(combat->prenade_point.z - eye->z, (real)sqrt(dx * dx + dy * dy)) - bot->pitch; + + bot->yaw += PIN(yaw_off, -turn, turn); + bot->pitch += PIN(pitch_off, -turn, turn); + /* (the throw once the aim is on the spot) */ + if (combat->prenade_until_tick - tick->now > 1 && (real)fabs(yaw_off) < 0.1f && (real)fabs(pitch_off) < 0.1f) + { + tick->flags |= FLAG(_unit_control_throw_grenade_bit); + if (tick->unit->unit.grenade_counts[(long)tick->unit->unit.current_grenade_index] <= 0) + tick->action->desired_grenade_index = tick->unit->unit.grenade_counts[0] > 0 ? 0 : 1; + combat->prenade_until_tick = tick->now + 1; + } + return; + } + if (skill < _bots_skill_veteran || bot->target_player_index == NONE || bot->target_last_surface_index == NONE || + combat->prenade_seen_tick == bot->target_seen_tick || !has || tick->now < bot->grenade_tick || + tick->object->object.parent_object_index != NONE) + { + return; + } + seconds = (real)(tick->now - bot->target_seen_tick) / TICKS_PER_SECOND; + if (seconds < 0.6f) + return; + combat->prenade_seen_tick = bot->target_seen_tick; + /* (about the target's middle where it stood) */ + point = bot->target_last_position; + point.z += 0.3f; + distance = bots_distance3d(bots_tick_eye(tick), &point); + target = player_try_and_get(bot->target_player_index); + if (!bots_combat_prenade(skill, seconds, distance, has, bots_random_real(bot)) || + !bots_line_of_sight(tick->player->unit_index, bots_tick_eye(tick), &point, + target && target->unit_index != NONE ? target->unit_index : NONE)) + { + return; + } + combat->prenade_point = point; + combat->prenade_until_tick = tick->now + TICKS_PER_SECOND / 2; + bot->grenade_tick = tick->now + bots_combat_grenade_cooldown(skill, bots_random_real(bot)); + bots_globals.combat_counts[_bots_combat_count_prenades]++; +} + +/* looking for enemies (every third tick, the bots in turn), and forgetting +the one gone a while */ +static void bots_bot_look(struct bots_bot *bot, struct bots_tick *tick) +{ + if (tick->now >= bot->next_look_tick) + { + long target = bots_find_target(bot, tick->player, bots_tick_eye(tick)); + + bot->next_look_tick = tick->now + 3; + /* (3 to 5 ticks apart: never a metronome) */ + bot->next_look_tick += bots_combat_look_jitter(bots_combat_hash01((unsigned long)bot->player_index ^ 0x5BD1E995UL, + (unsigned long)tick->now)); + if (target != NONE) + { + struct player_datum *target_player = player_get(target); + struct object_datum *target_object = object_get(target_player->unit_index); + real_point3d ground; + long surface_index; + + /* (a new target: the aim's error as it first turns to it) */ + if (target != bot->target_player_index || tick->now - bot->target_seen_tick > TICKS_PER_SECOND * 2) + { + real error = tick->skill->aim_error_degrees * BOTS_DEGREES; + + bot->target_first_seen_tick = tick->now; + bot->aim_error_yaw = bots_random_signed(bot) * error; + bot->aim_error_pitch = bots_random_signed(bot) * error * 0.6f; + } + bot->target_player_index = target; + bot->target_seen_tick = tick->now; + bot->target_last_position = target_object->object.position; + surface_index = bots_unit_surface(target_player->unit_index, &ground); + if (surface_index != NONE) + bot->target_last_surface_index = surface_index; + } + } + if (bot->target_player_index != NONE) + { + struct player_datum *target_player = player_try_and_get(bot->target_player_index); + + if (!target_player || target_player->unit_index == NONE || + tick->now - bot->target_seen_tick > TICKS_PER_SECOND * 10) + { + bot->target_player_index = NONE; + } + } +} + +/* fighting the target seen in the last half second: aim (turning at its +speed, leading, an error that settles), fire, a grenade, a blow, strafing */ +static void bots_bot_fight(struct bots_bot *bot, struct bots_tick *tick) +{ + struct bots_skill_definition const *skill = tick->skill; + struct player_datum *target_player = player_get(bot->target_player_index); + struct object_datum *target_object = object_get(target_player->unit_index); + real_point3d aim_point = target_object->object.bounding_sphere_center; + boolean zombie = infection_enabled() && infection_unit_is_zombie(tick->player->unit_index); + long reaction_ticks = (long)(skill->reaction_seconds * TICKS_PER_SECOND); + long now = tick->now; + real desired_yaw, desired_pitch, dx, dy, dz, horizontal, turn, yaw_off, pitch_off, cone; + real settle = (real)exp(-1.0f / (skill->aim_settle_seconds * TICKS_PER_SECOND) * 1.1f); + + tick->fighting = TRUE; + /* (a reaction of 0.85 to 1.35 of the level's, another each sighting; the + aim trailing the target at the lowest levels, at the head or ahead of a + throw) */ + reaction_ticks = bots_combat_reaction_ticks(bots_globals.skill, reaction_ticks, + bots_combat_hash01((unsigned long)bot->player_index, (unsigned long)bot->target_first_seen_tick)); + bots_level_trail(bot, now, &aim_point); + bots_level_aim_point(bot, tick, target_player->unit_index, &aim_point); + bots_tick_eye(tick); + enhanced_bots_aim((long)(bot - bots_globals.bots), bots_globals.skill, bot->target_player_index, tick->weapon_index, + &tick->eye, &aim_point); + tick->target_distance = bots_distance3d(&tick->eye, &aim_point); + /* (leading a moving target by the projectile's flight) */ + if (tick->weapon_index != NONE && skill->lead > 0.0f) + { + real speed = bots_projectile_speed(tick->weapon_index); + + if (speed > 0.01f) + { + real ticks = MIN(tick->target_distance / speed, 30.0f); + + aim_point.x += target_object->object.translational_velocity.i * ticks * skill->lead; + aim_point.y += target_object->object.translational_velocity.j * ticks * skill->lead; + aim_point.z += target_object->object.translational_velocity.k * ticks * skill->lead; + } + } + dx = aim_point.x - tick->eye.x; + dy = aim_point.y - tick->eye.y; + dz = aim_point.z - tick->eye.z; + horizontal = (real)sqrt(dx * dx + dy * dy); + /* the aim error settles while the target stays in sight, with a tremble */ + bot->aim_error_yaw = bot->aim_error_yaw * settle + + bots_random_signed(bot) * skill->aim_error_degrees * 0.04f * BOTS_DEGREES; + bot->aim_error_pitch = bot->aim_error_pitch * settle + + bots_random_signed(bot) * skill->aim_error_degrees * 0.03f * BOTS_DEGREES; + /* (recruit's wander, the error kept at range) */ + bots_level_aim_error(bot, tick); + desired_yaw = (real)atan2(dy, dx) + bot->aim_error_yaw; + desired_pitch = (real)atan2(dz, horizontal) + bot->aim_error_pitch; + turn = skill->turn_degrees_per_tick * BOTS_DEGREES; + yaw_off = bots_angle_difference(desired_yaw, bot->yaw); + pitch_off = desired_pitch - bot->pitch; + bot->yaw += PIN(yaw_off, -turn, turn); + bot->pitch += PIN(pitch_off, -turn, turn); + + /* fire: once it has reacted, while its aim is on the target (its size + at that distance) */ + yaw_off = (real)fabs(bots_angle_difference((real)atan2(dy, dx), bot->yaw)); + pitch_off = (real)fabs((real)atan2(dz, horizontal) - bot->pitch); + cone = (real)atan(0.35f / MAX(tick->target_distance, 0.5f)) * skill->fire_cone + 0.01f; + if (!bots_level_may_fire(bot, tick)) + cone = -1.0f; + if (!zombie && now - bot->target_first_seen_tick >= reaction_ticks && now - bot->target_seen_tick <= 3 && + yaw_off < cone && pitch_off < cone * 1.5f && tick->weapon_index != NONE) + { + short tap_ticks = bots_weapon_tap_ticks(tick->weapon_index); + + if (tap_ticks > 0) + { + /* (a press a shot, released between: as fast as the weapon fires, + a little slower for the less skilled) */ + if (now >= bot->burst_until_tick) + { + tick->flags |= FLAG(_unit_control_weapon_primary_trigger_bit); + bot->burst_until_tick = now + tap_ticks + (long)(bots_random(bot) % (1 + skill->pause_ticks / 3)); + } + } + else if (now < bot->burst_until_tick) + tick->flags |= FLAG(_unit_control_weapon_primary_trigger_bit); + else if (now >= bot->pause_until_tick) + { + /* (bursts, with pauses between) */ + bot->burst_until_tick = now + skill->burst_ticks + (long)(bots_random(bot) % 4); + bot->pause_until_tick = bot->burst_until_tick + skill->pause_ticks + (long)(bots_random(bot) % 4); + tick->flags |= FLAG(_unit_control_weapon_primary_trigger_bit); + } + } + /* a blow close up (the level's reach, its moment and its wait) */ + if (zombie ? (tick->target_distance < 1.6f && now >= bot->melee_tick) : + bots_level_melee(bot, tick, target_player->unit_index)) + { + tick->flags |= FLAG(_unit_control_use_equipment_bit); + bot->melee_tick = now + (zombie ? TICKS_PER_SECOND / 2 : + bots_combat_melee_cooldown(bots_globals.skill, bots_random_real(bot))); + } + /* a grenade at middle range, by the level's rules */ + if (!zombie) + bots_level_grenade(bot, tick, reaction_ticks); + /* strafing, to a side for a while; nearer or further to keep its + weapon's distance; a jump now and then */ + if (now >= bot->strafe_until_tick) + { + bot->strafe_sign = bots_random_real(bot) < 0.5f ? -1.0f : 1.0f; + /* (the level's strafes, short jiggles at the top) */ + bot->strafe_until_tick = now + bots_combat_strafe_ticks(bots_globals.skill, bots_random_real(bot)); + } + { + real to_target = (real)atan2(dy, dx); + real range = bots_weapon_range(tick->weapon_index); + real forward = tick->target_distance > range * 1.3f ? 0.8f : tick->target_distance < range * 0.6f ? -0.5f : 0.0f; + real side = bot->strafe_sign * bots_combat_strafe_strength(bots_globals.skill); + + if (zombie) + { + forward = 1.0f; + side *= 0.2f; + } + else if (infection_enabled() && infection_unit_is_zombie(target_player->unit_index) && + tick->target_distance < 7.0f) + forward = -1.0f; + + tick->move_direction = + (real)atan2((real)sin(to_target) * forward + (real)sin(to_target + BOTS_PI * 0.5f) * side, + (real)cos(to_target) * forward + (real)cos(to_target + BOTS_PI * 0.5f) * side); + tick->moving = TRUE; + tick->throttle_scale = 1.0f; + } + /* crouches, halts, a retreat, a charge, a step in, jumps, by level */ + if (bots_combat_crouch_chance(bots_globals.skill) > 0.0f && + bots_combat_crouch_step(&bot->combat.crouch, bots_globals.skill, now, bots_random_real(bot))) + { + tick->flags |= FLAG(_unit_control_crouch_modifier_bit); + } + if (!zombie) + bots_level_move(bot, tick, target_object); +} + +/* walking to the goal, looking where it goes; there, a look about (and the +last bit straight onto an item); a reload when no one is about */ +static void bots_bot_walk(struct bots_bot *bot, struct bots_tick *tick) +{ + real direction; + + if (bots_follow_path(bot, tick->player->unit_index, &tick->position, &direction)) + { + real turn = 12.0f * BOTS_DEGREES; + real off = bots_angle_difference(direction, bot->yaw); + + tick->move_direction = direction; + tick->moving = TRUE; + bot->yaw += PIN(off, -turn, turn); + bot->pitch += PIN(-bot->pitch, -0.05f, 0.05f); + if (bot->climb_until_tick && tick->now < bot->climb_until_tick && (bot->climb_until_tick - tick->now) % 20 == 0) + tick->flags |= FLAG(_unit_control_jump_bit); + } + else + { + bot->yaw += 2.0f * BOTS_DEGREES; + bots_tactics_look((long)(bot - bots_globals.bots), &tick->position, tick->now, &bot->yaw, &bot->pitch); + if (bot->goal_kind == _bots_goal_roam || bot->goal_kind == _bots_goal_enemy) + bot->goal_kind = _bots_goal_none; + /* (at an item: on to it) */ + if (bot->goal_kind == _bots_goal_item) + { + struct object_datum *item = object_try_and_get_and_verify_type(bot->item_index, _object_mask_item); + + if (item && bots_distance2d(&item->object.position, &tick->position) > 0.3f) + { + tick->move_direction = + (real)atan2(item->object.position.y - tick->position.y, item->object.position.x - tick->position.x); + tick->moving = TRUE; + tick->throttle_scale = 0.6f; + } + } + } + if (tick->weapon_index != NONE && bots_weapon_loaded(tick->weapon_index) < 0.4f && + tick->now - bot->target_seen_tick > TICKS_PER_SECOND * 2) + { + tick->flags |= FLAG(_unit_control_weapon_reload_bit); + } +} + +/* the bots in each other's way (a team's bots leaving their base by the same +door, Longest's, jammed in it a whole game, each going round the others): +the one with the higher index steps back from the other, while the other +moves, so that the first goes through */ +static void bots_bot_yield(long bot_index, struct bots_tick *tick) +{ + long index; + + if (!tick->moving || tick->fighting || tick->object->object.parent_object_index != NONE) + return; + for (index = 0; index < bot_index; index++) + { + struct bots_bot *other = &bots_globals.bots[index]; + struct object_datum *object; + real dx, dy, distance, velocity; + + if (other->player_index == NONE || other->unit_index == NONE) + continue; + object = (struct object_datum *)object_try_and_get_and_verify_type(other->unit_index, _object_mask_unit); + if (!object || object->object.parent_object_index != NONE) + continue; + dx = object->object.position.x - tick->position.x; + dy = object->object.position.y - tick->position.y; + distance = (real)sqrt(dx * dx + dy * dy); + velocity = (real)sqrt(object->object.translational_velocity.i * object->object.translational_velocity.i + + object->object.translational_velocity.j * object->object.translational_velocity.j); + if (distance > 1.1f || distance < 0.01f || fabs(object->object.position.z - tick->position.z) > 1.5f || + velocity < 0.02f || + (dx * (real)cos(tick->move_direction) + dy * (real)sin(tick->move_direction)) < 0.3f * distance) + { + continue; + } + tick->move_direction = (real)atan2(-dy, -dx); + tick->throttle_scale = 0.6f; + return; + } +} + +/* weapons: the other one when this one is empty; at the weapon it fetches, +once the game offers it (the player's action, as the HUD shows it), the +action button held, as a player holds it to swap a weapon (the swap: +players_update_before_game's player_handle_weapon_swap), let go now and +then, so that a second swap can follow a first */ +static void bots_bot_weapons(struct bots_bot *bot, struct bots_tick *tick) +{ + if (tick->weapon_index != NONE && bots_weapon_empty(tick->weapon_index)) + { + short slot; + + for (slot = 0; slot < MAXIMUM_WEAPONS_PER_UNIT; slot++) + { + long other = tick->unit->unit.weapon_object_indices[slot]; + + if (slot != tick->unit->unit.current_weapon_index && other != NONE && !bots_weapon_empty(other)) + { + tick->action->desired_weapon_index = slot; + break; + } + } + } + if (bot->goal_kind == _bots_goal_item) + { + struct object_datum *item = object_try_and_get_and_verify_type(bot->item_index, _object_mask_weapon); + + if (item && item->object.parent_object_index == NONE && + bots_distance2d(&item->object.position, &tick->position) < 0.8f && + fabs(item->object.position.z - tick->position.z) < 1.2f) + { + if (tick->now - bot->item_press_tick > TICKS_PER_SECOND) + bot->item_press_tick = tick->now; + if (bot->item_first_press_tick < bot->goal_tick) + bot->item_first_press_tick = tick->now; + if (tick->now - bot->item_press_tick < TICKS_PER_SECOND / 2 && + tick->player->action_object_index == bot->item_index && + (tick->player->action_result == _player_action_result_pickup_weapon || + tick->player->action_result == _player_action_result_swap_for_weapon || + tick->player->action_result == _player_action_result_add_weapon_to_inventory)) + { + tick->flags |= FLAG(_unit_control_swap_weapons_bit); + } + } + } +} + +/* stuck: not moving for a second while it walks - a jump and a sidestep, +then another path; somewhere else after three */ +static void bots_bot_unstick(struct bots_bot *bot, struct bots_tick *tick) +{ + long now = tick->now; + + /* A committed ladder climb moves vertically; its own timeout handles failure. */ + if (bots_navigation_climbing(bot)) + { + bot->stuck_position = tick->position; + bot->stuck_tick = now; + bot->stuck_count = 0; + bot->unstick_until_tick = 0; + return; + } + if (now - bot->stuck_tick >= TICKS_PER_SECOND) + { + if (tick->moving && bots_distance2d(&tick->position, &bot->stuck_position) < 0.4f && + tick->object->object.parent_object_index == NONE) + { + bots_globals.stuck_events++; + bot->stuck_count++; + bot->unstick_until_tick = now + TICKS_PER_SECOND / 2; + bot->unstick_direction = + tick->move_direction + (bots_random_real(bot) < 0.5f ? -1.0f : 1.0f) * BOTS_PI * 0.5f; + bot->path.valid = FALSE; + if (bot->stuck_count >= 3) + { + bots_globals.stuck_giveups++; + bots_goal_failed(bot); + bot->stuck_count = 0; + bots_pick_roam_goal(bot, &tick->position); + } + } + else + bot->stuck_count = 0; + bot->stuck_position = tick->position; + bot->stuck_tick = now; + } + if (now < bot->unstick_until_tick) + { + tick->move_direction = bot->unstick_direction; + tick->moving = TRUE; + if (now == bot->unstick_until_tick - TICKS_PER_SECOND / 2) + tick->flags |= FLAG(_unit_control_jump_bit); + } +} + +/* (debug.bot_trace = ) each bot's state that often */ +static void bots_bot_trace(struct bots_bot *bot, long bot_index, struct bots_tick *tick) +{ + static long trace = -1; + long now = tick->now; + + if (trace < 0) + trace = MAX(config_integer("debug.bot_trace"), 0) * TICKS_PER_SECOND; + if (trace <= 0 || now % trace != bot_index) + return; + platform_log("bots: trace %ld bot %ld at (%.1f %.1f %.1f) goal %d (%.1f %.1f %.1f) s%ld path %s %d/%d%s " + "target %ld seen %ld ago%s stuck %d yaw %.0f throttle %.2f/%.2f flags %lx searches %ld failures %ld", + now, bot_index + 1, tick->position.x, tick->position.y, tick->position.z, (int)bot->goal_kind, + bot->goal_point.x, bot->goal_point.y, bot->goal_point.z, bot->goal_surface_index, + bot->path.valid ? "yes" : "no", (int)bot->path.step_index, (int)bot->path.step_count, + bot->path.steps_finish_path ? " (all)" : "", + bot->target_player_index == NONE ? -1L : (long)DATUM_INDEX_TO_ABSOLUTE_INDEX(bot->target_player_index), + now - bot->target_seen_tick, tick->fighting ? " fighting" : "", (int)bot->stuck_count, + bot->yaw / BOTS_DEGREES, tick->action->throttle.i, tick->action->throttle.j, + tick->action->control_flags, bot->searches, bot->path_failures); + if (tick->weapon_index != NONE) + { + struct weapon_datum *weapon = weapon_get(tick->weapon_index); + + platform_log("bots: trace weapon %s loaded %d total %d, aim off %.1f/%.1f degrees, distance %.1f", + tag_get_name(weapon->definition_index), (int)weapon->weapon.magazines[0].rounds_loaded, + (int)weapon->weapon.magazines[0].rounds_total, bot->aim_error_yaw / BOTS_DEGREES, + bot->aim_error_pitch / BOTS_DEGREES, tick->target_distance); + } +} + +static void bots_bot_update(struct bots_bot *bot, long bot_index, struct player_action *action) +{ + struct bots_tick tick; + real vitality; + boolean climbing; + + csmemset(&tick, 0, sizeof(tick)); + tick.skill = &bots_skills[bots_globals.skill]; + tick.player = player_get(bot->player_index); + tick.now = game_time_get(); + tick.throttle_scale = 1.0f; + tick.action = action; + csmemset(action, 0, sizeof(*action)); + action->desired_weapon_index = NONE; + action->desired_grenade_index = NONE; + action->desired_zoom_level = NONE; + action->desired_facing.yaw = bot->yaw; + action->desired_facing.pitch = bot->pitch; + + if (tick.player->unit_index == NONE) + { + /* (dead: it forgets its fight and its path; the game respawns it) */ + bot->unit_index = NONE; + bots_globals.search_wait[bot_index] = 0; + bot->target_player_index = NONE; + bot->path.valid = FALSE; + bot->goal_kind = _bots_goal_none; + bot->previous_control_flags = 0; + { + bots_tactics_bot_dead(bot_index); + bots_navigation_reset_bot(bot_index); + bots_vehicles_reset_player(bot_index); + } + + return; + } + tick.unit = unit_get(tick.player->unit_index); + tick.object = object_get(tick.player->unit_index); + tick.position = tick.object->object.position; + if (bots_vehicle_parent(tick.player->unit_index) != NONE) + tick.position = object_get(bots_vehicle_parent(tick.player->unit_index))->object.position; + if (bot->unit_index != tick.player->unit_index) + { + /* (spawned: it looks the way its unit faces) */ + bot->unit_index = tick.player->unit_index; + bot->goal_serial++; + bot->path.valid = FALSE; + bot->objective_retry_tick = 0; + bot->previous_control_flags = 0; + bot->intent_point = tick.position; + bots_globals.search_wait[bot_index] = 0; + bot->yaw = (real)atan2(tick.object->object.forward.j, tick.object->object.forward.i); + bot->pitch = 0.0f; + bot->last_vitality = tick.object->object.body_vitality + tick.object->object.shield_vitality; + bot->stuck_position = tick.position; + bot->stuck_tick = tick.now; + bot->stuck_count = 0; + bot->goal_kind = _bots_goal_none; + bot->next_look_tick = tick.now + (bot_index % 3); + bot->climb_until_tick = 0; + bot->path_short = FALSE; + bot->escape_until_tick = 0; + bot->last_position = tick.position; + { + bots_vehicles_reset_player(bot_index); + bots_navigation_reset_bot(bot_index); + enhanced_bots_reset(bot_index, bot->player_index); + bot->powerup_index = NONE; + bot->powerup_check = tick.now + bot_index % TICKS_PER_SECOND; + } + bots_level_reset(&bot->combat); + } + { + long parent = bots_vehicle_parent(tick.player->unit_index); + short seat = tick.unit->unit.parent_seat_index; + if (parent != bot->navigation_parent || seat != bot->navigation_seat) + { + bot->navigation_parent = parent; + bot->navigation_seat = seat; + bot->path_short = FALSE; + if (parent != NONE && bot->goal_kind == _bots_goal_item) bot->goal_kind = _bots_goal_none; + bot->goal_serial++; + bot->path.valid = FALSE; + bot->path_tick = tick.now - TICKS_PER_SECOND; + bot->climb_until_tick = bot->escape_until_tick = bot->unstick_until_tick = 0; + bots_navigation_reset_bot(bot_index); + bots_tactics_objective(bot_index); + } + } + /* (sent on by a teleporter it walked onto: a new path from where it came + out) */ + if (bots_distance3d(&tick.position, &bot->last_position) > 3.0f && bot->goal_kind != _bots_goal_none && + tick.object->object.parent_object_index == NONE) + { + bot->path.valid = FALSE; + bot->path_tick = tick.now - TICKS_PER_SECOND; + bot->stuck_position = tick.position; + } + bots_navigation_update(bot, &tick.position, bots_vehicle_parent(tick.player->unit_index) != NONE); + bot->last_position = tick.position; + + /* hurt: it turns to look for who did it */ + vitality = tick.object->object.body_vitality + tick.object->object.shield_vitality; + if (vitality < bot->last_vitality - 0.01f) + bot->hurt_tick = tick.now; + bot->last_vitality = vitality; + + bots_bot_look(bot, &tick); + tick.weapon_index = bots_current_weapon(tick.unit); + tick.weapon_index = bots_vehicle_weapon(tick.player->unit_index, tick.weapon_index); + if (bot->target_player_index != NONE && tick.now - bot->target_seen_tick <= TICKS_PER_SECOND / 2) + bots_bot_fight(bot, &tick); + climbing = bots_navigation_climbing(bot); + /* the goal, and the path to it (while fighting, only a weapon close by: + towards it, still facing the enemy) */ + if (!climbing) + bots_choose_goal(bot, bot->player_index, &tick.position, tick.fighting); + if (!climbing && !enhanced_bots_carrying(bot_index) && bot->goal_kind != _bots_goal_item && + bot->goal_kind != _bots_goal_none && bot->goal_kind != _bots_goal_vehicle && + !enhanced_bots_holding_hill(tick.player->unit_index) && (!tick.fighting || tick.target_distance >= 15.0f)) + { + real_point3d seat_goal; + long seat_surface; + if (bots_vehicle_goal(bot_index, tick.player->unit_index, &bot->goal_point, &seat_goal, &seat_surface)) + bots_set_goal(bot, _bots_goal_vehicle, &seat_goal, seat_surface); + } + if (bots_vehicle_parent(tick.player->unit_index) != NONE) + { + tick.moving = bots_follow_path(bot, tick.player->unit_index, &tick.position, &tick.move_direction); + } + else if (!tick.fighting) + { + bots_bot_walk(bot, &tick); + bots_bot_yield(bot_index, &tick); + if (!(infection_enabled() && infection_unit_is_zombie(tick.player->unit_index))) + bots_level_prenade(bot, &tick); + } + else if (bot->goal_kind == _bots_goal_item || bot->goal_kind == _bots_goal_vehicle || + enhanced_bots_advancing(bot_index, tick.player->unit_index)) + { + real direction; + + if (bots_follow_path(bot, tick.player->unit_index, &tick.position, &direction)) + { + tick.move_direction = direction; + tick.moving = TRUE; + } + } + if (tick.fighting) + { + if (enhanced_bots_holding_hill(tick.player->unit_index)) + tick.moving = FALSE; + else + bots_tactics_fight(bot_index, &tick.position, tick.target_distance, &tick.moving, &tick.move_direction, + &tick.throttle_scale); + } + /* Finish a committed climb and its landing even when an enemy is visible. */ + if (climbing) + { + tick.moving = bots_navigation_follow(bot, &tick.position, &tick.move_direction); + tick.throttle_scale = 1.0f; + } + bots_bot_weapons(bot, &tick); + bots_bot_unstick(bot, &tick); + if (bots_vehicle_parent(tick.player->unit_index) == NONE && + enhanced_bots_capture_approach(bot_index, &tick.position, &tick.move_direction, &tick.flags)) + { + tick.moving = TRUE; + tick.throttle_scale = 1.0f; + } + + if (tick.moving) + { + real relative = bots_angle_difference(tick.move_direction, bot->yaw); + + action->throttle.i = (real)cos(relative) * tick.throttle_scale; + action->throttle.j = (real)sin(relative) * tick.throttle_scale; + } + bot->pitch = PIN(bot->pitch, -1.4f, 1.4f); + bot->yaw = bots_angle_difference(bot->yaw, 0.0f); + action->desired_facing.yaw = bot->yaw; + action->desired_facing.pitch = bot->pitch; + + /* a press is one tick held and the next released (the jump, the grenade, + the blow, the reload), as a player's buttons are; the trigger and the + swap button may be held */ + { + unsigned long pressed = FLAG(_unit_control_jump_bit) | FLAG(_unit_control_throw_grenade_bit) | + FLAG(_unit_control_use_equipment_bit) | FLAG(_unit_control_weapon_reload_bit); + + tick.flags &= ~(bot->previous_control_flags & pressed); + bot->previous_control_flags = tick.flags; + } + action->control_flags = tick.flags; + action->primary_trigger = TEST_FLAG(tick.flags, _unit_control_weapon_primary_trigger_bit) ? 1.0f : 0.0f; + bots_vehicle_action(bot_index, tick.player->unit_index, &bot->goal_point, bot->goal_kind == _bots_goal_enhanced, + tick.moving, tick.move_direction, + bot->target_player_index != NONE && tick.now - bot->target_seen_tick <= TICKS_PER_SECOND / 2 + ? player_get(bot->target_player_index)->unit_index + : NONE, + enhanced_bots_retreat(tick.unit, bots_globals.skill, bot->hurt_tick), action); + bots_navigation_action(bot, action); + bots_bot_trace(bot, bot_index, &tick); +} + +/* halo.log's line, a minute into the game and each minute on */ +static void bots_report(void) +{ + long now = game_time_get(); + long count = 0, index; + char line[400]; + int length = 0; + + if (bots_globals.last_report_tick != NONE && now - bots_globals.last_report_tick < TICKS_PER_SECOND * 60) + return; + bots_globals.last_report_tick = now; + line[0] = 0; + for (index = 0; index < BOTS_MAXIMUM; index++) + { + struct bots_bot *bot = &bots_globals.bots[index]; + struct player_datum *player = bot->player_index != NONE ? player_try_and_get(bot->player_index) : NULL; + + if (!player) + continue; + count++; + if (length < (int)sizeof(line) - 40) + length += snprintf(line + length, sizeof(line) - (size_t)length, " %ld:%d/%d", index + 1, + (int)player->statistics.kills[0], (int)player->statistics.deaths); + } + if (!count) + return; + platform_log("bots: tick %ld, %ld bots (%s): searches %ld (%ld failed, %ld short, %ld full, %ld unavoided, " + "%ld unsmoothed), stuck %ld (goals given up %ld), kills/deaths%s", now, count, + bots_skills[bots_globals.skill].name, bots_globals.searches, bots_globals.search_failures, + bots_globals.search_partials, bots_globals.search_overflows, bots_globals.search_unavoided, + bots_globals.search_unsmoothed, bots_globals.stuck_events, bots_globals.stuck_giveups, line); + { + long const *counts = bots_globals.combat_counts; + + platform_log("bots: fights since the map's start: grenades %ld (%ld at a last-seen spot), blows %ld " + "(%ld held back), retreats %ld, charges %ld, jumps %ld, halts %ld, shots paced %ld, " + "zoomed again %ld, high ground picks %ld, enemies out of vertical view %ld", + counts[_bots_combat_count_grenades] + counts[_bots_combat_count_prenades], counts[_bots_combat_count_prenades], + counts[_bots_combat_count_blows], counts[_bots_combat_count_blows_held], + counts[_bots_combat_count_retreats], counts[_bots_combat_count_charges], counts[_bots_combat_count_jumps], + counts[_bots_combat_count_halts], counts[_bots_combat_count_paced], counts[_bots_combat_count_rescopes], + counts[_bots_combat_count_high_ground], counts[_bots_combat_count_out_of_view]); + } +} + +void enhanced_controller_update(struct player_action *actions) +{ + struct data_iterator iterator; + struct player_datum *player; + long count = 0, index; + boolean present[BOTS_MAXIMUM]; + + /* Enhanced policy is selected at map load: changing it during a match + would invalidate goals and could strand a bot in a vehicle. */ + /* Only the host generates actions; clients replay the ordinary updates. */ + if (!game_engine_running() || !bots_session_allowed()) + return; + csmemset(present, 0, sizeof(present)); + data_iterator_new(&iterator, player_data); + while ((player = (struct player_datum *)data_iterator_next(&iterator)) != NULL) + { + long bot_index; + long absolute_index = DATUM_INDEX_TO_ABSOLUTE_INDEX(iterator.datum_index); + struct bots_bot *bot; + + if (player->local_player_index != NONE || !bots_player_owned(player->network_player_data.machine_index)) + continue; + /* (the roaming places and the walkable surfaces once a game has + bots; the skill once a tick) */ + if (!count) + { + if (!bots_globals.map_ready) + bots_prepare_map(); + bots_globals.skill = bots_skill(); + bots_globals.tick_searches = 0; + bots_paths_scan(); + enhanced_bots_update(bots_globals.roam_point_count, bots_globals.roam_points); + } + bot_index = player->network_player_data.machine_index - BOTS_FIRST_MACHINE; + present[bot_index] = TRUE; + bot = &bots_globals.bots[bot_index]; + if (bot->player_index != iterator.datum_index) + bots_bot_reset(bot, iterator.datum_index, bot_index); + if (absolute_index >= 0 && absolute_index < HALO_PORT_MAXIMUM_NETWORK_PLAYERS) + bots_bot_update(bot, bot_index, &actions[absolute_index]); + count++; + } + /* Live removal has no death tick. Release claims and invalidate pending + worker results before a later player can reuse this bot slot. */ + for (index = 0; index < BOTS_MAXIMUM; index++) + if (!present[index] && bots_globals.bots[index].player_index != NONE) + { + struct bots_bot *bot = &bots_globals.bots[index]; + bot->player_index = bot->unit_index = NONE; + bot->goal_serial++; + bot->path.valid = FALSE; + bots_globals.search_wait[index] = 0; + bots_vehicles_reset_player(index); + bots_navigation_reset_bot(index); + bots_tactics_bot_dead(index); + } + if (count) + { + bots_globals.ticks++; + bots_report(); + if (game_time_get() % (TICKS_PER_SECOND * 60) == 0) + bots_tactics_report(game_time_get()); + } + bots_network_record_actions(actions); +} diff --git a/port/linux/game/enhanced_bots_controller.h b/port/linux/game/enhanced_bots_controller.h new file mode 100644 index 0000000000..4423781af1 --- /dev/null +++ b/port/linux/game/enhanced_bots_controller.h @@ -0,0 +1,7 @@ +#ifndef ENHANCED_BOTS_CONTROLLER_H +#define ENHANCED_BOTS_CONTROLLER_H +struct player_action; +void enhanced_controller_initialize(void); +void enhanced_controller_dispose(void); +void enhanced_controller_update(struct player_action *actions); +#endif diff --git a/port/linux/game/enhanced_bots_flight.c b/port/linux/game/enhanced_bots_flight.c new file mode 100644 index 0000000000..7eccf0e401 --- /dev/null +++ b/port/linux/game/enhanced_bots_flight.c @@ -0,0 +1,690 @@ +/* Enhanced aircraft navigation. Uses authored vehicle physics through ordinary +player controls. Geometry is queried on the host; no physics, map conversion +or replicated rules are changed. A bounded 3D search owns each flight route. */ +#include "cseries.h" +#include "game/game.h" +#include "game/players.h" +#include "objects/objects.h" +#include "units/units.h" +#include "units/vehicle_datum.h" +#include "units/unit_definitions.h" +#include "physics/physics_definitions.h" +#include "physics/collisions.h" +#include "bots.h" +#include "enhanced_bots_flight.h" +#include + +long config_integer(char const *name); +void platform_log(char const *format, ...); + +enum +{ + FLIGHT_NODES = 1024, + FLIGHT_STEPS = 32 +}; +enum +{ + _flight_takeoff, + _flight_cruise, + _flight_approach, + _flight_land +}; +struct flight_node +{ + real_point3d point; + real cost, estimate; + short parent; + boolean closed; +}; +static struct flight_state +{ + long vehicle, retry, progress_tick; + short phase, count, expanded, step_count, step; + boolean searching, failed, hovering, landing_ready, landing_checked; + real_point3d destination, target, progress_target, landing; + real radius, height, spacing, remaining, cruise_height, waypoint_remaining; + struct flight_node nodes[FLIGHT_NODES]; + real_point3d steps[FLIGHT_STEPS]; +} flights[BOTS_MAXIMUM]; + +static real flight_distance(real_point3d const *a, real_point3d const *b) +{ + real x = a->x - b->x, y = a->y - b->y, z = a->z - b->z; + return (real)sqrt(x * x + y * y + z * z); +} + +static unsigned long flight_collision_flags(void) +{ + return FLAG(_collision_test_structure_bit) | FLAG(_collision_test_front_facing_surfaces_bit) | + FLAG(_collision_test_objects_bit) | FLAG(_collision_test_objects_scenery_bit) | + FLAG(_collision_test_objects_machines_bit) | FLAG(_collision_test_objects_vehicles_bit); +} + +static struct physics_definition *flight_physics(long vehicle_index) +{ + struct unit_definition *unit = unit_definition_get(object_get(vehicle_index)->definition_index); + struct physics_definition *physics; + if (unit->object.physics.index == NONE) return NULL; + physics = physics_definition_get(unit->object.physics.index); + return physics->mass_points.count > 0 && physics->mass_points.count <= MAXIMUM_MASS_POINTS_PER_PHYSICS ? physics : NULL; +} + +/* Fallback rays include the craft's sides and top/bottom, rather than only +its center. Horizontal clearance uses the object radius; vertical clearance +uses its physical thickness. Neither depends on a tag name. */ +static boolean flight_sweep(long vehicle, real_point3d const *a, real_point3d const *b, real radius, real height, boolean touchdown) +{ + struct collision_result hit; + real_vector3d delta; + long axis, sign; + struct object_datum *object = object_get(vehicle); + struct physics_definition *physics = flight_physics(vehicle); + vector_from_points3d(a, b, &delta); + /* Match physics_update_new: test segments from the authored mass points. + The legacy BSP capsule query does not honor object/front-face flags + and can reject a craft's resting contacts. Ordinary collision vectors + check both map and object geometry using the same contract as motion. */ + if (physics) + { + long index; + real_vector3d left; + left.i = object->object.up.j * object->object.forward.k - object->object.up.k * object->object.forward.j; + left.j = object->object.up.k * object->object.forward.i - object->object.up.i * object->object.forward.k; + left.k = object->object.up.i * object->object.forward.j - object->object.up.j * object->object.forward.i; + for (index = 0; index < physics->mass_points.count; index++) + { + struct mass_point_definition *point = TAG_BLOCK_GET_ELEMENT(&physics->mass_points, index, struct mass_point_definition); + real_point3d start, local; + /* Physics uses unscaled mass points relative to center of mass, + not model space or the render scale (physics_instance_new). */ + local.x = point->position.x - physics->center_of_mass.x; + local.y = point->position.y - physics->center_of_mass.y; + local.z = point->position.z - physics->center_of_mass.z; + start.x = a->x + object->object.position.x - object->object.bounding_sphere_center.x + + (object->object.forward.i * local.x + left.i * local.y + object->object.up.i * local.z); + start.y = a->y + object->object.position.y - object->object.bounding_sphere_center.y + + (object->object.forward.j * local.x + left.j * local.y + object->object.up.j * local.z); + start.z = a->z + object->object.position.z - object->object.bounding_sphere_center.z + + (object->object.forward.k * local.x + left.k * local.y + object->object.up.k * local.z); + if (collision_test_vector(flight_collision_flags(), &start, &delta, vehicle, &hit) && + !(touchdown && delta.k < 0.0f && hit.plane.n.k > 0.7f)) return FALSE; + } + return TRUE; + } + if (collision_test_vector(flight_collision_flags(), a, &delta, vehicle, &hit) && + !(touchdown && delta.k < 0.0f && hit.plane.n.k > 0.7f)) + return FALSE; + for (axis = 0; axis < 3; axis++) + for (sign = -1; sign <= 1; sign += 2) + { + real_point3d start = *a; + start.n[axis] += (axis == 2 ? height : radius) * sign; + if (collision_test_vector(flight_collision_flags(), &start, &delta, vehicle, &hit) && + !(touchdown && delta.k < 0.0f && hit.plane.n.k > 0.7f)) + return FALSE; + } + return TRUE; +} + +static boolean flight_clear(long vehicle, real_point3d const *a, real_point3d const *b, real radius, real height) +{ + return flight_sweep(vehicle, a, b, radius, height, FALSE); +} + +/* A wide, flat aircraft does not need its wingspan in vertical clearance. +Use the authored collision mass points, projected through the current attitude. +Fallback to the object sphere when no usable physics shape is available. */ +static real flight_height(long vehicle_index) +{ + struct object_datum *vehicle = object_get(vehicle_index); + struct physics_definition *physics = flight_physics(vehicle_index); + real height = 0.0f; + real left_z = vehicle->object.up.i * vehicle->object.forward.j - vehicle->object.up.j * vehicle->object.forward.i; + long index; + if (!physics) return vehicle->object.bounding_sphere_radius; + for (index = 0; index < physics->mass_points.count; index++) + { + struct mass_point_definition *point = TAG_BLOCK_GET_ELEMENT(&physics->mass_points, index, struct mass_point_definition); + real z = vehicle->object.position.z - vehicle->object.bounding_sphere_center.z + + vehicle->object.forward.k * (point->position.x - physics->center_of_mass.x) + + left_z * (point->position.y - physics->center_of_mass.y) + + vehicle->object.up.k * (point->position.z - physics->center_of_mass.z); + height = MAX(height, (real)fabs(z) + MAX(0.0f, point->radius)); + } + return MAX(height, 0.5f); +} + +static boolean flight_ground(long vehicle, real_point3d const *point, real *height) +{ + struct collision_result hit; + real_vector3d down = {0.0f, 0.0f, -128.0f}; + if (!collision_test_vector(flight_collision_flags(), point, &down, vehicle, &hit)) + return FALSE; + *height = hit.point.z; + return TRUE; +} + +/* A long trip needs clearance over intervening terrain, not an immediate +straight descent toward the destination's floor. Nine bounded probes choose +cruise height; the local route still checks every movement segment. */ +static real flight_cruise_height(long vehicle, real_point3d const *start, real_point3d const *goal, real height) +{ + struct collision_result hit; + real_vector3d down = {0.0f, 0.0f, -8192.0f}; + real clearance = MAX(8.0f, height * 2.0f + 4.0f); + real result = MAX(start->z, goal->z + clearance); + long index; + for (index = 0; index <= 8; index++) + { + real fraction = index / 8.0f; + real_point3d probe; + probe.x = start->x + (goal->x - start->x) * fraction; + probe.y = start->y + (goal->y - start->y) * fraction; + probe.z = MAX(start->z, goal->z) + 4096.0f; + if (collision_test_vector(flight_collision_flags(), &probe, &down, vehicle, &hit)) + result = MAX(result, hit.point.z + clearance); + } + return result; +} + +/* Objectives often sit inside bases. Pick an open descent column nearby, +then let the pedestrian controller cover the final distance. A roof between +cruise and the objective is not a reason to hover above it indefinitely. */ +static boolean flight_landing_site(struct flight_state *state, real_point3d const *goal) +{ + long ring, direction; + real spacing = MAX(8.0f, state->radius); + for (ring = 0; ring <= 3; ring++) + for (direction = 0; direction < (ring ? 8 : 1); direction++) + { + real angle = direction * 0.78539816f; + real_point3d probe = *goal, above, landing; + real ground; + probe.x += (real)cos(angle) * spacing * ring; + probe.y += (real)sin(angle) * spacing * ring; + probe.z += 4.0f; + if (!flight_ground(state->vehicle, &probe, &ground)) continue; + landing = probe; + landing.z = ground + state->height + 0.5f; + above = landing; + above.z = MAX(state->cruise_height, landing.z + 4.0f); + if (!flight_clear(state->vehicle, &above, &landing, state->radius, state->height)) continue; + state->landing = probe; + state->landing.z = ground; + return TRUE; + } + return FALSE; +} + +void enhanced_flight_reset(long index) +{ + csmemset(&flights[index], 0, sizeof(flights[index])); + flights[index].vehicle = NONE; +} + +boolean enhanced_flight_failed(long index) +{ + return flights[index].failed; +} + +boolean enhanced_flight_can_exit(long vehicle_index) +{ + struct vehicle_datum *vehicle = vehicle_datum_get(vehicle_index); + real height; + real_vector3d const *velocity = &vehicle->object.translational_velocity; + if (vehicle->object.up.k <= 0.7f) return FALSE; + if (vehicle->vehicle.on_ground_ticks >= 5 && magnitude3d(velocity) < 0.1f) return TRUE; + /* Ordinary seat exit is safe just above the floor during a controlled + approach. Requiring a fighter to stop completely in the air removes + the thrust it needs to oppose gravity and forces an unnecessary impact. */ + return fabs(velocity->k) < 0.06f && velocity->i * velocity->i + velocity->j * velocity->j < 0.1225f && + flight_ground(vehicle_index, &vehicle->object.position, &height) && + vehicle->object.position.z - height < 2.0f; +} + +boolean enhanced_flight_landing(long index) +{ + return flights[index].phase == _flight_land; +} + +/* Forward-flight physics has no vertical crouch lift. Glide onto known +upward-facing ground, allowing touchdown contact but rejecting walls. Engine +physics still owns collision response; stop thrust as soon as contact settles. */ +static void flight_descend(struct flight_state *state, real_point3d const *position, struct player_action *action) +{ + struct vehicle_datum *vehicle = vehicle_datum_get(state->vehicle); + real heading = (real)atan2(vehicle->object.forward.j, vehicle->object.forward.i); + real reach = MAX(2.0f, state->height * 2.0f); + real ground, pitch, throttle; + real clearance = REAL_MAX; + long turn; + if (state->hovering) + { + action->control_flags |= FLAG(_unit_control_crouch_modifier_bit); + return; + } + if (vehicle->vehicle.on_ground_ticks) + { + action->throttle.i = magnitude3d(&vehicle->object.translational_velocity) > 0.03f ? -0.2f : 0.0f; + return; + } + if (flight_ground(state->vehicle, &vehicle->object.position, &ground)) + clearance = vehicle->object.position.z - ground; + { + real desired_vertical = clearance < state->height + 10.0f ? -0.04f : -0.15f; + real speed = MAX(0.1f, magnitude3d(&vehicle->object.translational_velocity)); + pitch = PIN((real)atan2(desired_vertical, speed) + + (desired_vertical - vehicle->object.translational_velocity.k) * 2.0f, -0.2f, 0.65f); + throttle = 0.6f; + if (clearance < state->height + 25.0f) + { + struct physics_definition *physics = flight_physics(state->vehicle); + /* The newer fighter model can approach at low forward speed. + Keep a positive steering input: reverse can engage its authored + brake flag, which zeros the velocity-correction force. */ + if (!physics || physics->radius <= 0.0f) + { + desired_vertical = -0.025f; + /* Very low thrust also caps the force opposing gravity. + Retain control authority while slowing the approach. */ + throttle = 0.3f; + pitch = PIN((real)atan2(desired_vertical, speed) + + (desired_vertical - vehicle->object.translational_velocity.k) * 4.0f, -0.1f, 0.65f); + } + } + /* Forward-flight craft descend in a circuit around the landing + point. Continuing straight would carry them far beyond the objective + while losing altitude. The radial term keeps the circuit bounded. */ + { + real_point3d const *site = state->landing_ready ? &state->landing : &state->destination; + real dx = site->x - position->x; + real dy = site->y - position->y; + real range = (real)sqrt(dx * dx + dy * dy); + real orbit = MAX(12.0f, state->radius * 2.0f); + if (range > 0.1f) + heading = (real)atan2(dy, dx) + 1.57079633f - + PIN((range - orbit) / orbit, -1.0f, 1.0f) * 1.57079633f; + } + } + for (turn = 0; turn < 4; turn++) + { + real yaw = heading + turn * 1.57079633f; + real_point3d next = *position; + next.x += (real)cos(yaw) * reach; + next.y += (real)sin(yaw) * reach; + next.z += reach * pitch; + if (!flight_sweep(state->vehicle, position, &next, state->radius, state->height, TRUE)) continue; + action->desired_facing.yaw = yaw; + action->desired_facing.pitch = pitch; + action->throttle.i = turn == 0 ? throttle : 0.0f; + return; + } +} + +static void flight_begin(struct flight_state *state, real_point3d const *start, real_point3d const *target) +{ + state->target = *target; + state->count = 1; + state->expanded = 0; + state->step = state->step_count = 0; + state->searching = TRUE; + state->nodes[0].point = *start; + state->nodes[0].cost = 0.0f; + state->nodes[0].estimate = flight_distance(start, target); + state->nodes[0].parent = NONE; + state->nodes[0].closed = FALSE; +} + +/* Retain a validated prefix when a large map exceeds one search slice. +The next search starts where that prefix ends, rather than retrying forever +at the same place. Partial answers must reduce distance to the destination. */ +static void flight_route(struct flight_state *state, long best, boolean complete) +{ + real_point3d reverse[FLIGHT_NODES]; + long count = 0, at = best, node; + if (complete) reverse[count++] = state->target; + while (at > 0 && count < FLIGHT_NODES) + { + reverse[count++] = state->nodes[at].point; + at = state->nodes[at].parent; + } + state->step_count = (short)MIN(count, FLIGHT_STEPS); + for (node = 0; node < state->step_count; node++) + state->steps[node] = reverse[count - 1 - node]; + state->step = 0; + state->searching = FALSE; +} + +static boolean flight_segment(struct flight_state const *state, real_point3d const *a, real_point3d const *b) +{ + real dx = b->x - a->x, dy = b->y - a->y; + /* A clear ray is not a flyable shortcut when it requires a forward-flight + craft to climb vertically or exceed its commanded pitch. */ + if (!state->hovering && fabs(b->z - a->z) > 0.5f * sqrt(dx * dx + dy * dy)) + return FALSE; + return flight_clear(state->vehicle, a, b, state->radius, state->height); +} + +/* Each aircraft gets one slice every eight ticks, independent of player +iteration order. Full searches and unreachable destinations have a cooldown. */ +static void flight_search(long index, struct flight_state *state) +{ + long work; + if ((game_time_get() + index) % 8) + return; + for (work = 0; work < 4 && state->searching; work++) + { + long node, best = NONE, x, y, z; + real score = REAL_MAX; + struct flight_node *from; + for (node = 0; node < state->count; node++) + if (!state->nodes[node].closed && state->nodes[node].cost + state->nodes[node].estimate < score) + { + best = node; + score = state->nodes[node].cost + state->nodes[node].estimate; + } + if (best == NONE || state->count >= FLIGHT_NODES || state->expanded >= 256) + { + long closest = 0; + for (node = 1; node < state->count; node++) + if (state->nodes[node].estimate < state->nodes[closest].estimate) closest = node; + if (closest && state->nodes[closest].estimate + state->spacing * 0.5f < state->nodes[0].estimate) + flight_route(state, closest, FALSE); + else + { + state->searching = FALSE; + state->retry = game_time_get() + TICKS_PER_SECOND * 3; + } + return; + } + from = &state->nodes[best]; + from->closed = TRUE; + state->expanded++; + if (flight_segment(state, &from->point, &state->target)) + { + flight_route(state, best, TRUE); + return; + } + /* A transport leaving a roofed hangar can climb as soon as its + whole hull clears the roof, without filling the grid with tiny + altitude steps across a very large map. */ + if (state->hovering && state->target.z > from->point.z + state->spacing) + { + real_point3d above = from->point; + above.z = state->target.z; + if (flight_segment(state, &from->point, &above) && flight_segment(state, &above, &state->target)) + { + long climb = state->count++; + state->nodes[climb].point = above; + state->nodes[climb].parent = (short)best; + flight_route(state, climb, TRUE); + return; + } + } + /* Sloped segments are flyable without requiring a fixed-wing craft + to stop and climb straight upward. VTOL physics may also use vertical + segments. Four expansions bound each slice of this larger graph. */ + for (x = -1; x <= 1 && state->count < FLIGHT_NODES; x++) + for (y = -1; y <= 1 && state->count < FLIGHT_NODES; y++) + for (z = -1; z <= 1 && state->count < FLIGHT_NODES; z++) + { + real_point3d next = from->point; + real edge_cost; + long existing; + if ((!x && !y && !z) || (!x && !y && !state->hovering)) continue; + next.x += x * state->spacing; + next.y += y * state->spacing; + next.z += z * state->spacing * 0.5f; + edge_cost = flight_distance(&from->point, &next); + for (existing = 0; existing < state->count; existing++) + if (fabs(state->nodes[existing].point.x - next.x) < state->spacing * 0.25f && + fabs(state->nodes[existing].point.y - next.y) < state->spacing * 0.25f && + fabs(state->nodes[existing].point.z - next.z) < state->spacing * 0.25f) + break; + if (existing < state->count) + { + if (from->cost + edge_cost < state->nodes[existing].cost && + flight_segment(state, &from->point, &next)) + { + state->nodes[existing].cost = from->cost + edge_cost; + state->nodes[existing].parent = (short)best; + state->nodes[existing].closed = FALSE; + } + continue; + } + if (!flight_segment(state, &from->point, &next)) continue; + state->nodes[state->count].point = next; + state->nodes[state->count].cost = from->cost + edge_cost; + state->nodes[state->count].estimate = flight_distance(&next, &state->target); + state->nodes[state->count].parent = (short)best; + state->nodes[state->count].closed = FALSE; + state->count++; + } + } +} + +/* Human-plane neutral lift is slightly below gravity. Stabilize while a +search is pending instead of falling back onto the ground and restarting +takeoff before the search can finish. */ +static void flight_hold(struct flight_state const *state, struct object_datum const *vehicle, struct player_action *action) +{ + if (!state->hovering) return; + if (vehicle->object.translational_velocity.k < -0.005f) + action->control_flags |= FLAG(_unit_control_jump_bit); + else if (vehicle->object.translational_velocity.k > 0.02f) + action->control_flags |= FLAG(_unit_control_crouch_modifier_bit); +} + +void enhanced_flight_action(long index, long vehicle_index, boolean hovering, real_point3d const *goal, boolean land, boolean wait, + struct player_action *action) +{ + struct flight_state *state = &flights[index]; + struct object_datum *vehicle = object_get(vehicle_index); + real_point3d position = vehicle->object.bounding_sphere_center, target; + real ground, dx, dy, horizontal, pitch, yaw, heading, offset, speed; + long now = game_time_get(); + long trace = PIN(config_integer("debug.bot_trace"), 0, 3600) * TICKS_PER_SECOND; + real_point3d const *waypoint = state->step < state->step_count ? &state->steps[state->step] : &state->target; + if (trace && !(now % trace)) + { + platform_log("bots: flight %ld phase %d search %d nodes %d expanded %d route %d/%d waypoint %.1f %.1f %.1f cruise %.1f remaining %.1f failed %d", + index + 1, state->phase, state->searching, state->count, state->expanded, + state->step, state->step_count, (double)waypoint->x, (double)waypoint->y, (double)waypoint->z, (double)state->cruise_height, (double)state->remaining, state->failed); + platform_log("bots: flight motion position %.2f %.2f %.2f velocity %.3f %.3f %.3f up %.2f ground %d health %.2f", + (double)vehicle->object.position.x, (double)vehicle->object.position.y, (double)vehicle->object.position.z, + (double)vehicle->object.translational_velocity.i, (double)vehicle->object.translational_velocity.j, + (double)vehicle->object.translational_velocity.k, (double)vehicle->object.up.k, + vehicle_datum_get(vehicle_index)->vehicle.on_ground_ticks, (double)vehicle->object.body_vitality); + } + if (state->vehicle != vehicle_index) + { + enhanced_flight_reset(index); + state->vehicle = vehicle_index; + state->radius = MAX(vehicle->object.bounding_sphere_radius, 0.5f); + /* Large hulls still need small steps to align with hangar exits. */ + state->spacing = MAX(4.0f, MIN(12.0f, state->radius * 0.5f + 2.0f)); + state->destination = *goal; + state->landing_ready = state->landing_checked = FALSE; + state->progress_tick = now; + state->remaining = flight_distance(&position, goal); + state->cruise_height = flight_cruise_height(vehicle_index, &position, goal, flight_height(vehicle_index)); + } + state->hovering = hovering; + state->height = flight_height(vehicle_index); + /* The flight controller owns steering even while waiting for a route. + Do not leave the combat controller's aim on an aircraft with no path. */ + heading = (real)atan2(vehicle->object.forward.j, vehicle->object.forward.i); + action->desired_facing.yaw = heading; + action->desired_facing.pitch = 0.0f; + action->throttle.i = action->throttle.j = 0.0f; + action->primary_trigger = 0.0f; + action->control_flags &= ~(FLAG(_unit_control_weapon_primary_trigger_bit) | FLAG(_unit_control_jump_bit) | + FLAG(_unit_control_crouch_modifier_bit)); + if (wait && enhanced_flight_can_exit(vehicle_index)) + return; + if (flight_distance(&state->destination, goal) > 6.0f) + { + state->destination = *goal; + state->landing_ready = state->landing_checked = FALSE; + state->progress_tick = now; + state->remaining = flight_distance(&position, goal); + state->searching = FALSE; + state->step_count = 0; + state->retry = 0; + state->phase = _flight_cruise; + state->cruise_height = flight_cruise_height(vehicle_index, &position, goal, state->height); + } + if (land && !state->landing_checked) + { + state->landing_checked = TRUE; + state->landing_ready = flight_landing_site(state, goal); + if (!state->landing_ready) state->failed = TRUE; + } + if (land && state->landing_ready) goal = &state->landing; + target = *goal; + target.z = state->cruise_height; + /* A blocked aircraft must not hold its bot's objective indefinitely. + Recover over known ground, then let ordinary exit input resume walking. */ + if (flight_distance(&position, goal) + 1.0f < state->remaining) + { + state->remaining = flight_distance(&position, goal); + state->progress_tick = now; + } + if (now - state->progress_tick > 45 * TICKS_PER_SECOND && flight_ground(vehicle_index, &position, &ground)) + state->failed = TRUE; + if (state->failed || (land && state->phase == _flight_land)) + { + flight_descend(state, &position, action); + return; + } + dx = goal->x - position.x; + dy = goal->y - position.y; + horizontal = (real)sqrt(dx * dx + dy * dy); + speed = magnitude3d(&vehicle->object.translational_velocity); + /* Brake before a fast custom craft reaches the destination, and keep + the approach committed as it slows instead of oscillating into cruise. */ + if (land && (state->phase >= _flight_approach || + horizontal < MAX(MAX(MAX(10.0f, state->radius * 2.0f), hovering ? 0.0f : (position.z - goal->z) * 2.0f), + speed * speed * 100.0f + speed * 20.0f))) + { + state->phase = _flight_approach; + target = *goal; + if (flight_ground(vehicle_index, goal, &ground)) target.z = ground; + target.z += state->height + 0.5f; + /* Hover aircraft align with the validated descent column first. + A diagonal approach can intersect a nearby roof or hangar wall. */ + if (hovering) target.z = MAX(position.z, target.z); + if (horizontal < MAX(2.0f, state->radius * 0.5f) || + (!hovering && horizontal < MAX(60.0f, state->radius * 2.0f) && position.z - target.z < 25.0f)) + { + state->phase = _flight_land; + flight_descend(state, &position, action); + return; + } + } + else if (flight_ground(vehicle_index, &position, &ground) && position.z - ground < state->height + 4.0f) + { + state->phase = _flight_takeoff; + target = position; + /* Turn toward the departure route, not into the wall a parked + aircraft may face. Lift while turning before applying forward thrust. */ + target.x += (horizontal > 1.0f ? dx / horizontal : vehicle->object.forward.i) * state->spacing; + target.y += (horizontal > 1.0f ? dy / horizontal : vehicle->object.forward.j) * state->spacing; + target.z += state->spacing; + } + else + state->phase = _flight_cruise; + if (state->phase == _flight_cruise) + { + if (state->step < state->step_count && + flight_distance(&position, &state->steps[state->step]) < MAX(1.0f, MIN(3.0f, state->radius * 0.25f))) + state->step++; + if (state->step >= state->step_count && !state->searching && now >= state->retry) + flight_begin(state, &position, &target); + if (state->searching) + flight_search(index, state); + /* Look ahead through already validated route points, then recheck + the shortcut against the current hull attitude. Heavy transports + cannot stop and turn at every small grid cell. */ + if (state->step < state->step_count && !((now + index) % 8)) + { + long look = MIN(state->step_count - 1, state->step + 8); + for (; look > state->step; look--) + if (flight_segment(state, &position, &state->steps[look])) + { state->step = (short)look; break; } + } + if (state->step < state->step_count) + target = state->steps[state->step]; + else + { + flight_hold(state, vehicle, action); + return; + } + } + /* A climb or detour can increase distance to the final objective. + Measure progress toward the current waypoint as well, so a heavy craft + climbing out of a hangar is not declared stuck after 45 seconds. */ + if (flight_distance(&state->progress_target, &target) > 1.0f) + { + state->progress_target = target; + state->waypoint_remaining = flight_distance(&position, &target); + } + else if (flight_distance(&position, &target) + 1.0f < state->waypoint_remaining) + { + state->waypoint_remaining = flight_distance(&position, &target); + state->progress_tick = now; + } + if (!flight_clear(vehicle_index, &position, &target, state->radius, state->height)) + { + state->step_count = 0; + state->searching = FALSE; + state->retry = now + TICKS_PER_SECOND; + if (state->phase == _flight_cruise) flight_hold(state, vehicle, action); + return; + } + dx = target.x - position.x; + dy = target.y - position.y; + horizontal = (real)sqrt(dx * dx + dy * dy); + if (hovering && horizontal < MAX(1.0f, state->spacing * 0.25f) && fabs(target.z - position.z) > 1.0f) + { + /* Human-plane tags implement vertical lift through ordinary jump + and crouch input; forward thrust cannot reach a vertical waypoint. */ + action->control_flags |= FLAG(target.z > position.z ? _unit_control_jump_bit : _unit_control_crouch_modifier_bit); + return; + } + yaw = horizontal > 0.1f ? (real)atan2(dy, dx) : heading; + pitch = (real)atan2(target.z - position.z, MAX(horizontal, 1.0f)); + offset = (real)atan2(sin(yaw - heading), cos(yaw - heading)); + /* Player actions carry an absolute desired heading. The authored + vehicle physics limits the turn; a tiny heading increment would starve + heavy aircraft of steering torque and make them circle or stall. */ + action->desired_facing.yaw = yaw; + /* Human-plane lift follows the hull up vector. Pitching up at low + thrust tips that lift backwards: a heavy transport slides away from its + route. Keep hover craft level and control altitude with lift input. */ + action->desired_facing.pitch = hovering ? 0.0f : PIN(pitch, -0.5f, 0.65f); + /* Both fighter models need forward input: the newer model also + scales its velocity correction by throttle, so zero cannot arrest a + fall even when the authored antigravity provides little support. */ + if (!state->hovering) + { + real forward_speed = MAX(0.1f, speed); + real desired_vertical = PIN((target.z - position.z) * 0.03f, -0.15f, 0.25f); + action->desired_facing.pitch = PIN((real)atan2(desired_vertical, forward_speed) + + (desired_vertical - vehicle->object.translational_velocity.k) * 2.0f, -0.35f, 0.65f); + } + if (hovering && target.z > position.z + 1.0f) + action->control_flags |= FLAG(_unit_control_jump_bit); + else if (hovering && target.z < position.z - 1.0f) + action->control_flags |= FLAG(_unit_control_crouch_modifier_bit); + if (!hovering) + /* Forward-flight craft need airspeed to take off as well as cruise. */ + action->throttle.i = state->phase == _flight_approach ? 0.6f : + state->phase == _flight_takeoff && fabs(offset) > 0.8f ? 0.0f : 0.8f; + else if (state->phase == _flight_takeoff) + action->throttle.i = fabs(offset) > 0.8f ? 0.0f : 0.35f; + else if (state->phase == _flight_approach) + action->throttle.i = speed > 0.08f ? 0.0f : 0.2f; + else if (fabs(offset) <= 0.8f) + action->throttle.i = horizontal < state->spacing ? 0.35f : 0.8f; +} diff --git a/port/linux/game/enhanced_bots_flight.h b/port/linux/game/enhanced_bots_flight.h new file mode 100644 index 0000000000..7c197ccfbb --- /dev/null +++ b/port/linux/game/enhanced_bots_flight.h @@ -0,0 +1,10 @@ +#ifndef ENHANCED_BOTS_FLIGHT_H +#define ENHANCED_BOTS_FLIGHT_H +struct player_action; +void enhanced_flight_reset(long index); +void enhanced_flight_action(long index, long vehicle_index, boolean hovering, real_point3d const *goal, + boolean land, boolean wait, struct player_action *action); +boolean enhanced_flight_landing(long index); +boolean enhanced_flight_failed(long index); +boolean enhanced_flight_can_exit(long vehicle_index); +#endif diff --git a/port/linux/game/first_person_legs.c b/port/linux/game/first_person_legs.c index 6f578a371d..6464dd4daa 100644 --- a/port/linux/game/first_person_legs.c +++ b/port/linux/game/first_person_legs.c @@ -1,58 +1,88 @@ /* FIRST_PERSON_LEGS.C -Your own legs in first person (Video Setup > FOV and Viewmodels > Legs): the -player's own body, which the game animates as everyone else sees it but does -not draw for its own player, drawn from the waist down. Look down while -standing, running, strafing or crouching and the legs move as the body's -animation moves them. - -Only the drawing is changed: a copy of the body's pose, all but its hips and -legs folded into a lid over the waist, the whole set back a little behind -the eye so the camera never looks out through the hips. The body itself, its hit boxes and markers, are the game's -as ever. The legs are drawn in the world with the world's camera, so they -keep their place and size at any field of view. +Your own legs in first person (Video Setup > FOV and Viewmodels > Legs, +display.first_person_legs; off, the stock game's: the body not drawn in its +own player's view). The body the game animates for everyone else is drawn +for its own player too, from the waist down: looking down while standing, +running or crouching, the legs move as the body's animation moves them. + +Only the drawing changes, and only in that player's first-person view: its +shadow, its reflection, its hit boxes and markers are the game's as ever, +and nothing it carries or wears (its weapons, its children, its widgets) is +drawn with it. + +The skeleton identifies the legs, torso, head and arms. The copied pose +keeps every bone's original scale and animation: folding torso bones into +the pelvis distorts the blended waist skin into a pouch. Feature-owned +index buffers omit the head and arms while retaining the intact torso-to- +hip surface (first_person_legs_geometry.c). The actual animated upper +surface and cut boundaries determine clearance, so no opening enters the +view as the player walks, crouches or changes FOV. + +The pose is each local player's own (split-screen views draw their own +bodies). It is turned about the hips from the body's facing to the view's: +the game turns a standing body only once the aim is well away from it, and +slowly, and one in the air not at all, so the legs drawn as they face would +lag behind the view and, after a jump's turn, stand in front of it. It is +set back along the view's level facing, by at least FIRST_PERSON_LEGS_SET_BACK. +The clearance uses the animated surface, eye height and FOV, not the +current look pitch. Looking up and down alone does not slide the pose. */ #include "cseries.h" #include "real_math.h" -#include "objects/objects.h" +#include "camera/director.h" +#include "game/players.h" #include "models/model_definitions.h" -#include "units/units.h" +#include "objects/objects.h" +#include "objects/object_definitions.h" +#include "objects/object_types.h" #include "render/render.h" -#include "rasterizer/rasterizer.h" -#include -#include "rasterizer/xbox/rasterizer_xbox.h" - -#include "object_mesh.h" +#include "render/render_cameras.h" +#include "tag_files/tag_groups.h" +#include "units/biped_definitions.h" +#include "first_person_legs.h" +#include "first_person_legs_geometry.h" -#include +enum +{ + FIRST_PERSON_LEGS_MODELS = 8, +}; +/* how far behind the eye the body is drawn, world units (about 49 cm), along +the view's level facing (tuned in-game) */ +#define FIRST_PERSON_LEGS_SET_BACK 0.16f /* port/linux/src/port_config.c */ int config_boolean(const char *name); unsigned long config_changes(void); +/* port/linux/src (halo.log) */ +void platform_log(const char *format, ...); -enum +/* ---------- globals */ + +/* a biped definition's legs, as its skeleton has them */ +struct first_person_legs_model { - FIRST_PERSON_LEGS_MAXIMUM_NODES = 64, - FIRST_PERSON_LEGS_MAXIMUM_RIM = 64, + long definition_index; /* NONE: free */ + /* the pelvis's child towards the head; NONE: no legs to draw */ + short spine_node_index; + /* TRUE: head/arm geometry omitted from the local body */ + boolean omitted[MAXIMUM_NODES_PER_MODEL]; + boolean lower[MAXIMUM_NODES_PER_MODEL]; + short geometry_status; /* 0: unprepared, 1: ready, -1: unsupported */ }; -/* how far the body is set back behind the eye at least, world units (about -12 cm), and at most (about 1 m) */ -#define FIRST_PERSON_LEGS_SET_BACK 0.04f -#define FIRST_PERSON_LEGS_SET_BACK_MAXIMUM 0.33f -/* how far out of the view the waist's rim is kept (world units: 3 cm) */ -#define FIRST_PERSON_LEGS_OUT_OF_VIEW 0.01f -/* the point the upper body folds into: the middle of the waist's rim, a -little above it (world units: about 3 cm), so the skin that joined hips to -chest closes the waist as a low lid, flush with the belt (the body's model is -a hollow shell: folded higher, it stood up as a cone before the eye; lower, -it sank into a funnel) */ -#define FIRST_PERSON_LEGS_LID_UP 0.01f - -static real_matrix4x3 first_person_legs_matrices[FIRST_PERSON_LEGS_MAXIMUM_NODES]; +static struct first_person_legs_model first_person_legs_models[FIRST_PERSON_LEGS_MODELS]; +static short first_person_legs_next_model = 0; +static boolean first_person_legs_models_valid = FALSE; + +/* each local player's pose of its legs, rewritten as its view is drawn */ +static real_matrix4x3 first_person_legs_matrices[MAXIMUM_LOCAL_PLAYERS][MAXIMUM_NODES_PER_MODEL]; + +/* ---------- private code */ + static boolean first_person_legs_enabled( void) { @@ -62,248 +92,305 @@ static boolean first_person_legs_enabled( if (changes != config_changes()) { changes = config_changes(); + if (enabled && !config_boolean("display.first_person_legs")) + first_person_legs_reset(); enabled = config_boolean("display.first_person_legs") != 0; } return enabled; } -/* the player's own unit, seen from inside it: its legs drawn (on foot, -alive, not hidden) */ -boolean first_person_legs_wanted( - long object_index) -{ - struct object_datum *object = object_try_and_get(object_index); - - return first_person_legs_enabled() && object && object->object.type == _object_type_biped && - object->object.parent_object_index == NONE && - !TEST_FLAG(object->object.damage_flags, _object_dead_bit) && - !TEST_FLAG(object->object.flags, _object_invisible_bit); -} - -/* whether a node's name has part in it, whatever its case (the game's -characters name theirs "bip01 l thigh", "Bip01 Pelvis") */ -static boolean first_person_legs_name_has( - char const *name, - char const *part) -{ - char lower[TAG_STRING_LENGTH + 1]; - short index; - - for (index = 0; index < TAG_STRING_LENGTH && name[index]; index++) - lower[index] = (char)(name[index] >= 'A' && name[index] <= 'Z' ? name[index] - 'A' + 'a' : name[index]); - lower[index] = 0; - return strstr(lower, part) != NULL; -} - -/* a node of the legs: the hips, thighs, calves, feet and toes */ -static boolean first_person_legs_node( - char const *name) +/* whether ancestor is node or above it (a map's parents are followed no +further than there are nodes, so a loop ends) */ +static boolean first_person_legs_below( + struct model const *model, + short node_count, + short node_index, + short ancestor_index) { - static char const *const parts[] = { "pelvis", "thigh", "calf", "foot", "toe", "leg" }; - short index; + short steps; - for (index = 0; index < (short)NUMBEROF(parts); index++) + for (steps = 0; steps <= node_count && node_index >= 0 && node_index < node_count; steps++) { - if (first_person_legs_name_has(name, parts[index])) + if (node_index == ancestor_index) return TRUE; + node_index = TAG_BLOCK_GET_ELEMENT(&model->nodes, node_index, struct model_node)->parent_node_index; } return FALSE; } -/* the middle of the waist's rim in the model's space: the hips' vertices -on triangles that run up into the body above them (FALSE: none), kept for -the mesh it was found in (a new map forgets it: first_person_legs_reset) */ -static real_point3d first_person_legs_rim[FIRST_PERSON_LEGS_MAXIMUM_RIM]; -static short first_person_legs_rim_count = 0; -static long first_person_legs_waist_key = NONE; -static long first_person_legs_waist_model = NONE; -static boolean first_person_legs_waist_found = FALSE; -static real_point3d first_person_legs_waist_middle; - -/* a new map: the waist found, and the mesh it was found in, forgotten (the -new map's models have indices of their own) */ -void first_person_legs_reset( - void) -{ - first_person_legs_waist_key = NONE; - first_person_legs_waist_model = NONE; - first_person_legs_rim_count = 0; - object_mesh_reset(); -} - -static boolean first_person_legs_waist( - struct object_mesh const *mesh, +/* a skeleton's legs, from its pelvis and head: the spine node, or NONE (and +why not, for the log) */ +static short first_person_legs_find( struct model const *model, - short pelvis, - real_point3d *middle) + short node_count, + short pelvis_index, + short head_index, + boolean *omitted, + char const **reason) { - real_point3d sum = { 0.f, 0.f, 0.f }; - long found = 0; - long index; + short spine_index = NONE; + short leg_count = 0; + short node_index; + short steps; - if (mesh->key == first_person_legs_waist_key && mesh->model_index == first_person_legs_waist_model) + if (pelvis_index < 0 || pelvis_index >= node_count || head_index < 0 || head_index >= node_count || + head_index == pelvis_index) { - *middle = first_person_legs_waist_middle; - return first_person_legs_waist_found; + *reason = "no pelvis and head nodes"; + return NONE; } - first_person_legs_rim_count = 0; - for (index = 0; index < mesh->triangle_count; index++) + /* (the spine: the head's ancestor whose parent is the pelvis) */ + node_index = head_index; + for (steps = 0; steps <= node_count && node_index >= 0 && node_index < node_count; steps++) { - boolean hips = FALSE; - boolean above = FALSE; - short corner; + short parent_index = TAG_BLOCK_GET_ELEMENT(&model->nodes, node_index, struct model_node)->parent_node_index; - for (corner = 0; corner < 3; corner++) + if (parent_index == pelvis_index) { - struct object_mesh_vertex const *vertex = &mesh->vertices[mesh->triangles[index][corner]]; - short n; - - if (vertex->nodes[0] == pelvis && (vertex->nodes[1] == pelvis || vertex->weight >= 32767)) - hips = TRUE; - for (n = 0; n < 2; n++) - { - if (vertex->nodes[n] < model->nodes.count && (n == 0 || vertex->weight < 32767) && - !first_person_legs_node(TAG_BLOCK_GET_ELEMENT(&model->nodes, vertex->nodes[n], struct model_node)->name)) - { - above = TRUE; - } - } + spine_index = node_index; + break; } - if (!hips || !above) - continue; - for (corner = 0; corner < 3; corner++) + node_index = parent_index; + } + if (spine_index == NONE) + { + *reason = "its head is not below its pelvis"; + return NONE; + } + for (node_index = 0; node_index < node_count; node_index++) + { + /* (the pelvis and the frames above it are the body's place, kept) */ + if (first_person_legs_below(model, node_count, pelvis_index, node_index)) + omitted[node_index] = FALSE; + else if (first_person_legs_below(model, node_count, node_index, pelvis_index) && + !first_person_legs_below(model, node_count, node_index, spine_index)) { - struct object_mesh_vertex const *vertex = &mesh->vertices[mesh->triangles[index][corner]]; - - if (vertex->nodes[0] == pelvis && (vertex->nodes[1] == pelvis || vertex->weight >= 32767)) - { - sum.x += vertex->position.x; - sum.y += vertex->position.y; - sum.z += vertex->position.z; - found++; - if (first_person_legs_rim_count < FIRST_PERSON_LEGS_MAXIMUM_RIM) - first_person_legs_rim[first_person_legs_rim_count++] = vertex->position; - } + omitted[node_index] = FALSE; + leg_count++; } + else if (node_index != head_index && + first_person_legs_below(model, node_count, head_index, node_index)) + omitted[node_index] = FALSE; + else + omitted[node_index] = TRUE; } - first_person_legs_waist_key = mesh->key; - first_person_legs_waist_model = mesh->model_index; - first_person_legs_waist_found = found > 0; - if (found > 0) + if (leg_count == 0) { - first_person_legs_waist_middle.x = sum.x / found; - first_person_legs_waist_middle.y = sum.y / found; - first_person_legs_waist_middle.z = sum.z / found + FIRST_PERSON_LEGS_LID_UP; + *reason = "no nodes below its pelvis but its spine"; + return NONE; } - *middle = first_person_legs_waist_middle; - return first_person_legs_waist_found; + return spine_index; } -/* the pose to draw the legs with: the body's own (as it is drawn now), all -but the legs folded into the hips, the whole set back behind the eye; NULL: -none (a body without named legs) */ -real_matrix4x3 const *first_person_legs_node_matrices( - long object_index, - real_matrix4x3 const *nodes) +/* a biped definition's legs, found once (and, when it has none, said once) */ +static struct first_person_legs_model *first_person_legs_model_get( + long definition_index, + struct model const *model, + short node_count, + short pelvis_index, + short head_index) { - struct object_datum *object = object_try_and_get(object_index); - struct object_definition *definition; - struct model const *model; - long count; - short pelvis = NONE; - short thighs = 0; + struct first_person_legs_model *entry; + char const *reason = ""; short index; - real_point3d fold; + + if (!first_person_legs_models_valid) + first_person_legs_reset(); + for (index = 0; index < FIRST_PERSON_LEGS_MODELS; index++) + { + if (first_person_legs_models[index].definition_index == definition_index) + return &first_person_legs_models[index]; + } + entry = &first_person_legs_models[first_person_legs_next_model]; + first_person_legs_next_model = (short)((first_person_legs_next_model + 1) % FIRST_PERSON_LEGS_MODELS); + entry->definition_index = definition_index; + entry->geometry_status = 0; + entry->spine_node_index = first_person_legs_find(model, node_count, pelvis_index, head_index, + entry->omitted, &reason); + for (index = 0; index < node_count; index++) + entry->lower[index] = index != pelvis_index && + first_person_legs_below(model, node_count, index, pelvis_index) && + !first_person_legs_below(model, node_count, index, entry->spine_node_index); + if (entry->spine_node_index == NONE) + platform_log("first-person legs: %s has %s; its legs are not drawn\n", tag_get_name(definition_index), reason); + return entry; +} + +/* the way the view looks, level: its forward's level part, with its up's +(which points the way the forward did) so that looking straight down or up +it still has one; FALSE for none */ +static boolean first_person_legs_view_heading( + real_vector3d const *forward, + real_vector3d const *up, + real_vector3d *heading) +{ + heading->i = forward->i - forward->k * up->i; + heading->j = forward->j - forward->k * up->j; + heading->k = 0.f; + return normalize3d(heading) > 0.f; +} + +/* the way the body faces, level, in the pose drawn: the object's facing (as +the last tick turned it), taken into its first node's frame as that tick +left it, and out of that node's frame as drawn (between ticks), so the body +turns as smoothly as its pose; FALSE for none */ +static boolean first_person_legs_body_heading( + real_vector3d const *facing, + real_matrix4x3 const *tick_root, + real_matrix4x3 const *drawn_root, + real_vector3d *heading) +{ + real forward = dot_product3d(facing, &tick_root->forward); + real left = dot_product3d(facing, &tick_root->left); + real up = dot_product3d(facing, &tick_root->up); + + heading->i = forward * drawn_root->forward.i + left * drawn_root->left.i + up * drawn_root->up.i; + heading->j = forward * drawn_root->forward.j + left * drawn_root->left.j + up * drawn_root->up.j; + heading->k = 0.f; + return normalize3d(heading) > 0.f; +} + +/* a vector turned about the vertical by the angle whose cosine and sine +these are */ +static void first_person_legs_turn( + real_vector3d *vector, + real cosine, + real sine) +{ + real i = vector->i; + + vector->i = cosine * i - sine * vector->j; + vector->j = sine * i + cosine * vector->j; +} + +/* ---------- public code */ + +void first_person_legs_reset( + void) +{ + short index; + + first_person_legs_geometry_reset(); + for (index = 0; index < FIRST_PERSON_LEGS_MODELS; index++) + first_person_legs_models[index].definition_index = NONE; + first_person_legs_next_model = 0; + first_person_legs_models_valid = TRUE; +} + +real_matrix4x3 const *first_person_legs_node_matrices( + short local_player_index, + long object_index) +{ + struct object_datum *object; + struct biped_definition *definition; + struct model *model; + struct first_person_legs_model *legs; + real_matrix4x3 const *nodes; + real_matrix4x3 *pose; + real_vector3d view; + real_vector3d body; real_vector3d back; - real_matrix4x3 skin; + real_point3d pivot; real set_back; + real cosine = 1.f; + real sine = 0.f; + long player_index; + short node_count; + short index; - if (!object || !nodes) + if (!first_person_legs_enabled() || local_player_index < 0 || local_player_index >= MAXIMUM_LOCAL_PLAYERS || + director_get_perspective(local_player_index) != _director_perspective_first_person) + { return NULL; - definition = object_definition_get(object->definition_index); + } + /* (the player's own living, visible biped, on foot) */ + player_index = local_player_get_player_index(local_player_index); + object = object_try_and_get(object_index); + if (player_index == NONE || player_get(player_index)->unit_index != object_index || !object || + object->object.type != _object_type_biped || object->object.parent_object_index != NONE || + TEST_FLAG(object->object.damage_flags, _object_dead_bit) || + TEST_FLAG(object->object.flags, _object_invisible_bit)) + { + return NULL; + } + definition = biped_definition_get(object->definition_index); if (!definition || definition->object.model.index == NONE) return NULL; model = model_definition_get(definition->object.model.index); - count = object->object.node_matrices.size / (long)sizeof(real_matrix4x3); - if (!model || count <= 0 || count > FIRST_PERSON_LEGS_MAXIMUM_NODES || model->nodes.count < count) + node_count = (short)MIN(model->nodes.count, MAXIMUM_NODES_PER_MODEL); + /* (the object's own matrices, as many as the model's nodes) */ + if (node_count <= 0 || object->object.node_matrices.size < node_count * (long)sizeof(real_matrix4x3)) return NULL; - - for (index = 0; index < count; index++) + legs = first_person_legs_model_get(object->definition_index, model, node_count, + definition->biped.runtime_pelvis_node_index, definition->biped.runtime_head_node_index); + if (legs->spine_node_index == NONE) + return NULL; + if (!legs->geometry_status) { - struct model_node const *node = TAG_BLOCK_GET_ELEMENT(&model->nodes, index, struct model_node); - - if (pelvis == NONE && first_person_legs_name_has(node->name, "pelvis")) - pelvis = index; - if (first_person_legs_name_has(node->name, "thigh")) - thighs++; + legs->geometry_status = first_person_legs_geometry_prepare(object->definition_index, + model, legs->omitted, legs->lower) ? 1 : -1; + if (legs->geometry_status < 0) + platform_log("first-person legs: %s has unsupported geometry; local body not drawn\n", tag_get_name(object->definition_index)); } - if (pelvis == NONE || thighs == 0) + if (legs->geometry_status < 0) return NULL; - /* (the waist's middle as the hips are posed now) */ - { - struct object_mesh const *mesh = object_mesh_get(object_index); - real_point3d middle; - if (!mesh || pelvis >= mesh->node_count || !first_person_legs_waist(mesh, model, pelvis, &middle)) - return NULL; - matrix4x3_multiply(&nodes[pelvis], &mesh->inverse[pelvis], &skin); - matrix4x3_transform_point(&skin, &middle, &fold); + nodes = object_get_node_matrices(object_index); + pose = first_person_legs_matrices[local_player_index]; + /* (turned from the body's facing, the object's, to the view's; not + from its first node's, which in the game's characters is the pelvis, + its axis up the spine) */ + if (!first_person_legs_view_heading(&render.camera.forward, &render.camera.up, &view)) + return NULL; + else if (first_person_legs_body_heading(&object->object.forward, + (real_matrix4x3 const *)object_header_block_get(object_index, &object->object.node_matrices), + &nodes[0], &body)) + { + cosine = dot_product3d(&body, &view); + sine = body.i * view.j - body.j * view.i; } - - /* (set back away from the way the eye looks, level) */ - back.i = -global_window_parameters.camera.forward.i; - back.j = -global_window_parameters.camera.forward.j; + back.i = -view.i; + back.j = -view.j; back.k = 0.f; - if (normalize3d(&back) <= 0.f) - back = *global_zero_vector3d; - - /* (as far back as keeps the waist's rim out of the bottom of the view, - as Halo 2 keeps its first person body's open top out of it: looking - ahead, the least; looking down, the legs stand behind the eye, the - thighs, knees and feet seen as they swing forward) */ - set_back = FIRST_PERSON_LEGS_SET_BACK; + /* A model may have a separate root above the pelvis. Turn about the + drawn hips so that an offset root does not move them as the view turns. */ + pivot = nodes[definition->biped.runtime_pelvis_node_index].position; + set_back = first_person_legs_geometry_setback(object->definition_index, nodes, &pivot, + cosine, sine, &view, &render.camera.position, render.camera.vertical_field_of_view, FIRST_PERSON_LEGS_SET_BACK); + if (!(set_back < REAL_MAX)) + return NULL; + for (index = 0; index < node_count; index++) { - real_plane3d const *bottom = &global_window_parameters.frustum.world_planes[2]; - real toward = dot_product3d(&bottom->n, &back); - short corner; - - if (toward > 0.05f) + pose[index] = nodes[index]; { - for (corner = 0; corner < first_person_legs_rim_count; corner++) - { - real_point3d p; - real distance; - - matrix4x3_transform_point(&skin, &first_person_legs_rim[corner], &p); - distance = plane3d_distance_to_point(bottom, &p) + toward * FIRST_PERSON_LEGS_SET_BACK; - if (distance < FIRST_PERSON_LEGS_OUT_OF_VIEW) - { - real needed = FIRST_PERSON_LEGS_SET_BACK + (FIRST_PERSON_LEGS_OUT_OF_VIEW - distance) / toward; - - if (needed > set_back) - set_back = needed; - } - } + real x = pose[index].position.x - pivot.x; + real y = pose[index].position.y - pivot.y; + + pose[index].position.x = pivot.x + cosine * x - sine * y + back.i * set_back; + pose[index].position.y = pivot.y + sine * x + cosine * y + back.j * set_back; } - if (set_back > FIRST_PERSON_LEGS_SET_BACK_MAXIMUM) - set_back = FIRST_PERSON_LEGS_SET_BACK_MAXIMUM; + first_person_legs_turn(&pose[index].forward, cosine, sine); + first_person_legs_turn(&pose[index].left, cosine, sine); + first_person_legs_turn(&pose[index].up, cosine, sine); } + return pose; +} - for (index = 0; index < count; index++) - { - struct model_node const *node = TAG_BLOCK_GET_ELEMENT(&model->nodes, index, struct model_node); - real_matrix4x3 *matrix = &first_person_legs_matrices[index]; +struct triangle_buffer const *first_person_legs_triangles( + long object_index, struct model const *model, + struct vertex_buffer const *vertices, struct triangle_buffer const *triangles) +{ + struct object_datum *object = object_try_and_get(object_index); + short index; - *matrix = nodes[index]; - /* (the root kept: it is the body's frame, not a part of it) */ - if (node->parent_node_index != NONE && !first_person_legs_node(node->name)) - { - matrix->position = fold; - matrix->scale = 0.001f; - } - matrix->position.x += back.i * set_back; - matrix->position.y += back.j * set_back; - matrix->position.z += back.k * set_back; + if (!object || !first_person_legs_enabled()) + return NULL; + for (index = 0; index < FIRST_PERSON_LEGS_MODELS; index++) + { + struct first_person_legs_model const *legs = &first_person_legs_models[index]; + if (legs->definition_index == object->definition_index && legs->geometry_status > 0) + return first_person_legs_geometry_get(object->definition_index, model, + legs->omitted, legs->lower, vertices, triangles); } - return first_person_legs_matrices; + return NULL; } diff --git a/port/linux/game/first_person_legs.h b/port/linux/game/first_person_legs.h new file mode 100644 index 0000000000..1ca1468d38 --- /dev/null +++ b/port/linux/game/first_person_legs.h @@ -0,0 +1,27 @@ +/* +FIRST_PERSON_LEGS.H + +The local player's own legs in first person (first_person_legs.c). +*/ + +#ifndef FIRST_PERSON_LEGS_H +#define FIRST_PERSON_LEGS_H + +/* the pose the local player's own body is drawn with in its first-person +view (display.first_person_legs), the legs alone, or NULL: not drawn, as +the stock game does not */ +real_matrix4x3 const *first_person_legs_node_matrices(short local_player_index, long object_index); +/* the bipeds' legs found so far forgotten (a map loaded or unloaded: its +tag indices are another map's) */ +void first_person_legs_reset(void); + +/* Dedicated draw flag, after the four established render_model flags. */ +#define FIRST_PERSON_LEGS_RENDER_FLAG (1UL << 4) +struct model; +struct vertex_buffer; +struct triangle_buffer; +struct triangle_buffer const *first_person_legs_triangles(long object_index, + struct model const *model, struct vertex_buffer const *vertices, + struct triangle_buffer const *triangles); + +#endif diff --git a/port/linux/game/first_person_legs_geometry.c b/port/linux/game/first_person_legs_geometry.c new file mode 100644 index 0000000000..fffc72d3a9 --- /dev/null +++ b/port/linux/game/first_person_legs_geometry.c @@ -0,0 +1,348 @@ +/* +FIRST_PERSON_LEGS_GEOMETRY.C + +Private first-person triangle selection and surface clearance. Head/arm +triangles are omitted; original vertices, palettes, weights and animation +are untouched. Torso triangles stay intact instead of collapsing into a +waist pouch. All retained non-leg vertices, and vertices shared with omitted +triangles, constrain the pose's setback. Their animated positions stay +outside the view even at vertical pitch, so cuts never become visible. + +The map loader validates the source geometry. Counts, formats, indices and +palettes are checked again here before reading. Private buffers survive +queued material/shield draws, have a fixed memory budget, and are released +on disable or map teardown. No buffer is evicted during a frame. +*/ +#include "cseries.h" +#include "real_math.h" +#include "models/model_definitions.h" +#include "rasterizer/rasterizer_geometry.h" +#include "rasterizer/rasterizer_model_types.h" +#include "first_person_legs_geometry.h" +#include +#include + +enum { FIRST_PERSON_LEGS_PARTS = 256, FIRST_PERSON_LEGS_VERTICES = 65535, + FIRST_PERSON_LEGS_TRIANGLES = 65535, FIRST_PERSON_LEGS_BYTES = 16 * 1024 * 1024 }; + +extern short custom_edition_part_palette(struct vertex_buffer const *, byte const **); +extern short mcc_cache_part_palette(void const *, byte const **); +extern void platform_log(char const *, ...); + +struct first_person_legs_boundary +{ + real_point3d local[2]; + short nodes[2]; + real weight; +}; + +/* The engine's validated model-part layout (models.c). No map-family +conversion or buffer ownership changes here. */ +struct first_person_legs_geometry +{ + byte reserved[0x24]; + struct tag_block parts; +}; +struct first_person_legs_source_part +{ + unsigned long flags; + byte reserved[0x1C]; + struct tag_block uncompressed_vertices, compressed_vertices, triangles; + struct triangle_buffer triangle_buffer; + struct vertex_buffer vertex_buffer; +}; +typedef char first_person_legs_part_layout[sizeof(struct first_person_legs_source_part) == 0x68 ? 1 : -1]; + +static struct first_person_legs_part +{ + long definition_index; + struct vertex_buffer const *source_vertices; + struct triangle_buffer const *source_triangles; + struct triangle_buffer triangles; + word *indices; + struct first_person_legs_boundary *boundary; + long boundary_count; + boolean valid; +} first_person_legs_parts[FIRST_PERSON_LEGS_PARTS]; +static short first_person_legs_part_count; +static unsigned long first_person_legs_bytes; + +static boolean first_person_legs_vertex_kept( + struct model_vertex_compressed const *vertex, short node_count, + boolean const *upper, short palette_count, byte const *palette) +{ + short weights[2]; + short index; + + if (vertex->node_weight < 0) + return FALSE; + weights[0] = vertex->node_weight; + weights[1] = 32767 - weights[0]; + for (index = 0; index < 2; index++) + { + short node; + + if (weights[index] == 0) + continue; + if (vertex->nodes[index] % 3) + return FALSE; + node = vertex->nodes[index] / 3; + if (palette_count) + { + if (node >= palette_count) + return FALSE; + node = palette[node]; + } + if (node >= node_count || upper[node]) + return FALSE; + } + return TRUE; +} + +static long first_person_legs_select( + word const *source, long triangle_count, short type, + boolean const *kept, long vertex_count, word *output) +{ + long triangle, count = 0; + + for (triangle = 0; triangle < triangle_count; triangle++) + { + long start = type == _triangle_buffer_type_triangles ? triangle * 3 : triangle; + word a = source[start], b = source[start + 1], c = source[start + 2]; + + if (a >= vertex_count || b >= vertex_count || c >= vertex_count) + return NONE; + if (a == b || a == c || b == c || !kept[a] || !kept[b] || !kept[c]) + continue; + /* Odd strip triangles reverse winding. Degenerates still consume + a position in the strip. */ + output[count * 3] = type == _triangle_buffer_type_precompiled_strip && (triangle & 1) ? b : a; + output[count * 3 + 1] = type == _triangle_buffer_type_precompiled_strip && (triangle & 1) ? a : b; + output[count * 3 + 2] = c; + count++; + } + return count; +} + +struct triangle_buffer const *first_person_legs_geometry_get( + long definition_index, struct model const *model, boolean const *upper, boolean const *lower, + struct vertex_buffer const *vertices, struct triangle_buffer const *triangles) +{ + struct first_person_legs_part *part; + struct model_vertex_compressed const *data = NULL; + word const *source = NULL; + boolean *kept, *used, *edge; + long node_count = model->nodes.count; + byte const *palette = NULL, *mcc_palette = NULL; + short palette_count, mcc_count, index; + long vertex, count; + unsigned long allocation; + + if (!triangles->count) + return NULL; + for (index = 0; index < first_person_legs_part_count; index++) + { + part = &first_person_legs_parts[index]; + if (part->definition_index == definition_index && + part->source_vertices == vertices && part->source_triangles == triangles) + return part->triangles.count ? &part->triangles : NULL; + } + if (first_person_legs_part_count == FIRST_PERSON_LEGS_PARTS) + return NULL; + part = &first_person_legs_parts[first_person_legs_part_count++]; + csmemset(part, 0, sizeof(*part)); + part->definition_index = definition_index; + part->source_vertices = vertices; + part->source_triangles = triangles; + if (node_count <= 0 || node_count > 64 || + vertices->type != _rasterizer_vertex_type_model_compressed || + vertices->count <= 0 || vertices->count > FIRST_PERSON_LEGS_VERTICES || + triangles->count <= 0 || triangles->count > FIRST_PERSON_LEGS_TRIANGLES || + (triangles->type != _triangle_buffer_type_triangles && + triangles->type != _triangle_buffer_type_precompiled_strip) || + !vertices->hardware_format || !triangles->hardware_format) + { + platform_log("first-person legs: unsupported geometry; part not drawn\n"); + return NULL; + } + palette_count = custom_edition_part_palette(vertices, &palette); + mcc_count = mcc_cache_part_palette(vertices, &mcc_palette); + if (mcc_count) + { + palette_count = mcc_count; + palette = mcc_palette; + } + if (palette_count < 0 || palette_count > 64 || (palette_count && !palette)) + return NULL; + allocation = vertices->count * sizeof(*part->boundary) + triangles->count * 3 * sizeof(*part->indices); + if (allocation > FIRST_PERSON_LEGS_BYTES - first_person_legs_bytes) + return NULL; + kept = malloc(vertices->count * 3 * sizeof(*kept)); + used = kept ? kept + vertices->count : NULL; + edge = kept ? used + vertices->count : NULL; + part->boundary = malloc(vertices->count * sizeof(*part->boundary)); + part->indices = malloc(triangles->count * 3 * sizeof(*part->indices)); + if (!kept || !part->indices || !part->boundary) + { + if (kept) free(kept); + if (part->indices) free(part->indices); + if (part->boundary) free(part->boundary); + part->boundary = NULL; + part->indices = NULL; + return NULL; + } + first_person_legs_bytes += allocation; + IDirect3DVertexBuffer8_Lock(vertices->hardware_format, 0, + vertices->count * sizeof(*data), (BYTE **)&data, D3DLOCK_READONLY); + IDirect3DIndexBuffer8_Lock(triangles->hardware_format, 0, + (triangles->type == _triangle_buffer_type_triangles ? triangles->count * 3 : triangles->count + 2) * sizeof(word), + (BYTE **)&source, D3DLOCK_READONLY); + count = NONE; + if (data && source) + { + for (vertex = 0; vertex < vertices->count; vertex++) + kept[vertex] = first_person_legs_vertex_kept(&data[vertex], node_count, upper, palette_count, palette); + count = first_person_legs_select(source, triangles->count, triangles->type, kept, vertices->count, part->indices); + if (count >= 0) + { + long triangle; + csmemset(used, 0, vertices->count * 2 * sizeof(*used)); + for (triangle = 0; triangle < triangles->count; triangle++) + { + long start = triangles->type == _triangle_buffer_type_triangles ? triangle * 3 : triangle; + word a = source[start], b = source[start + 1], c = source[start + 2]; + boolean *mark; + if (a == b || a == c || b == c) continue; + mark = kept[a] && kept[b] && kept[c] ? used : edge; + mark[a] = mark[b] = mark[c] = TRUE; + } + for (vertex = 0; vertex < vertices->count; vertex++) + { + struct first_person_legs_boundary *boundary = &part->boundary[part->boundary_count]; + short j; + boolean leg_only = TRUE; + if (!used[vertex]) continue; + boundary->weight = data[vertex].node_weight / 32767.f; + for (j = 0; j < 2; j++) + { + short node = data[vertex].nodes[j] / 3; + real weight = j ? 1.f - boundary->weight : boundary->weight; + if (weight == 0.f) node = 0; + else if (palette_count) node = palette[node]; + boundary->nodes[j] = node; + if (weight > 0.f && !lower[node]) leg_only = FALSE; + matrix4x3_transform_point(&TAG_BLOCK_GET_ELEMENT(&model->nodes, node, + struct model_node)->runtime_default_inverse_matrix, &data[vertex].position, &boundary->local[j]); + } + if (edge[vertex] || !leg_only) part->boundary_count++; + } + part->valid = TRUE; + } + + } + IDirect3DVertexBuffer8_Unlock(vertices->hardware_format); + IDirect3DIndexBuffer8_Unlock(triangles->hardware_format); + free(kept); + if (count <= 0 || !rasterizer_triangle_buffer_new(&part->triangles, + _triangle_buffer_type_triangles, count, part->indices)) + { + free(part->indices); + part->indices = NULL; + free(part->boundary); + part->boundary = NULL; + part->boundary_count = 0; + first_person_legs_bytes -= allocation; + if (count > 0) part->valid = FALSE; + return NULL; + } + return &part->triangles; +} + +void first_person_legs_geometry_reset(void) +{ + short index; + + for (index = 0; index < first_person_legs_part_count; index++) + { + rasterizer_triangle_buffer_delete(&first_person_legs_parts[index].triangles); + if (first_person_legs_parts[index].boundary) + free(first_person_legs_parts[index].boundary); + if (first_person_legs_parts[index].indices) + free(first_person_legs_parts[index].indices); + } + csmemset(first_person_legs_parts, 0, sizeof(first_person_legs_parts)); + first_person_legs_part_count = 0; + first_person_legs_bytes = 0; +} + +boolean first_person_legs_geometry_prepare(long definition_index, struct model const *model, + boolean const *upper, boolean const *lower) +{ + long geometry, part; + short index; + if (model->geometries.count < 0 || model->geometries.count > MAXIMUM_GEOMETRIES_PER_MODEL) + return FALSE; + for (geometry = 0; geometry < model->geometries.count; geometry++) + { + struct first_person_legs_geometry const *g = TAG_BLOCK_GET_ELEMENT(&model->geometries, + geometry, struct first_person_legs_geometry); + if (g->parts.count < 0 || g->parts.count > MAXIMUM_PARTS_PER_MODEL_GEOMETRY) + return FALSE; + for (part = 0; part < g->parts.count; part++) + { + struct first_person_legs_source_part const *p = TAG_BLOCK_GET_ELEMENT(&g->parts, + part, struct first_person_legs_source_part); + if (p->flags & 1) continue; /* stripped parts are not rendered */ + if (p->triangle_buffer.count == 0) continue; + first_person_legs_geometry_get(definition_index, model, upper, lower, &p->vertex_buffer, &p->triangle_buffer); + } + } + for (index = 0; index < first_person_legs_part_count; index++) + if (first_person_legs_parts[index].definition_index == definition_index && !first_person_legs_parts[index].valid) + return FALSE; + return first_person_legs_part_count < FIRST_PERSON_LEGS_PARTS; +} + +real first_person_legs_geometry_setback(long definition_index, real_matrix4x3 const *nodes, + real_point3d const *pivot, real cosine, real sine, real_vector3d const *view, + real_point3d const *eye, real vertical_fov, real minimum) +{ + real tangent, margin; + short part; + real result = minimum; + if (!(vertical_fov > 0.f && vertical_fov < _pi)) return REAL_MAX; + /* At vertical pitch a surface point is outside the view when its + rearward distance exceeds abs(height) * tan(half FOV). That also + excludes it at intermediate pitches. The margin is a plane distance; + the absolute height covers openings both above and below the eye. + Use the drawn skin, including inverse bind and both bone weights, + rather than bone origins, which do not bound the surface. */ + tangent = (real)tan(vertical_fov * 0.5); + margin = 0.03f / (real)cos(vertical_fov * 0.5); + for (part = 0; part < first_person_legs_part_count; part++) + { + struct first_person_legs_part const *entry = &first_person_legs_parts[part]; + long vertex; + if (entry->definition_index != definition_index) continue; + for (vertex = 0; vertex < entry->boundary_count; vertex++) + { + struct first_person_legs_boundary const *boundary = &entry->boundary[vertex]; + real_point3d a, b, point; + real x, y, world_x, world_y, current, required; + matrix4x3_transform_point(&nodes[boundary->nodes[0]], &boundary->local[0], &a); + matrix4x3_transform_point(&nodes[boundary->nodes[1]], &boundary->local[1], &b); + point.x = a.x * boundary->weight + b.x * (1.f - boundary->weight); + point.y = a.y * boundary->weight + b.y * (1.f - boundary->weight); + point.z = a.z * boundary->weight + b.z * (1.f - boundary->weight); + x = point.x - pivot->x; y = point.y - pivot->y; + world_x = pivot->x + cosine * x - sine * y; + world_y = pivot->y + sine * x + cosine * y; + current = (eye->x - world_x) * view->i + (eye->y - world_y) * view->j; + required = (real)fabs(eye->z - point.z) * tangent + margin; + if (!(required - current > -REAL_MAX && required - current < REAL_MAX)) + return REAL_MAX; + result = MAX(result, required - current); + } + } + return result; +} diff --git a/port/linux/game/first_person_legs_geometry.h b/port/linux/game/first_person_legs_geometry.h new file mode 100644 index 0000000000..ca2ac3ad8f --- /dev/null +++ b/port/linux/game/first_person_legs_geometry.h @@ -0,0 +1,24 @@ +/* +FIRST_PERSON_LEGS_GEOMETRY.H + +Private lower-body index buffers; original vertices and palettes stay owned +by their map. +*/ +#ifndef FIRST_PERSON_LEGS_GEOMETRY_H +#define FIRST_PERSON_LEGS_GEOMETRY_H + +struct model; +struct triangle_buffer; +struct vertex_buffer; + +struct triangle_buffer const *first_person_legs_geometry_get( + long definition_index, struct model const *model, boolean const *upper, boolean const *lower, + struct vertex_buffer const *vertices, struct triangle_buffer const *triangles); +void first_person_legs_geometry_reset(void); + +boolean first_person_legs_geometry_prepare(long definition_index, struct model const *model, + boolean const *upper, boolean const *lower); +real first_person_legs_geometry_setback(long definition_index, real_matrix4x3 const *nodes, + real_point3d const *pivot, real cosine, real sine, real_vector3d const *view, + real_point3d const *eye, real vertical_fov, real minimum); +#endif diff --git a/port/linux/game/frontend_glyphs.c b/port/linux/game/frontend_glyphs.c new file mode 100644 index 0000000000..9d008ed1dc --- /dev/null +++ b/port/linux/game/frontend_glyphs.c @@ -0,0 +1,52 @@ +/* Modern and stock PC menus share the existing artwork owner with gameplay; + * the prompt dispatcher gates their use on High-Res HUD. */ +#include "cseries.h" +#include "frontend_menu.h" +#include "frontend_prompts.h" +#include "controller_buttons.h" +#include "controller_glyphs.h" +#include "bitmaps/bitmaps.h" +#include "bitmaps/bitmap_group.h" +#include "interface/hud_definitions.h" +#include "rasterizer/rasterizer.h" +#include "rasterizer/xbox/rasterizer_xbox_hardware_bitmaps.h" +#include "text/draw_string.h" +#include "hud_button_layout.h" +#include + +struct bitmap_data *hud_hires_button_bitmap(short style, short slot); + +boolean frontend_glyph_draw(short port, short button, rectangle2d *cursor, pixel32 color) +{ + struct rasterizer_dynamic_screen_geometry_parameters parameters; + struct dynamic_screen_vertex vertices[4]; + struct bitmap_data *bitmap; + short style, i; + real x, y, width = 16.0f, height = 20.0f; + if (button < 0 || (button > 3 && button != 16) || port < 0 || port > 3) return FALSE; + style = (short)controller_button_style_for_port(port); + if (button == 16) return controller_glyph_draw_menu(style < 3 ? 3 : style, button, cursor, color); + if (style >= 3) return controller_glyph_draw_menu(style, button, cursor, color); + if (style < 0) return FALSE; + bitmap = hud_hires_button_bitmap(style, button); + if (!bitmap) return FALSE; + x = cursor->x0 + 4.0f; + y = draw_unicode_string_capital_middle(cursor, L"") - height * 0.5f; + hud_button_face_bounds(style, button, &x, &y, &width, &height); + memset(¶meters, 0, sizeof(parameters)); + parameters.map[0] = bitmap; + parameters.map_texture_scale[0].i = parameters.map_texture_scale[0].j = 1.0f; + parameters.map_scale[0].i = parameters.map_scale[0].j = 1.0f; + for (i = 0; i < 4; i++) + { + boolean right = ((i + 1) & 2) != 0, bottom = i > 1; + vertices[i].position.x = x + (right ? width : 0.0f); + vertices[i].position.y = y + (bottom ? height : 0.0f); + vertices[i].texture_coordinates.x = right ? 21.0f / 32.0f : 0.0f; + vertices[i].texture_coordinates.y = bottom ? 26.0f / 32.0f : 0.0f; + vertices[i].color = (color & 0xff000000UL) | 0xffffffUL; + } + rasterizer_psuedo_dynamic_screen_quad_draw(¶meters, vertices); + cursor->x0 += 26; + return TRUE; +} diff --git a/port/linux/game/frontend_layout.c b/port/linux/game/frontend_layout.c new file mode 100644 index 0000000000..b47799ef1f --- /dev/null +++ b/port/linux/game/frontend_layout.c @@ -0,0 +1,229 @@ +/* Modern frontend geometry uses the engine's centered 640-column coordinates. + * Definitions remain immutable; the renderer and hit testing share a local copy. */ +#include "cseries.h" +#include "frontend_menu.h" +#include "tag_files/tag_files.h" +#include +#include + +long halo_screen_width(void); +static int frontend_text_active; +#include "frontend_network_layout.inl" + +static int frontend_network_role(char const *name) +{ + unsigned int i; + for (i = 0; i < sizeof(frontend_network_widgets) / sizeof(frontend_network_widgets[0]); i++) + if (!strcmp(name, frontend_network_widgets[i].name)) return frontend_network_widgets[i].role; + return -1; +} + +static int frontend_network_geometry(char const *name, int screen, short *left, short *right, short *shift) +{ + int extra = frontend_layout_width(screen) - 640, rows = extra * 3 / 5; + int origin = -extra / 2; + *shift = 0; + switch (frontend_network_role(name)) + { + case FRONTEND_NET_FULL: *left = (short)(-(screen - 640) / 2); *right = (short)(*left + screen); break; + case FRONTEND_NET_ROW: case FRONTEND_NET_HEADING: + *shift = (short)origin; *right += (short)rows; break; + case FRONTEND_NET_DETAIL: case FRONTEND_NET_DETAIL_WRAP: + *shift = (short)(origin + rows); *right += (short)(extra - rows); break; + case FRONTEND_NET_DETAIL_FIXED: case FRONTEND_NET_DETAIL_ICON: + *shift = (short)(origin + rows + (extra - rows) / 2); break; + case FRONTEND_NET_LABEL: *right += (short)(rows * 2 / 3); break; + case FRONTEND_NET_LABEL_FULL: case FRONTEND_NET_CHOOSER: *right += (short)rows; break; + case FRONTEND_NET_VALUE: *shift = (short)(rows * 2 / 3); *right += (short)(rows - rows * 2 / 3); break; + case FRONTEND_NET_BAR: case FRONTEND_NET_STATUS: *shift = (short)origin; *right += (short)extra; break; + case FRONTEND_NET_BUTTON: *shift = (short)extra; break; + } + return 1; +} + +void frontend_menu_text_begin(long tag) +{ + char const *name; + frontend_text_active = 0; + if (!frontend_menu_available()) return; + name = tag_get_name(tag); + frontend_text_active = name && !strncmp(name, "pc\\modern\\", 10); +} + +void frontend_menu_text_end(void) +{ + frontend_text_active = 0; +} + +void frontend_menu_clip_text(short left, short right, short *clipped_left, short *clipped_right) +{ + int width, origin; + if (!frontend_text_active) return; + width = (int)halo_screen_width(); + origin = -(width - 640) / 2; + *clipped_left = (short)(left < origin ? origin : left); + *clipped_right = (short)(right > origin + width ? origin + width : right); +} + +int frontend_layout_width(int screen) +{ + return screen < 640 ? 640 : screen > 1280 ? 1280 : screen; +} + +int frontend_layout_geometry(char const *name, int screen, short *left, short *right, short *shift) +{ + int width, extra, rows, origin, navigation; + + if (strncmp(name, "pc\\modern\\", 10) || !strncmp(name + 10, "entry", 5)) + return 0; + if (!strncmp(name, "pc\\modern\\network\\", 18)) return frontend_network_geometry(name, screen, left, right, shift); + navigation = !strncmp(name + 10, "multiplayer\\", 12) || !strncmp(name + 10, "host\\", 5); + name = strrchr(name, '\\') + 1; + width = frontend_layout_width(screen); + extra = width - 640; + rows = navigation ? extra * 9 / 20 : extra * 3 / 5; + origin = -extra / 2; + *shift = 0; + if (!strcmp(name, "settings") || !strcmp(name, "screen") || !strcmp(name, "options")) + { + *left = (short)(-(screen - 640) / 2); + *right = (short)(*left + screen); + } + else if (!strncmp(name, "row_", 4)) + { + *shift = (short)origin; + *right += (short)rows; + } + else if (!strncmp(name, "spinner_", 8)) + { + *shift = (short)(rows - rows / 3); + *right += (short)(rows / 3); + } + else if (!strncmp(name, "label_", 6)) + *right += (short)(navigation ? rows : rows - rows / 3); + else if (!strcmp(name, "master_servers_value")) + { + *shift = (short)(rows - rows / 3); + *right += (short)(rows / 3); + } + else if (!strcmp(name, "help") || !strncmp(name, "help_", 5)) + { + *shift = (short)(origin + rows); + *right += (short)(extra - rows); + } + else if (!strcmp(name, "button_bar")) + { + *shift = (short)origin; + *right += (short)extra; + } + else if (!strcmp(name, "button_defaults")) + *shift = 0; + else if (!strncmp(name, "button_", 7)) + *shift = (short)extra; + else if (!strcmp(name, "tabs")) + *shift = (short)origin; + else if (!strncmp(name, "tab_", 4)) + *shift = (short)(atoi(name + 4) * extra / 5); + else if (!strcmp(name, "title")) + *shift = (short)origin; + else if (!strncmp(name, "section", 7) || !strncmp(name, "rule_", 5) || + !strcmp(name, "status") || !strcmp(name, "prompts")) + { + *shift = (short)origin; + *right += (short)(!strcmp(name, "prompts") ? extra : rows); + } + return 1; +} + +int frontend_menu_geometry(long tag, short *left, short *right, short *shift) +{ + char const *name; + if (!frontend_menu_available()) + return 0; + name = tag_get_name(tag); + return name && frontend_layout_geometry(name, (int)halo_screen_width(), left, right, shift); +} + +int frontend_menu_wrap(long tag) +{ + char const *name; + if (!frontend_menu_available()) + return 0; + name = tag_get_name(tag); + return name && !strncmp(name, "pc\\modern\\", 10) && + (!strcmp(strrchr(name, '\\') + 1, "help") || !strcmp(strrchr(name, '\\') + 1, "help_value") || frontend_network_role(name) == FRONTEND_NET_DETAIL_WRAP); +} + +/* Native descriptions contain manual |n breaks (including split words such + * as wea-|npon). Reflow only the modern instance copy for its current width. + * Authored alignment belongs to the modern widget, not those legacy strings. */ +void frontend_menu_reflow_text(wchar_t *text) +{ + wchar_t *read = text, *write = text; + while (*read) + { + if (*read == L'|' && (read[1] == L'c' || read[1] == L'l' || read[1] == L'r')) + { + read += 2; + continue; + } + if (*read == L'\r' || *read == L'\n' || (*read == L'|' && read[1] == L'n')) + { + do + { + read += *read == L'|' ? 2 : 1; + } while (*read == L'\r' || *read == L'\n' || (*read == L'|' && read[1] == L'n')); + if (write > text && write[-1] == L'-') write--; + else if (write > text && write[-1] != L' ' && *read && *read != L' ') *write++ = L' '; + continue; + } + *write++ = *read++; + } + *write = 0; +} + +/* Stock previews occupy a subrectangle of a padded bitmap. Keep the native + * texel placement for them; only our independently generated art stretches. */ +int frontend_menu_stretch_bitmap(long tag) +{ + char const *name; + if (!frontend_menu_available()) return 0; + name = tag_get_name(tag); + return name && !strncmp(name, "pc\\modern\\", 10) && + frontend_network_role(name) != FRONTEND_NET_DETAIL_FIXED; +} + +int frontend_menu_bitmap_region(long tag, short *width, short *height) +{ + char const *name; + if (!frontend_menu_available()) return 0; + name = tag_get_name(tag); + if (!name || frontend_network_role(name) != FRONTEND_NET_DETAIL_ICON) return 0; + name = strrchr(name, '\\') + 1; + *width = (short)(!strcmp(name, "difficulty_indicator") ? 44 : 200); + *height = (short)(!strcmp(name, "difficulty_indicator") ? 48 : 211); + return 1; +} + +/* One option-text size for the whole screen, never a size chosen per row. + * The narrow layout uses the small UI face; wide screens use the large face + * with both columns expanded. Headings and footer buttons retain their roles. */ +long frontend_menu_font(long tag, long normal) +{ + char const *name; + long font; + if (!frontend_menu_available()) return normal; + name = tag_get_name(tag); + if (!name || strncmp(name, "pc\\modern\\", 10)) return normal; + if (!strncmp(name, "pc\\modern\\network\\", 18)) + { + int role = frontend_network_role(name); + if (role != FRONTEND_NET_LABEL && role != FRONTEND_NET_LABEL_FULL && role != FRONTEND_NET_VALUE && role != FRONTEND_NET_CHOOSER) return normal; + font = tag_loaded('font', halo_screen_width() < 832 ? "ui\\small_ui" : "ui\\large_ui"); + return font == NONE ? normal : font; + } + name = strrchr(name, '\\') + 1; + if (strncmp(name, "label_", 6) && strncmp(name, "spinner_", 8) && strcmp(name, "master_servers_value")) return normal; + font = tag_loaded('font', halo_screen_width() < 832 ? "ui\\small_ui" : "ui\\large_ui"); + return font == NONE ? normal : font; +} diff --git a/port/linux/game/frontend_legacy_footers.inl b/port/linux/game/frontend_legacy_footers.inl new file mode 100644 index 0000000000..950a1bcfce --- /dev/null +++ b/port/linux/game/frontend_legacy_footers.inl @@ -0,0 +1,58 @@ +/* Generated by tools/frontend_menu.py. Xbox-only footer replacements. */ +static struct { char const *native, *replacement, *glyph; } const frontend_legacy_footers[] = { + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\audio_settings\\sound_processing\\button_defaults", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\audio_settings\\sound_processing\\button_defaults", "pc\\frontend_legacy\\footer_glyph_x"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\audio_settings\\sound_processing\\button_ok", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\audio_settings\\sound_processing\\button_ok", "pc\\frontend_legacy\\footer_glyph_a"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\audio_settings\\button_defaults", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\audio_settings\\button_defaults", "pc\\frontend_legacy\\footer_glyph_x"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\audio_settings\\button_ok", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\audio_settings\\button_ok", "pc\\frontend_legacy\\footer_glyph_a"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\controller_appearance\\button_defaults", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\controller_appearance\\button_defaults", "pc\\frontend_legacy\\footer_glyph_x"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\controller_appearance\\button_ok", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\controller_appearance\\button_ok", "pc\\frontend_legacy\\footer_glyph_a"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\controller_remapping\\button_defaults", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\controller_remapping\\button_defaults", "pc\\frontend_legacy\\footer_glyph_x"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\controller_remapping\\button_ok", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\controller_remapping\\button_ok", "pc\\frontend_legacy\\footer_glyph_a"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\controls_setup\\button_defaults", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\controls_setup\\button_defaults", "pc\\frontend_legacy\\footer_glyph_x"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\controls_setup\\button_ok", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\controls_setup\\button_ok", "pc\\frontend_legacy\\footer_glyph_a"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\gamepad_setup\\android\\button_defaults", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\gamepad_setup\\android\\button_defaults", "pc\\frontend_legacy\\footer_glyph_x"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\gamepad_setup\\android\\button_ok", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\gamepad_setup\\android\\button_ok", "pc\\frontend_legacy\\footer_glyph_a"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\gamepad_setup\\dead_zones\\button_defaults", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\gamepad_setup\\dead_zones\\button_defaults", "pc\\frontend_legacy\\footer_glyph_x"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\gamepad_setup\\dead_zones\\button_ok", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\gamepad_setup\\dead_zones\\button_ok", "pc\\frontend_legacy\\footer_glyph_a"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\gamepad_setup\\gyro\\button_defaults", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\gamepad_setup\\gyro\\button_defaults", "pc\\frontend_legacy\\footer_glyph_x"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\gamepad_setup\\gyro\\button_ok", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\gamepad_setup\\gyro\\button_ok", "pc\\frontend_legacy\\footer_glyph_a"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\gamepad_setup\\button_defaults", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\gamepad_setup\\button_defaults", "pc\\frontend_legacy\\footer_glyph_x"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\gamepad_setup\\button_ok", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\gamepad_setup\\button_ok", "pc\\frontend_legacy\\footer_glyph_a"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\mouse_settings\\button_defaults", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\mouse_settings\\button_defaults", "pc\\frontend_legacy\\footer_glyph_x"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\mouse_settings\\button_ok", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\mouse_settings\\button_ok", "pc\\frontend_legacy\\footer_glyph_a"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\bots\\manage\\button_ok", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\bots\\manage\\button_ok", "pc\\frontend_legacy\\footer_glyph_a"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\bots\\button_defaults", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\bots\\button_defaults", "pc\\frontend_legacy\\footer_glyph_x"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\bots\\button_ok", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\bots\\button_ok", "pc\\frontend_legacy\\footer_glyph_a"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\discord_account\\button_defaults", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\discord_account\\button_defaults", "pc\\frontend_legacy\\footer_glyph_x"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\discord_account\\button_ok", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\discord_account\\button_ok", "pc\\frontend_legacy\\footer_glyph_a"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\in_game\\button_defaults", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\in_game\\button_defaults", "pc\\frontend_legacy\\footer_glyph_x"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\in_game\\button_ok", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\in_game\\button_ok", "pc\\frontend_legacy\\footer_glyph_a"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\map_sharing\\button_defaults", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\map_sharing\\button_defaults", "pc\\frontend_legacy\\footer_glyph_x"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\map_sharing\\button_ok", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\map_sharing\\button_ok", "pc\\frontend_legacy\\footer_glyph_a"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\mcc_packages\\button_defaults", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\mcc_packages\\button_defaults", "pc\\frontend_legacy\\footer_glyph_x"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\mcc_packages\\button_ok", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\mcc_packages\\button_ok", "pc\\frontend_legacy\\footer_glyph_a"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\multiplayer_hud\\button_defaults", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\multiplayer_hud\\button_defaults", "pc\\frontend_legacy\\footer_glyph_x"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\multiplayer_hud\\button_ok", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\multiplayer_hud\\button_ok", "pc\\frontend_legacy\\footer_glyph_a"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\server_browser\\button_defaults", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\server_browser\\button_defaults", "pc\\frontend_legacy\\footer_glyph_x"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\server_browser\\button_ok", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\server_browser\\button_ok", "pc\\frontend_legacy\\footer_glyph_a"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\streamer_mode\\button_defaults", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\streamer_mode\\button_defaults", "pc\\frontend_legacy\\footer_glyph_x"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\streamer_mode\\button_ok", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\streamer_mode\\button_ok", "pc\\frontend_legacy\\footer_glyph_a"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\button_defaults", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\button_defaults", "pc\\frontend_legacy\\footer_glyph_x"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\button_ok", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\button_ok", "pc\\frontend_legacy\\footer_glyph_a"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\video_settings\\dynamic_lighting\\button_defaults", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\video_settings\\dynamic_lighting\\button_defaults", "pc\\frontend_legacy\\footer_glyph_x"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\video_settings\\dynamic_lighting\\button_ok", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\video_settings\\dynamic_lighting\\button_ok", "pc\\frontend_legacy\\footer_glyph_a"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\video_settings\\extra_effects\\button_defaults", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\video_settings\\extra_effects\\button_defaults", "pc\\frontend_legacy\\footer_glyph_x"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\video_settings\\extra_effects\\button_ok", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\video_settings\\extra_effects\\button_ok", "pc\\frontend_legacy\\footer_glyph_a"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\video_settings\\fov_viewmodels\\button_defaults", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\video_settings\\fov_viewmodels\\button_defaults", "pc\\frontend_legacy\\footer_glyph_x"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\video_settings\\fov_viewmodels\\button_ok", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\video_settings\\fov_viewmodels\\button_ok", "pc\\frontend_legacy\\footer_glyph_a"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\video_settings\\graphics\\button_defaults", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\video_settings\\graphics\\button_defaults", "pc\\frontend_legacy\\footer_glyph_x"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\video_settings\\graphics\\button_ok", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\video_settings\\graphics\\button_ok", "pc\\frontend_legacy\\footer_glyph_a"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\video_settings\\hdr_calibration\\button_defaults", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\video_settings\\hdr_calibration\\button_defaults", "pc\\frontend_legacy\\footer_glyph_x"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\video_settings\\hdr_calibration\\button_ok", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\video_settings\\hdr_calibration\\button_ok", "pc\\frontend_legacy\\footer_glyph_a"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\video_settings\\shoulder_camera\\button_defaults", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\video_settings\\shoulder_camera\\button_defaults", "pc\\frontend_legacy\\footer_glyph_x"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\video_settings\\shoulder_camera\\button_ok", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\video_settings\\shoulder_camera\\button_ok", "pc\\frontend_legacy\\footer_glyph_a"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\video_settings\\button_defaults", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\video_settings\\button_defaults", "pc\\frontend_legacy\\footer_glyph_x"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\video_settings\\button_ok", "pc\\frontend_legacy\\footer\\main_menu\\settings_select\\player_setup\\player_profile_edit\\video_settings\\button_ok", "pc\\frontend_legacy\\footer_glyph_a"}, + {"pc\\common_button_back", "pc\\frontend_legacy\\footer\\common_button_back", "pc\\frontend_legacy\\footer_glyph_b"}, + {"pc\\common_button_cancel", "pc\\frontend_legacy\\footer\\common_button_cancel", "pc\\frontend_legacy\\footer_glyph_b"}, +}; diff --git a/port/linux/game/frontend_menu.c b/port/linux/game/frontend_menu.c new file mode 100644 index 0000000000..8e60b0d88d --- /dev/null +++ b/port/linux/game/frontend_menu.c @@ -0,0 +1,122 @@ +/* GulchCE's frontend selection is latched at the main-menu boundary. + * It never changes display.menus, which also governs legacy pause menus. */ +#include "cseries.h" +#include "frontend_menu.h" +#include "frontend_input.h" +#include "keyboard_glyphs.h" +#include "../src/port_config.h" +#include "tag_files/tag_groups.h" +#include + +boolean main_menu_is_active(void); +boolean network_game_is_active(void); + +static int frontend_menu_loaded; +static int frontend_menu_ui_map; +static int frontend_style_latched; +static char frontend_style[8]; + +char const *frontend_menu_style(void) +{ + return frontend_menu_ui_map || !frontend_style_latched ? + config_string("display.menu_frontend") : frontend_style; +} + +#include "frontend_network_routes.inl" + +int frontend_menu_requested(void) +{ + char const *value = frontend_menu_style(); + return !strcmp(value, "modern") || !strcmp(value, "pc") || !strcmp(value, "xbox"); +} + +void frontend_menu_map_loaded(char const *name, int mcc) +{ + frontend_menu_ui_map = !mcc && !strcmp(name, "ui"); + /* A gameplay load keeps the style selected at the main menu, including + * across rounds. Saved in-game changes are adopted only on return to ui. */ + if (frontend_menu_ui_map || !frontend_style_latched) + { + strncpy(frontend_style, config_string("display.menu_frontend"), sizeof(frontend_style) - 1); + frontend_style[sizeof(frontend_style) - 1] = 0; + frontend_style_latched = 1; + } + frontend_menu_loaded = !(mcc && !strcmp(name, "ui")) && frontend_menu_requested(); + frontend_input_enable(frontend_menu_loaded); +} + +void frontend_menu_unloaded(void) +{ + if (frontend_menu_ui_map) + { + strncpy(frontend_style, config_string("display.menu_frontend"), sizeof(frontend_style) - 1); + frontend_style[sizeof(frontend_style) - 1] = 0; + } + frontend_menu_session_reset(); + frontend_menu_loaded = 0; + frontend_menu_ui_map = 0; + frontend_input_enable(0); + frontend_menu_text_end(); + frontend_panel_end(); + keyboard_glyphs_dispose(); +} + +int frontend_menu_reload_required(void) +{ + /* Stock does not load the optional tags. Rebuild ui.map only when crossing + * that boundary, after the current settings widgets have been closed. */ + return frontend_menu_ui_map && frontend_menu_loaded != frontend_menu_requested(); +} + +int frontend_menu_available(void) +{ + return frontend_menu_loaded && tag_loaded('DeLa', FRONTEND_MENU_SCREEN) != NONE; +} + +char const *frontend_menu_root(char const *legacy) +{ + char const *value, *root; + + /* Loading the optional set also makes PC tags available to an Xbox + * frontend. A missing modern screen must still respect its old policy. */ + if (frontend_menu_loaded && !strcmp(legacy, FRONTEND_MENU_PC) && + csstrcasecmp(config_string("display.menus"), "pc")) + legacy = FRONTEND_MENU_XBOX; + if (!frontend_menu_available()) + return legacy; + value = frontend_menu_style(); + root = !strcmp(value, "pc") ? FRONTEND_MENU_PC : !strcmp(value, "xbox") ? FRONTEND_MENU_XBOX : legacy; + return tag_loaded('DeLa', root) != NONE ? root : legacy; +} + +/* Explicit root routes only. A pregame host/client is active on ui.map; + * that is allowed here, but never in the separate style-switching policy. */ +long frontend_menu_destination(long tag) +{ + char const *name; + long modern; + unsigned int index; + if (tag == NONE || !frontend_menu_available()) return tag; + name = tag_get_name(tag); + if (!name) return tag; + if (!strcmp(name, "pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\player_profile_edit_screen") || + !strcmp(name, "ui\\shell\\main_menu\\settings_select\\player_setup\\player_profile_edit\\player_profile_edit_screen")) + { + if (!strcmp(frontend_menu_style(), "modern")) + modern = tag_loaded('DeLa', main_menu_is_active() ? FRONTEND_MENU_SCREEN : FRONTEND_MENU_PAUSED); + else if (!main_menu_is_active() && !strcmp(frontend_menu_style(), "xbox")) + modern = tag_loaded('DeLa', FRONTEND_MENU_XBOX_SETTINGS); + else return tag; + return modern == NONE ? tag : modern; + } + if (!frontend_menu_ui_map || !main_menu_is_active() || strcmp(frontend_menu_style(), "modern")) return tag; + for (index = 0; index < sizeof(frontend_network_routes) / sizeof(frontend_network_routes[0]); index++) + if (!strcmp(name, frontend_network_routes[index].legacy)) + { + modern = tag_loaded('DeLa', frontend_network_routes[index].modern); + return modern == NONE ? tag : modern; + } + if (network_game_is_active() || strcmp(name, "pc\\main_menu\\multiplayer_type_select\\multiplayer_type_select_screen")) return tag; + modern = tag_loaded('DeLa', "pc\\modern\\multiplayer\\screen"); + return modern == NONE ? tag : modern; +} diff --git a/port/linux/game/frontend_menu.h b/port/linux/game/frontend_menu.h new file mode 100644 index 0000000000..d9d8ea2fd6 --- /dev/null +++ b/port/linux/game/frontend_menu.h @@ -0,0 +1,49 @@ +/* Optional settings presentation. Pause roots remain owned by each map family. */ +#ifndef FRONTEND_MENU_H +#define FRONTEND_MENU_H +#include + +struct widget_instance; +struct event_record; +struct halo_menus; +struct rasterizer_dynamic_screen_geometry_parameters; +struct dynamic_screen_vertex; + +int frontend_menu_requested(void); +char const *frontend_menu_style(void); +int frontend_menu_reload_required(void); +void frontend_menu_reflow_text(wchar_t *text); +int frontend_menu_bitmap_region(long tag, short *width, short *height); +void frontend_menu_map_loaded(char const *name, int mcc); +void frontend_menu_unloaded(void); +void frontend_menu_session_reset(void); +int frontend_menu_row_drawable(struct widget_instance *widget); +int frontend_menu_available(void); +char const *frontend_menu_root(char const *legacy); +long frontend_menu_destination(long tag); +void frontend_menu_attach(struct widget_instance *widget); +short frontend_menu_legacy_description_index(struct widget_instance *list, short index); +int frontend_menu_legacy_controls_help(struct widget_instance *list); +int frontend_menu_shortcut(struct widget_instance *widget, struct event_record *event); +int frontend_layout_width(int screen); +int frontend_layout_geometry(char const *name, int screen, short *left, short *right, short *shift); +int frontend_menu_geometry(long tag, short *left, short *right, short *shift); +int frontend_menu_wrap(long tag); +int frontend_menu_stretch_bitmap(long tag); +long frontend_menu_font(long tag, long normal); +void frontend_menu_text_begin(long tag); +void frontend_menu_text_end(void); +void frontend_menu_clip_text(short left, short right, short *clipped_left, short *clipped_right); +void frontend_panel_begin(long tag); +void frontend_panel_end(void); +int frontend_panel_draw(struct rasterizer_dynamic_screen_geometry_parameters *parameters, + struct dynamic_screen_vertex *vertices, long source_width); +struct halo_menus const *frontend_menu_files_load(void); + +#define FRONTEND_MENU_SCREEN "pc\\modern\\settings" +#define FRONTEND_MENU_PAUSED "pc\\modern\\paused\\settings" +#define FRONTEND_MENU_XBOX_SETTINGS "pc\\frontend_legacy\\paused\\settings" +#define FRONTEND_MENU_PC "pc\\main_menu\\main_menu" +#define FRONTEND_MENU_XBOX "ui\\shell\\main_menu\\main_menu" + +#endif diff --git a/port/linux/game/frontend_menu_runtime.inl b/port/linux/game/frontend_menu_runtime.inl new file mode 100644 index 0000000000..6f908ad0a7 --- /dev/null +++ b/port/linux/game/frontend_menu_runtime.inl @@ -0,0 +1,694 @@ +/* Instance access stays beside the menu adapter's existing widget helpers. + * These callbacks never load/release tag tables or touch a map's pause UI. */ +#include "frontend_menu.h" +#include "controller_buttons.h" +#include "tag_files/tag_files.h" +#include "frontend_pages.inl" +#include "frontend_multiplayer.inl" +#include "frontend_legacy_footers.inl" + +boolean network_game_is_active(void); +boolean ui_widget_port_open(struct widget_instance *, char const *, boolean *); + +#include "mcc_xbox_menu.inl" + +static boolean frontend_menu_can_edit(void) +{ + return frontend_menu_available(); +} + +static boolean frontend_menu_legacy_root(struct widget_instance *widget) +{ + char const *name; + + if (!widget || widget->parent || !frontend_menu_can_edit() || !main_menu_is_active() || network_game_is_active()) + return FALSE; + name = tag_get_name(widget->definition_tag_index); + return name && (!strcmp(name, FRONTEND_MENU_PC) || !strcmp(name, FRONTEND_MENU_XBOX)); +} + +void frontend_menu_attach(struct widget_instance *widget) +{ + static char const *settings[] = {"audio", "video", "network"}; + static char const *controls[] = {"keyboard", "controller", "glyphs"}; + char const *name, **links; + char path[96]; + struct widget_instance *entry, *last, *save, *before, *description; + int index; + mcc_xbox_attach(widget); + if (!widget || !frontend_menu_can_edit() || strcmp(frontend_menu_style(), "xbox")) return; + name = tag_get_name(widget->definition_tag_index); + if (!name) return; + /* Gameplay caches may omit ui.map's button-key art. Use the same Xbox + * redraws as the existing HUD, never the user's modern glyph preference. */ + for (index = 0; index < 3; index++) + { + static char const glyphs[] = "abx"; + snprintf(path, sizeof(path), "pc\\frontend_legacy\\footer_glyph_%c", glyphs[index]); + if (!strcmp(name, path)) + { + long fallback; + snprintf(path, sizeof(path), "ui\\shell\\bitmaps\\%c_butn", glyphs[index]); + if (tag_loaded('bitm', path) != NONE) return; + snprintf(path, sizeof(path), "pc\\frontend_legacy\\footer_glyph_%c_fallback", glyphs[index]); + fallback = tag_loaded('DeLa', path); + if (fallback != NONE) widget->definition_tag_index = fallback; + return; + } + } + /* Only this live Xbox instance borrows the matching footer definition. + * Its native callbacks/name stay intact; no stock tag is modified. */ + for (index = 0; index < NUMBEROF(frontend_legacy_footers); index++) + if (!strcmp(name, frontend_legacy_footers[index].native)) + { + long replacement = tag_loaded('DeLa', frontend_legacy_footers[index].replacement); + char const *root_name = tag_get_name(screen_of(widget)->definition_tag_index); + static char const profile[] = "pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\"; + if (!root_name || strncmp(root_name, profile, sizeof(profile) - 1)) return; + if (replacement == NONE) return; + widget->definition_tag_index = replacement; + widget->parameters.text_box.string_list_index = 0; + entry = ui_widget_load_by_name_or_tag(frontend_legacy_footers[index].glyph, NONE, + widget, widget->local_player_index, NONE, NONE, NONE); + if (entry) widget->child = entry; + return; + } + if (!strcmp(name, "ui\\shell\\main_menu\\settings_select\\player_setup\\player_profile_edit\\player_profile_edit_screen")) + { + entry = named(widget, "blueline", 0); + if (entry) entry->vertical_offset += 99; + return; + } + if (!strcmp(name, "ui\\shell\\main_menu\\settings_select\\player_setup\\player_profile_edit\\profile_edit_select_list")) + links = settings; + else if (!strcmp(name, "ui\\shell\\main_menu\\settings_select\\player_setup\\player_profile_edit\\advanced_controls\\advanced_controls_menu")) + links = controls; + else return; + save = links == settings ? named(widget, "save_changes_profile_item", 0) : NULL; + before = links == settings ? named(widget, "color_profile_item", 0) : NULL; + for (index = 0; index < 3; index++) + { + snprintf(path, sizeof(path), "pc\\frontend_legacy\\%s", links[index]); + entry = ui_widget_load_by_name_or_tag(path, NONE, widget, widget->local_player_index, NONE, NONE, NONE); + if (!entry) continue; + last = before ? before->previous : widget->child; + if (!before) while (last && last->next) last = last->next; + entry->previous = last; + entry->next = before; + if (last) last->next = entry; + else widget->child = entry; + if (before) before->previous = entry; + } + if (before) before->vertical_offset += 99; + if (save) save->vertical_offset += 99; + description = links == settings ? widget->parameters.list.extended_description : NULL; + if (description) + { + entry = ui_widget_load_by_name_or_tag("pc\\frontend_legacy\\description", NONE, description, + widget->local_player_index, NONE, NONE, NONE); + if (entry) + { + last = description->child; + while (last && last->next) last = last->next; + entry->previous = last; + if (last) last->next = entry; + else description->child = entry; + entry->visible = FALSE; + } + } +} + +/* Native settings use X for defaults and A to accept a value page. Binding + * editors retain A-to-bind/X-to-clear while a binding row owns focus. */ +static boolean frontend_menu_legacy_footer_action(struct widget_instance *root, struct event_record *event) +{ + struct widget_instance *focused = root, *button = NULL, *spinner; + char const *name = tag_get_name(root->definition_tag_index), *path; + boolean deleted = FALSE; + if (event->type != 3 || event->data.button.value != 1) return FALSE; + while (focused->focused_child) focused = focused->focused_child; + if (event->data.button.index == 2 && name && + !strstr(name, "\\controls_setup\\") && !strstr(name, "\\controller_remapping\\")) + button = named(root, "button_defaults", 0); + else if (event->data.button.index == 0) + for (spinner = focused; spinner && spinner != root; spinner = spinner->parent) + if (spinner->type == 2 && pc_menu_setting_get(spinner->definition_tag_index)) + { + button = named(root, "button_ok", 0); + break; + } + path = button ? tag_get_name(button->definition_tag_index) : NULL; + if (!path || strncmp(path, "pc\\frontend_legacy\\footer\\", 26)) return FALSE; + return ui_widget_port_dispatch_event(button, 0, event->controller_index, &deleted); +} + +int frontend_menu_shortcut(struct widget_instance *widget, struct event_record *event) +{ + struct widget_instance *focused; + char const *name, *target = NULL; + char path[256]; + boolean deleted = FALSE; + if (mcc_xbox_shortcut(widget, event)) return TRUE; + if (widget && !widget->parent && frontend_menu_can_edit() && + !strcmp(frontend_menu_style(), "xbox") && + frontend_menu_legacy_footer_action(widget, event)) return TRUE; + /* The native Advanced Controls list accepts A itself, before dispatching + * to a child. Open our appended editor actions before that save/back event. */ + if (widget && !widget->parent && frontend_menu_can_edit() && + !strcmp(frontend_menu_style(), "xbox") && event->type == 3 && + (event->data.button.index == 0 || event->data.button.index == 12) && event->data.button.value == 1) + { + focused = widget; + while (focused->focused_child) focused = focused->focused_child; + name = tag_get_name(focused->definition_tag_index); + if (name && !strcmp(name, "pc\\frontend_legacy\\keyboard")) target = "controls_setup\\controls_settings_screen"; + else if (name && !strcmp(name, "pc\\frontend_legacy\\controller")) target = "controller_remapping\\controller_remapping_screen"; + else if (name && !strcmp(name, "pc\\frontend_legacy\\glyphs")) target = "controller_appearance\\controller_appearance_screen"; + if (target && focused->parent) + { + if (!game_function("plyr prf save adv cntl set", focused->parent, event, &deleted)) return FALSE; + snprintf(path, sizeof(path), "pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\%s", target); + return ui_widget_port_open(focused, path, &deleted); + } + } + /* event_manager's button event (3), Y (also the keyboard's Tab). + * A repeat must not reopen the freshly created screen. */ + if (!frontend_menu_legacy_root(widget) || event->type != 3 || + event->data.button.index != _gamepad_analog_button_y || event->data.button.value != 1) + return FALSE; + return ui_widget_load_by_name_or_tag(FRONTEND_MENU_SCREEN, NONE, NULL, + widget->local_player_index, NONE, NONE, NONE) != NULL; +} + +/* The native description's frames and strings correspond only to native + * rows. Inserted links have no matching frame; Save retains its old index. */ +short frontend_menu_legacy_description_index(struct widget_instance *list, short index) +{ + struct widget_instance *child, *detail; + char const *name; + short native_index = 0; + boolean added; + if (!list || !frontend_menu_can_edit() || !main_menu_is_active() || network_game_is_active() || + strcmp(frontend_menu_style(), "xbox")) return index; + name = tag_get_name(list->definition_tag_index); + if (!name || strcmp(name, "ui\\shell\\main_menu\\settings_select\\player_setup\\player_profile_edit\\profile_edit_select_list")) return index; + for (child = list->child; child; child = child->next) + { + name = tag_get_name(child->definition_tag_index); + added = name && !strncmp(name, "pc\\frontend_legacy\\", 19); + if (child == list->focused_child) + { + if (list->parameters.list.extended_description) + for (detail = list->parameters.list.extended_description->child; detail; detail = detail->next) + { + char const *path = tag_get_name(detail->definition_tag_index); + boolean help = path && !strcmp(path, "pc\\frontend_legacy\\description"); + detail->visible = help ? added : !added; + if (help && added) + text_set_length(detail, !strcmp(name + 19, "audio") ? L"Adjust music, sound effects|nand audio playback.|n|nCurrent Profile:" : + !strcmp(name + 19, "video") ? L"Adjust the display, graphics|nand menu style.|n|nCurrent Profile:" : + L"Configure network connections|nand online play.|n|nCurrent Profile:", 128); + } + return added ? NONE : native_index; + } + if (!added) native_index++; + } + return index; +} + +/* Advanced Controls' native help requires a spinner in every selected row. + * The appended editor links are actions, so leave that service to its rows. */ +int frontend_menu_legacy_controls_help(struct widget_instance *list) +{ + char const *name; + boolean added; + if (!list || !frontend_menu_can_edit() || strcmp(frontend_menu_style(), "xbox")) return FALSE; + name = tag_get_name(list->definition_tag_index); + if (!name || strcmp(name, "ui\\shell\\main_menu\\settings_select\\player_setup\\player_profile_edit\\advanced_controls\\advanced_controls_menu")) return FALSE; + name = list->focused_child ? tag_get_name(list->focused_child->definition_tag_index) : NULL; + added = name && !strncmp(name, "pc\\frontend_legacy\\", 19); + if (list->parameters.list.extended_description) list->parameters.list.extended_description->visible = !added; + return added; +} + +/* Tags live for one ui.map. Keep indices, never widget pointers: changing a + * page destroys its instances. No config writes occur while browsing pages. */ +#define FRONTEND_PENDING_MAX 256 +#define FRONTEND_ROWS_VISIBLE 8 +static struct +{ + boolean owns_profile, error; + short count; + short first[NUMBEROF(frontend_pages)]; + struct { long tag; short index, original; } pending[FRONTEND_PENDING_MAX]; +} frontend_session; + +static void settings_help(struct widget_instance *list); +static void master_servers_show(struct widget_instance *list); + +void frontend_menu_session_reset(void) +{ + mcc_xbox_reset(); + if (frontend_session.owns_profile) + player_ui_end_editing_profile(); + memset(&frontend_session, 0, sizeof(frontend_session)); +} + +static short frontend_page(struct widget_instance *root) +{ + char const *path = root ? tag_get_name(root->definition_tag_index) : NULL; + short page; + for (page = 0; path && page < NUMBEROF(frontend_pages); page++) + if (!strcmp(path, frontend_pages[page].path) || !strcmp(path, frontend_pages[page].paused)) return page; + return NONE; +} + +static void frontend_error(struct widget_instance *root, wchar_t const *message) +{ + frontend_session.error = TRUE; + text_set(named(root, "status", 0), message); +} + +static short frontend_pending(long tag) +{ + short i; + for (i = 0; i < frontend_session.count; i++) + if (frontend_session.pending[i].tag == tag) return i; + return NONE; +} + +static boolean frontend_restore(struct widget_instance *spinner, struct pc_menu_setting *setting) +{ + short entry = frontend_pending(spinner->definition_tag_index); + setting->loaded_index = NONE; + setting_load(spinner); + if (entry != NONE) + { + spinner->parameters.list.selected_index = frontend_session.pending[entry].index; + setting->loaded_index = frontend_session.pending[entry].original; + } + /* No profile is silently created, and an unavailable profile cannot be + * edited as though its zero-initialized spinner were a real value. */ + if (!strncmp(setting->setting, "profile.", 8)) + { + spinner->parent->disabled = !frontend_session.owns_profile; + spinner->parent->visible = frontend_session.owns_profile; + } + return TRUE; +} + +static boolean frontend_capture(struct widget_instance *widget) +{ + struct widget_instance *child; + struct pc_menu_setting *setting; + short entry, index; + for (child = widget->child; child; child = child->next) + { + setting = child->type == 2 && !spinner_item(child) ? + pc_menu_setting_get(child->definition_tag_index) : NULL; + if (!setting) + { + if (!frontend_capture(child)) return FALSE; + continue; + } + if (setting->loaded_index == NONE) continue; + index = child->parameters.list.selected_index; + if (index < 0 || index >= setting->value_count) return FALSE; + entry = frontend_pending(child->definition_tag_index); + if (entry == NONE) + { + if (index == setting->loaded_index) continue; + if (frontend_session.count == FRONTEND_PENDING_MAX) return FALSE; + entry = frontend_session.count++; + frontend_session.pending[entry].tag = child->definition_tag_index; + frontend_session.pending[entry].original = setting->loaded_index; + } + frontend_session.pending[entry].index = index; + } + return TRUE; +} + +static boolean frontend_commit(void) +{ + struct pc_menu_setting *setting; + short entry, index; + /* Validate the whole batch before writing. Individual config writes may + * still fail; keep pending values and report partial application for retry. */ + for (entry = 0; entry < frontend_session.count; entry++) + { + setting = pc_menu_setting_get(frontend_session.pending[entry].tag); + index = frontend_session.pending[entry].index; + if (!setting || index < 0 || index >= setting->value_count) return FALSE; + } + for (entry = 0; entry < frontend_session.count; entry++) + { + setting = pc_menu_setting_get(frontend_session.pending[entry].tag); + index = frontend_session.pending[entry].index; + if (index != frontend_session.pending[entry].original && + !setting_write(setting->setting, setting->values[index])) return FALSE; + } + if (frontend_session.owns_profile && player_ui_edit_profile_is_dirty() && + !player_ui_save_profile()) return FALSE; + return TRUE; +} + +static boolean frontend_open_page(struct widget_instance *root, short page, boolean *deleted) +{ + if (page < 0 || page >= NUMBEROF(frontend_pages)) return FALSE; + if (!frontend_capture(root)) + { + frontend_error(root, L"Could not keep pending changes. Stay here and retry."); + return FALSE; + } + frontend_session.error = FALSE; + *deleted = ui_widget_load_by_name_or_tag(main_menu_is_active() ? frontend_pages[page].path : frontend_pages[page].paused, NONE, NULL, + root->local_player_index, NONE, NONE, NONE) != NULL; + return *deleted; +} + +static boolean frontend_editor(struct widget_instance *widget, boolean *deleted) +{ + char const *target = NULL; + char const *key = widget->name; + struct widget_instance *root = screen_of(widget); + short entry; + struct pc_menu_setting *setting; + if (!frontend_capture(root)) return FALSE; + if (!strcmp(key, "row_profiles")) + { + for (entry = 0; entry < frontend_session.count; entry++) + { + setting = pc_menu_setting_get(frontend_session.pending[entry].tag); + if (setting && !strncmp(setting->setting, "profile.", 8) && + frontend_session.pending[entry].index != frontend_session.pending[entry].original) break; + } + if (entry < frontend_session.count || + (frontend_session.owns_profile && player_ui_edit_profile_is_dirty())) + { + frontend_error(root, L"Save or cancel profile edits before changing profile."); + return FALSE; + } + /* Unchanged profile entries must not be restored over another profile. */ + for (entry = 0; entry < frontend_session.count;) + { + setting = pc_menu_setting_get(frontend_session.pending[entry].tag); + if (setting && !strncmp(setting->setting, "profile.", 8)) + frontend_session.pending[entry] = frontend_session.pending[--frontend_session.count]; + else entry++; + } + if (frontend_session.owns_profile) player_ui_end_editing_profile(); + frontend_session.owns_profile = FALSE; + frontend_session.error = FALSE; + return ui_widget_port_open(widget, "pc\\main_menu\\profile_manager\\player_profile_manager_screen", deleted); + } + if (!strcmp(key, "row_keyboard")) target = "controls_setup\\controls_settings_screen"; + else if (!strcmp(key, "row_dead_zones")) target = "gamepad_setup\\dead_zones\\dead_zone_settings_screen"; + else if (!strcmp(key, "row_discord")) target = "network_setup\\discord_account\\discord_account_settings_screen"; + else if (!strcmp(key, "row_mcc_downloads")) target = "network_setup\\mcc_downloads\\screen"; + else if (!strcmp(key, "row_gamepad")) target = "controller_remapping\\controller_remapping_screen"; + else + { + if (!frontend_session.owns_profile) + { + frontend_error(root, L"Choose SELECT PROFILE to select or create a profile."); + return FALSE; + } + if (!strcmp(key, "row_name")) + { + /* The existing name editor owns text entry and validation. */ + return game_function("player profile change name", widget, NULL, deleted); + } + if (!strcmp(key, "row_color")) target = "color_edit\\color_select_screen"; + } + if (target) + { + char path[256]; + snprintf(path, sizeof(path), "pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\%s", target); + return ui_widget_port_open(widget, path, deleted); + } + return FALSE; +} + +#include "frontend_navigation.inl" + +static boolean frontend_menu_event(struct widget_instance *widget, char const *name, boolean *deleted) +{ + struct widget_instance *root = screen_of(widget); + struct widget_instance *list, *child; + short index, page; + if (!frontend_menu_can_edit()) return FALSE; + if (frontend_navigation_root(root)) return frontend_navigation_event(widget, name); + page = frontend_page(root); + if (page == NONE) return FALSE; + if (!strcmp(name, "port frontend init")) + { + /* The pause entry already owns a controller-specific profile session. + * Adopt it instead of beginning another (especially on MCC). */ + if (!main_menu_is_active() && player_ui_get_edit_player_profile()) + frontend_session.owns_profile = TRUE; + if (page == 5 && !frontend_session.owns_profile) + frontend_session.owns_profile = pc_menu_profile_edit_begin(); + settings_each(root, frontend_restore); + if (page == 5 && !frontend_session.owns_profile) + frontend_error(root, L"Choose SELECT PROFILE to select or create a profile."); + list = named(root, "options", 0); + child = named(root, "tabs", 0); + if (child) + { + struct widget_instance *tab = child->child; + for (index = 0; tab && index < frontend_pages[page].tab; index++) tab = tab->next; + child->focused_child = tab; + child->parameters.list.selected_index = frontend_pages[page].tab; + } + /* Start on the first option, while Up still reaches the tab bar. */ + for (child = list ? list->child : NULL; child; child = child->next) + if (!strncmp(child->name, "row_", 4) && !child->disabled) + { + list->focused_child = child; + break; + } + return TRUE; + } + if (!strcmp(name, "port frontend defaults")) + { + settings_each(root, setting_default_show); + return TRUE; + } + if (!strcmp(name, "port frontend editor")) return frontend_editor(widget, deleted); + if (!strcmp(name, "port frontend page")) + { + index = !strncmp(widget->name, "tab_", 4) ? atoi(widget->name + 4) : + !strncmp(widget->name, "row_link_", 9) ? atoi(widget->name + 9) : NONE; + return frontend_open_page(root, index, deleted); + } + if (!strcmp(name, "port frontend next tab")) + return frontend_open_page(root, (short)((frontend_pages[page].tab + 1) % 6), deleted); + if (!strcmp(name, "port frontend back") && page >= 6) + return frontend_open_page(root, frontend_pages[page].parent, deleted); + if (!strcmp(name, "port frontend apply")) + { + if (!frontend_capture(root) || !frontend_commit()) + { + frontend_error(root, L"Save failed; some changes may be active. Retry OK."); + return FALSE; + } + platform_display_apply(); + } + else if (strcmp(name, "port frontend cancel") && strcmp(name, "port frontend back")) return FALSE; + frontend_menu_session_reset(); + if (main_menu_is_active()) main_goto_main_menu(); + else + { + ui_widget_port_go_back(root); + *deleted = TRUE; + } + return TRUE; +} + +/* A render-only exclusion: navigation still sees every enabled row. The + * engine calls this before drawing AND before registering mouse targets. */ +int frontend_menu_row_drawable(struct widget_instance *widget) +{ + if (!frontend_menu_available() || !widget || !widget->parent) return TRUE; + if (frontend_multiplayer_root(screen_of(widget))) return frontend_multiplayer_drawable(widget); + if (frontend_navigation_root(screen_of(widget))) return frontend_navigation_drawable(widget); + if (strncmp(widget->name, "row_", 4) || frontend_page(screen_of(widget)) == NONE) return TRUE; + return widget->vertical_offset >= 137 && widget->vertical_offset <= 347; +} + +static struct widget_instance *frontend_setting_row(struct widget_instance *list, char const *key) +{ + struct widget_instance *row, *child; + struct pc_menu_setting *setting; + for (row = list->child; row; row = row->next) + for (child = row->child; child; child = child->next) + { + setting = child->type == 2 ? pc_menu_setting_get(child->definition_tag_index) : NULL; + if (setting && !strcmp(setting->setting, key)) return row; + } + return NULL; +} + +static char const *frontend_row_value(struct widget_instance *row) +{ + struct widget_instance *child; + struct pc_menu_setting *setting; + short index; + for (child = row ? row->child : NULL; child; child = child->next) + { + setting = child->type == 2 ? pc_menu_setting_get(child->definition_tag_index) : NULL; + index = child->parameters.list.selected_index; + if (setting && index >= 0 && index < setting->value_count) return setting->values[index]; + } + return ""; +} + +/* Match the native controller-family selection, using pending values so hiding + * a row never changes its saved preference. High-Res HUD gates these controls. */ +static void frontend_button_rows_show(struct widget_instance *list) +{ + static char const *styles[] = {"display.hud_button_style", "display.hud_button_style_xbox", + "display.hud_button_style_ps", "display.hud_button_style_switch"}; + struct widget_instance *hud = frontend_setting_row(list, "display.high_res_hud"); + struct widget_instance *menu_glyphs = frontend_setting_row(list, "display.menu_button_glyphs"); + struct widget_instance *automatic = frontend_setting_row(list, "input.auto_button_detection"); + struct widget_instance *keyboard = named(list, "row_detected_button_style", 0); + struct widget_instance *bumper = frontend_setting_row(list, "display.hud_bumper_style"); + struct widget_instance *shown, *row; + struct controller_device device; + boolean enabled, detect; + short family = 0, index, port; + int active; + if (!hud || !automatic) return; + enabled = !strcmp(frontend_row_value(hud), "true"); + if (menu_glyphs) menu_glyphs->visible = enabled; + detect = !strcmp(frontend_row_value(automatic), "true"); + active = frontend_input_device(); + port = active >= 0 && active < 4 ? (short)active : controller_of(list); + controller_device_get(port, &device); + if (detect && device.family >= 0 && device.family <= 3) family = (short)device.family; + shown = frontend_setting_row(list, styles[family]); + if (detect && active == -1 && keyboard) shown = keyboard; + automatic->visible = enabled; + if (keyboard) keyboard->visible = enabled && shown == keyboard; + for (index = 0; index < 4; index++) + { + row = frontend_setting_row(list, styles[index]); + if (row) + { + row->visible = enabled && row == shown; + row->disabled = FALSE; + row->alpha_modifier = 1.0f; + } + } + if (bumper) + bumper->visible = enabled && shown && frontend_row_value(shown)[0] && + controller_button_style_index(frontend_row_value(shown)) < 3; + if (list->focused_child && !list->focused_child->visible) + list->focused_child = enabled && shown ? shown : hud; + for (row = list->child, index = 0; row; row = row->next, index++) + if (row == list->focused_child) list->parameters.list.selected_index = index; +} + +static void frontend_rows_show(struct widget_instance *list) +{ + struct widget_instance *resolution = frontend_setting_row(list, "display.resolution"); + struct widget_instance *window = frontend_setting_row(list, "display.window_size"); + struct widget_instance *shown; + struct widget_instance *third = frontend_setting_row(list, "display.third_person"); + struct widget_instance *row, *child; + struct pc_menu_setting *setting; + short index; + if (resolution && window) + { + shown = !strcmp(frontend_row_value(frontend_setting_row(list, "display.mode")), "windowed") ? window : resolution; + resolution->visible = shown == resolution; + window->visible = shown == window; + if (list->focused_child == (shown == resolution ? window : resolution)) list->focused_child = shown; + } + frontend_button_rows_show(list); + if (third) + for (row = list->child; row; row = row->next) + for (child = row->child; child; child = child->next) + { + setting = child->type == 2 ? pc_menu_setting_get(child->definition_tag_index) : NULL; + if (!setting || strncmp(setting->setting, "display.third_person_", 21)) continue; + row->visible = !strcmp(frontend_row_value(third), "true"); + if (!row->visible && list->focused_child == row) list->focused_child = third; + } + for (row = list->child, index = 0; row; row = row->next, index++) + if (row == list->focused_child) list->parameters.list.selected_index = index; +} + +static void frontend_menu_help(struct widget_instance *list) +{ + struct widget_instance *root = screen_of(list); + struct widget_instance *row, *child, *title, *value; + struct pc_menu_setting *setting; + short page = frontend_page(root), count = 0, focused = NONE, index = 0; + short *first; + long strings; + char path[256]; + wchar_t status[ROW_TEXT_LENGTH]; + if (!frontend_menu_can_edit() || page == NONE || strcmp(list->name, "options")) return; + frontend_rows_show(list); + if (!main_menu_is_active()) + for (row = list->child; row; row = row->next) + { + /* Retain the native in-game Settings restrictions: no profile + * replacement or connection changes while a game is running. */ + if (!strncmp(row->name, "row_", 4) && (!strcmp(row->name, "row_profiles") || !strcmp(row->name, "row_name") || + !strcmp(row->name, "row_color") || (page == 3 && + strncmp(row->name, "row_link_", 9)) || (page == 3 && !strcmp(row->name, "row_link_11")))) + row->visible = FALSE; + } + if (list->focused_child && !list->focused_child->visible) + for (row = list->child; row; row = row->next) + if (row->visible && !row->disabled) { list->focused_child = row; break; } + for (row = list->child, index = 0; row; row = row->next, index++) + if (row == list->focused_child) list->parameters.list.selected_index = index; + index = 0; + master_servers_show(list); + first = &frontend_session.first[page]; + for (row = list->child; row; row = row->next) + { + if (strncmp(row->name, "row_", 4) || !row->visible) continue; + if (row == list->focused_child) focused = count; + count++; + } + if (focused != NONE && focused < *first) *first = focused; + if (focused >= *first + FRONTEND_ROWS_VISIBLE) *first = focused - FRONTEND_ROWS_VISIBLE + 1; + if (*first > MAX(0, count - FRONTEND_ROWS_VISIBLE)) *first = MAX(0, count - FRONTEND_ROWS_VISIBLE); + for (row = list->child; row; row = row->next) + if (!strncmp(row->name, "row_", 4) && row->visible) + row->vertical_offset = (short)(137 + 30 * (index++ - *first)); + if (!frontend_session.error) + { + if (count > FRONTEND_ROWS_VISIBLE) + usnprintf(status, NUMBEROF(status) - 1, L"%d-%d / %d UP / DOWN TO SCROLL", *first + 1, MIN(count, *first + FRONTEND_ROWS_VISIBLE), count); + else status[0] = 0; + text_set(named(root, "status", 0), status); + } + settings_help(list); + title = named(root, "help_title", 0); + value = named(root, "help_value", 0); + row = list->focused_child; + if (row && strncmp(row->name, "row_", 4) && list->parameters.list.extended_description) + list->parameters.list.extended_description->parameters.text_box.string_list_index = 0; + index = list->parameters.list.extended_description ? list->parameters.list.extended_description->parameters.text_box.string_list_index - 1 : NONE; + if (!title || !value) return; + title->visible = value->visible = index >= 0; + if (index < 0 || !row) return; + title->parameters.text_box.string_list_index = index; + text_set(value, L""); + for (child = row->child; child; child = child->next) + { + setting = child->type == 2 ? pc_menu_setting_get(child->definition_tag_index) : NULL; + if (!setting) continue; + snprintf(path, sizeof(path), "%s strings", tag_get_name(child->definition_tag_index)); + strings = tag_loaded('ustr', path); + index = child->parameters.list.selected_index; + if (strings != NONE && index >= 0 && index < setting->value_count) + text_set(value, unicode_string_list_get_string(strings, index)); + } +} diff --git a/port/linux/game/frontend_multiplayer.inl b/port/linux/game/frontend_multiplayer.inl new file mode 100644 index 0000000000..98eaeacae9 --- /dev/null +++ b/port/linux/game/frontend_multiplayer.inl @@ -0,0 +1,104 @@ +/* Presentation only. Native callbacks run first and own the session, map + * families, list contents, paging, joins and host authority. */ +static boolean frontend_multiplayer_root(struct widget_instance *root) +{ + char const *name = root ? tag_get_name(root->definition_tag_index) : NULL; + return frontend_menu_available() && main_menu_is_active() && name && + !strncmp(name, "pc\\modern\\network\\", 18); +} + +static boolean frontend_multiplayer_row(struct widget_instance *row) +{ + if (!row->parent || row->parent->type != 3) return FALSE; + return (!strncmp(row->name, "list_item_", 10) && row->name[10] >= '0' && row->name[10] <= '9') || + (!strncmp(row->name, "op_", 3)) || strstr(row->name, "_difficulty_item") != NULL; +} + +static boolean frontend_multiplayer_drawable(struct widget_instance *widget) +{ + short top = 110; + return !frontend_multiplayer_row(widget) || + (widget->vertical_offset >= top && widget->vertical_offset <= 350); +} + +/* The service owns the selected map and difficulty; this changes only the + * Modern widgets used by its embedded difficulty step. */ +static void frontend_multiplayer_difficulty(struct widget_instance *list, short difficulty) +{ + struct widget_instance *root = screen_of(list), *description, *icon, *text, *row, *label; + char path[256]; + char const *name; + long replacement; + size_t length; + if (!frontend_multiplayer_root(root)) return; + description = list->parameters.list.extended_description; + icon = named(description, "difficulty_options", 0); + text = named(description, "difficulty_extended_description", 0); + if (!icon || !text) return; + icon->visible = text->visible = difficulty >= 0 && difficulty < 4; + if (icon->visible) + { + visible_set(named(description, "mp_map_right_item", 0), FALSE); + icon->animation.current_frame_index = difficulty; + text->parameters.text_box.string_list_index = difficulty; + } + for (row = list->child; row; row = row->next) + { + label = named(row, "list_item_text", 0); + name = label ? tag_get_name(label->definition_tag_index) : NULL; + if (!name) continue; + length = strlen(name); + if (length >= sizeof(path) - 10) continue; + strcpy(path, name); + if (length >= 9 && !strcmp(path + length - 9, "_centered")) path[length - 9] = 0; + if (icon->visible) strcat(path, "_centered"); + replacement = tag_loaded('DeLa', path); + if (replacement != NONE) label->definition_tag_index = replacement; + } +} + +static void frontend_multiplayer_update(struct widget_instance *list) +{ + struct widget_instance *root = screen_of(list), *row, *first_row = NULL; + short count = 0, focus = NONE, first = 0, index = 0; + short top = 110; + short capacity = 9; + wchar_t status[64]; + if (!frontend_multiplayer_root(root)) return; + for (row = list->child; row; row = row->next) + if (frontend_multiplayer_row(row) && row->visible) + { + if (!first_row) first_row = row; + if (row == list->focused_child) focus = count; + count++; + } + /* Off-screen rows remain navigable; only rendering and pointer targets + * are clipped. Derive the viewport from live instances, never a global. */ + if (first_row) first = (short)MAX(0, (top - first_row->vertical_offset) / 30); + if (focus != NONE && focus < first) first = focus; + if (focus >= first + capacity) first = (short)(focus - capacity + 1); + first = (short)PIN(first, 0, MAX(0, count - capacity)); + for (row = list->child; row; row = row->next) + if (frontend_multiplayer_row(row) && row->visible) + row->vertical_offset = (short)(top + 30 * (index++ - first)); + status[0] = 0; + if (count > capacity) + usnprintf(status, NUMBEROF(status) - 1, L"%d-%d / %d UP / DOWN TO SCROLL", first + 1, MIN(count, first + capacity), count); + text_set(named(root, "status", 0), status); + /* The native service's instruction exceeds the compact value column. + * Keep the action explicit without truncating an actual invite/address. */ + row = named(list, "invite_value", 0); + if (row && row->parameters.text_box.text && + !wcscmp(row->parameters.text_box.text, L"SELECT TO COPY LINK")) + text_set(row, L"COPY LINK"); + /* Text fields can be longer than their inline value column. Keep the + * full selected value readable above its explanation in Server Setup. */ + if (named(root, "help_value", 0)) + { + wchar_t const *value = L""; + for (row = list->focused_child ? list->focused_child->child : NULL; row; row = row->next) + if (row->type == 1 && strstr(row->name, "_value") && row->parameters.text_box.text) + value = row->parameters.text_box.text; + text_set(named(root, "help_value", 0), value); + } +} diff --git a/port/linux/game/frontend_navigation.inl b/port/linux/game/frontend_navigation.inl new file mode 100644 index 0000000000..2873514f7e --- /dev/null +++ b/port/linux/game/frontend_navigation.inl @@ -0,0 +1,69 @@ +/* Landing screens keep their navigation in widget instances and use the + * existing browser, host and co-op callbacks through generated XML. */ +static boolean frontend_navigation_root(struct widget_instance *root) +{ + char const *name = root ? tag_get_name(root->definition_tag_index) : NULL; + return main_menu_is_active() && !network_game_is_active() && name && + (!strcmp(name, "pc\\modern\\multiplayer\\screen") || !strcmp(name, "pc\\modern\\host\\screen")); +} + +static boolean frontend_navigation_content(struct widget_instance *widget) +{ + return !strncmp(widget->name, "row_", 4) || !strncmp(widget->name, "section_", 8) || !strncmp(widget->name, "rule_", 5); +} + +static boolean frontend_navigation_drawable(struct widget_instance *widget) +{ + short height = !strncmp(widget->name, "rule_", 5) ? 1 : 26; + return !frontend_navigation_content(widget) || + (widget->vertical_offset >= 82 && widget->vertical_offset + height <= 382); +} + +static boolean frontend_navigation_event(struct widget_instance *widget, char const *name) +{ + struct widget_instance *root = screen_of(widget), *list, *row; + if (!frontend_menu_can_edit() || !frontend_navigation_root(root)) return FALSE; + if (strcmp(name, "port frontend navigation init")) return FALSE; + list = named(root, "options", 0); + for (row = list ? list->child : NULL; row; row = row->next) + if (!strncmp(row->name, "row_", 4) && row->visible && !row->disabled) + { + list->focused_child = row; + break; + } + return TRUE; +} + +static void frontend_navigation_update(struct widget_instance *list) +{ + struct widget_instance *root = screen_of(list), *row, *focus, *title; + short shift = 0, index; + boolean overflow = FALSE; + if (!frontend_menu_can_edit() || !frontend_navigation_root(root) || strcmp(list->name, "options")) return; + focus = list->focused_child; + if (focus && !strncmp(focus->name, "row_", 4)) + { + if (focus->vertical_offset < 110) shift = 110 - focus->vertical_offset; + else if (focus->vertical_offset > 356) shift = 356 - focus->vertical_offset; + } + /* Move section labels and rules with their rows. Never hide off-screen + * instances: the existing keyboard, pad and pointer navigation needs them. */ + for (row = list->child; row; row = row->next) + if (frontend_navigation_content(row)) + { + row->vertical_offset += shift; + if (!strncmp(row->name, "row_", 4) && !frontend_navigation_drawable(row)) overflow = TRUE; + } + text_set(named(root, "status", 0), overflow ? L"UP / DOWN TO SCROLL" : L""); + settings_help(list); + index = focus && !strncmp(focus->name, "row_", 4) && list->parameters.list.extended_description ? + list->parameters.list.extended_description->parameters.text_box.string_list_index - 1 : NONE; + if (index == NONE && list->parameters.list.extended_description) + list->parameters.list.extended_description->parameters.text_box.string_list_index = 0; + title = named(root, "help_title", 0); + if (title) + { + title->visible = index >= 0; + if (index >= 0) title->parameters.text_box.string_list_index = index; + } +} diff --git a/port/linux/game/frontend_network_layout.inl b/port/linux/game/frontend_network_layout.inl new file mode 100644 index 0000000000..ab8e913f09 --- /dev/null +++ b/port/linux/game/frontend_network_layout.inl @@ -0,0 +1,412 @@ +/* Generated by tools/frontend_menu.py. Modern multiplayer views only. */ +enum { FRONTEND_NET_FULL, FRONTEND_NET_ROW, FRONTEND_NET_CHOOSER, FRONTEND_NET_LABEL_FULL, FRONTEND_NET_BAR, FRONTEND_NET_BUTTON, FRONTEND_NET_DETAIL, FRONTEND_NET_DETAIL_FIXED, FRONTEND_NET_DETAIL_WRAP, FRONTEND_NET_DETAIL_ICON, FRONTEND_NET_HEADING, FRONTEND_NET_STATUS, FRONTEND_NET_LABEL, FRONTEND_NET_VALUE }; +static struct { char const *name; int role; } const frontend_network_widgets[] = { + {"pc\\modern\\network\\maps\\1\\mp_map_select_screen", FRONTEND_NET_FULL}, + {"pc\\modern\\network\\maps\\0\\connected_map_select_wrapper", FRONTEND_NET_FULL}, + {"pc\\modern\\network\\maps\\3\\mp_map_select_list_2", FRONTEND_NET_FULL}, + {"pc\\modern\\network\\maps\\4\\list_item_0_map_kind", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\maps\\5\\list_item_0_map_kind_spinner", FRONTEND_NET_CHOOSER}, + {"pc\\modern\\network\\maps\\6\\list_item_1", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\maps\\7\\list_item_text", FRONTEND_NET_LABEL_FULL}, + {"pc\\modern\\network\\maps\\15\\list_item_2", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\maps\\16\\list_item_3", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\maps\\17\\list_item_4", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\maps\\18\\list_item_5", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\maps\\19\\list_item_6", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\maps\\20\\list_item_7", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\maps\\21\\list_item_8", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\maps\\22\\list_item_9", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\maps\\23\\list_item_10", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\maps\\24\\mp_map_select_button_bar", FRONTEND_NET_BAR}, + {"pc\\modern\\network\\maps\\25\\mp_map_select_button_ok", FRONTEND_NET_BUTTON}, + {"pc\\modern\\network\\maps\\26\\common_button_back", FRONTEND_NET_BUTTON}, + {"pc\\modern\\network\\maps\\27\\mp_map_extended_desc", FRONTEND_NET_FULL}, + {"pc\\modern\\network\\maps\\30\\mp_map_right_name", FRONTEND_NET_DETAIL}, + {"pc\\modern\\network\\maps\\31\\mp_map_right_pic", FRONTEND_NET_DETAIL_FIXED}, + {"pc\\modern\\network\\maps\\32\\mp_map_right_data", FRONTEND_NET_DETAIL_WRAP}, + {"pc\\modern\\network\\maps\\33\\replay_level_right_name", FRONTEND_NET_DETAIL}, + {"pc\\modern\\network\\maps\\34\\replay_level_right_pic", FRONTEND_NET_DETAIL_FIXED}, + {"pc\\modern\\network\\maps\\35\\replay_level_right_data", FRONTEND_NET_DETAIL_WRAP}, + {"pc\\modern\\network\\maps\\36\\mcc_folder_name", FRONTEND_NET_DETAIL}, + {"pc\\modern\\network\\maps\\37\\mcc_folder_help", FRONTEND_NET_DETAIL_WRAP}, + {"pc\\modern\\network\\maps\\39\\difficulty_options", FRONTEND_NET_DETAIL_ICON}, + {"pc\\modern\\network\\maps\\40\\difficulty_extended_description", FRONTEND_NET_DETAIL_WRAP}, + {"pc\\modern\\network\\maps\\7\\list_item_text_centered", FRONTEND_NET_LABEL_FULL}, + {"pc\\modern\\network\\maps\\title", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\maps\\help_panel", FRONTEND_NET_DETAIL}, + {"pc\\modern\\network\\maps\\rule", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\maps\\section", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\maps\\prompts", FRONTEND_NET_STATUS}, + {"pc\\modern\\network\\maps\\status", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\gametypes\\1\\gametype_select_screen", FRONTEND_NET_FULL}, + {"pc\\modern\\network\\gametypes\\0\\gametype_select_screen_wrapper", FRONTEND_NET_FULL}, + {"pc\\modern\\network\\gametypes\\3\\gametype_select_list_2", FRONTEND_NET_FULL}, + {"pc\\modern\\network\\gametypes\\4\\list_item_0_chooser", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\gametypes\\5\\list_item_0_chooser_spinner", FRONTEND_NET_CHOOSER}, + {"pc\\modern\\network\\gametypes\\6\\list_item_1", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\gametypes\\7\\list_item_text", FRONTEND_NET_LABEL_FULL}, + {"pc\\modern\\network\\gametypes\\15\\list_item_2", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\gametypes\\16\\list_item_3", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\gametypes\\17\\list_item_4", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\gametypes\\18\\list_item_5", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\gametypes\\19\\list_item_6", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\gametypes\\20\\list_item_7", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\gametypes\\21\\list_item_8", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\gametypes\\22\\list_item_9", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\gametypes\\23\\list_item_10", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\gametypes\\24\\gametype_select_button_bar", FRONTEND_NET_BAR}, + {"pc\\modern\\network\\gametypes\\25\\gametype_select_button_ok", FRONTEND_NET_BUTTON}, + {"pc\\modern\\network\\gametypes\\26\\common_button_back", FRONTEND_NET_BUTTON}, + {"pc\\modern\\network\\gametypes\\27\\gametype_extended_desc", FRONTEND_NET_FULL}, + {"pc\\modern\\network\\gametypes\\30\\gametype_right_name", FRONTEND_NET_DETAIL}, + {"pc\\modern\\network\\gametypes\\31\\gametype_right_pic", FRONTEND_NET_DETAIL_FIXED}, + {"pc\\modern\\network\\gametypes\\32\\gametype_right_data", FRONTEND_NET_DETAIL_WRAP}, + {"pc\\modern\\network\\gametypes\\title", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\gametypes\\help_panel", FRONTEND_NET_DETAIL}, + {"pc\\modern\\network\\gametypes\\rule", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\gametypes\\section", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\gametypes\\prompts", FRONTEND_NET_STATUS}, + {"pc\\modern\\network\\gametypes\\status", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\server\\0\\server_settings_screen", FRONTEND_NET_FULL}, + {"pc\\modern\\network\\server\\2\\options_menu", FRONTEND_NET_FULL}, + {"pc\\modern\\network\\server\\3\\op_server_name", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\server\\4\\server_name_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\server\\5\\server_name_value", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\server\\6\\op_max_players", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\server\\7\\max_players_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\server\\8\\max_players_spinner", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\server\\9\\op_listing", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\server\\10\\listing_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\server\\11\\listing_spinner", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\server\\12\\op_password", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\server\\13\\password_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\server\\14\\password_value", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\server\\15\\op_session_options", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\server\\16\\session_options_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\server\\17\\op_map_share_options", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\server\\18\\map_share_options_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\server\\19\\op_coop_options", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\server\\20\\coop_options_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\server\\21\\op_voice_options", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\server\\22\\voice_options_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\server\\23\\op_game_type", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\server\\24\\game_type_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\server\\25\\game_type_value", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\server\\26\\op_player_options", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\server\\27\\player_options_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\server\\28\\player_options_value", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\server\\29\\op_item_options", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\server\\30\\item_options_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\server\\31\\item_options_value", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\server\\32\\op_vehicle_options", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\server\\33\\vehicle_options_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\server\\34\\vehicle_options_value", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\server\\35\\op_indicator_options", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\server\\36\\indicator_options_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\server\\37\\indicator_options_value", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\server\\38\\op_team_options", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\server\\39\\team_options_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\server\\40\\team_options_value", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\server\\41\\button_bar", FRONTEND_NET_BAR}, + {"pc\\modern\\network\\server\\42\\button_bots", FRONTEND_NET_BUTTON}, + {"pc\\modern\\network\\server\\43\\button_ok", FRONTEND_NET_BUTTON}, + {"pc\\modern\\network\\server\\44\\common_button_cancel", FRONTEND_NET_BUTTON}, + {"pc\\modern\\network\\server\\45\\help", FRONTEND_NET_DETAIL_WRAP}, + {"pc\\modern\\network\\server\\help_value", FRONTEND_NET_DETAIL_WRAP}, + {"pc\\modern\\network\\server\\title", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\server\\help_panel", FRONTEND_NET_DETAIL}, + {"pc\\modern\\network\\server\\rule", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\server\\section", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\server\\prompts", FRONTEND_NET_STATUS}, + {"pc\\modern\\network\\server\\status", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\session\\0\\session_options_screen", FRONTEND_NET_FULL}, + {"pc\\modern\\network\\session\\2\\options_menu", FRONTEND_NET_FULL}, + {"pc\\modern\\network\\session\\3\\op_session_compatibility", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\session\\4\\session_compatibility_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\session\\5\\session_compatibility_spinner", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\session\\6\\op_camera_policy", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\session\\7\\camera_policy_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\session\\8\\camera_policy_spinner", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\session\\9\\op_invite", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\session\\10\\invite_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\session\\11\\invite_value", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\session\\12\\button_bar", FRONTEND_NET_BAR}, + {"pc\\modern\\network\\session\\13\\common_button_cancel", FRONTEND_NET_BUTTON}, + {"pc\\modern\\network\\session\\14\\help", FRONTEND_NET_DETAIL_WRAP}, + {"pc\\modern\\network\\session\\help_value", FRONTEND_NET_DETAIL_WRAP}, + {"pc\\modern\\network\\session\\title", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\session\\help_panel", FRONTEND_NET_DETAIL}, + {"pc\\modern\\network\\session\\rule", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\session\\section", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\session\\prompts", FRONTEND_NET_STATUS}, + {"pc\\modern\\network\\session\\status", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\lobby\\0\\lobby_screen", FRONTEND_NET_FULL}, + {"pc\\modern\\network\\lobby\\2\\lobby_list", FRONTEND_NET_FULL}, + {"pc\\modern\\network\\lobby\\3\\list_item_0", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\lobby\\4\\list_item_text", FRONTEND_NET_LABEL_FULL}, + {"pc\\modern\\network\\lobby\\8\\list_item_1", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\lobby\\9\\list_item_2", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\lobby\\10\\list_item_3", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\lobby\\11\\list_item_4", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\lobby\\12\\list_item_5", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\lobby\\13\\list_item_6", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\lobby\\14\\list_item_7", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\lobby\\15\\list_item_8", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\lobby\\16\\list_item_9", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\lobby\\17\\list_item_10", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\lobby\\18\\lobby_button_bar", FRONTEND_NET_BAR}, + {"pc\\modern\\network\\lobby\\19\\lobby_button_team", FRONTEND_NET_BUTTON}, + {"pc\\modern\\network\\lobby\\20\\lobby_button_start", FRONTEND_NET_BUTTON}, + {"pc\\modern\\network\\lobby\\21\\lobby_button_add", FRONTEND_NET_BUTTON}, + {"pc\\modern\\network\\lobby\\22\\lobby_button_leave", FRONTEND_NET_BUTTON}, + {"pc\\modern\\network\\lobby\\23\\lobby_button_bots", FRONTEND_NET_BUTTON}, + {"pc\\modern\\network\\lobby\\24\\lobby_desc", FRONTEND_NET_FULL}, + {"pc\\modern\\network\\lobby\\27\\lobby_map_pic", FRONTEND_NET_DETAIL_FIXED}, + {"pc\\modern\\network\\lobby\\28\\lobby_map_name", FRONTEND_NET_DETAIL}, + {"pc\\modern\\network\\lobby\\29\\replay_level_right_pic", FRONTEND_NET_DETAIL_FIXED}, + {"pc\\modern\\network\\lobby\\30\\replay_level_right_name", FRONTEND_NET_DETAIL}, + {"pc\\modern\\network\\lobby\\31\\lobby_game_data", FRONTEND_NET_DETAIL_WRAP}, + {"pc\\modern\\network\\lobby\\33\\lobby_join_help", FRONTEND_NET_STATUS}, + {"pc\\modern\\network\\lobby\\title", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\lobby\\help_panel", FRONTEND_NET_DETAIL}, + {"pc\\modern\\network\\lobby\\rule", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\lobby\\section", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\lobby\\prompts", FRONTEND_NET_STATUS}, + {"pc\\modern\\network\\lobby\\status", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\preview\\0\\preview_screen", FRONTEND_NET_FULL}, + {"pc\\modern\\network\\preview\\2\\preview_list", FRONTEND_NET_FULL}, + {"pc\\modern\\network\\preview\\3\\preview_status", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\preview\\4\\preview_button_bar", FRONTEND_NET_BAR}, + {"pc\\modern\\network\\preview\\5\\preview_button_join", FRONTEND_NET_BUTTON}, + {"pc\\modern\\network\\preview\\6\\preview_button_add", FRONTEND_NET_BUTTON}, + {"pc\\modern\\network\\preview\\7\\preview_button_back", FRONTEND_NET_BUTTON}, + {"pc\\modern\\network\\preview\\8\\lobby_desc", FRONTEND_NET_FULL}, + {"pc\\modern\\network\\preview\\11\\lobby_map_pic", FRONTEND_NET_DETAIL_FIXED}, + {"pc\\modern\\network\\preview\\12\\lobby_map_name", FRONTEND_NET_DETAIL}, + {"pc\\modern\\network\\preview\\13\\replay_level_right_pic", FRONTEND_NET_DETAIL_FIXED}, + {"pc\\modern\\network\\preview\\14\\replay_level_right_name", FRONTEND_NET_DETAIL}, + {"pc\\modern\\network\\preview\\15\\lobby_game_data", FRONTEND_NET_DETAIL_WRAP}, + {"pc\\modern\\network\\preview\\17\\lobby_join_help", FRONTEND_NET_STATUS}, + {"pc\\modern\\network\\preview\\title", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\preview\\help_panel", FRONTEND_NET_DETAIL}, + {"pc\\modern\\network\\preview\\rule", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\preview\\section", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\preview\\prompts", FRONTEND_NET_STATUS}, + {"pc\\modern\\network\\preview\\status", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\bots\\0\\bots_screen", FRONTEND_NET_FULL}, + {"pc\\modern\\network\\bots\\2\\options_menu", FRONTEND_NET_FULL}, + {"pc\\modern\\network\\bots\\3\\op_count", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\bots\\4\\count_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\bots\\5\\count_spinner", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\bots\\6\\op_network", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\bots\\7\\network_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\bots\\8\\network_spinner", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\bots\\9\\op_skill", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\bots\\10\\skill_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\bots\\11\\skill_spinner", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\bots\\12\\op_teams", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\bots\\13\\teams_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\bots\\14\\teams_spinner", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\bots\\15\\op_enhanced", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\bots\\16\\enhanced_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\bots\\17\\enhanced_spinner", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\bots\\18\\op_vehicles", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\bots\\19\\vehicles_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\bots\\20\\vehicles_spinner", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\bots\\21\\op_routes", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\bots\\22\\routes_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\bots\\23\\routes_spinner", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\bots\\24\\op_thread", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\bots\\25\\thread_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\bots\\26\\thread_spinner", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\bots\\27\\op_manage", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\bots\\28\\manage_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\bots\\29\\button_bar", FRONTEND_NET_BAR}, + {"pc\\modern\\network\\bots\\30\\button_defaults", FRONTEND_NET_BUTTON}, + {"pc\\modern\\network\\bots\\31\\button_ok", FRONTEND_NET_BUTTON}, + {"pc\\modern\\network\\bots\\32\\common_button_cancel", FRONTEND_NET_BUTTON}, + {"pc\\modern\\network\\bots\\33\\help", FRONTEND_NET_DETAIL_WRAP}, + {"pc\\modern\\network\\bots\\title", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\bots\\help_panel", FRONTEND_NET_DETAIL}, + {"pc\\modern\\network\\bots\\rule", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\bots\\section", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\bots\\prompts", FRONTEND_NET_STATUS}, + {"pc\\modern\\network\\bots\\status", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\sharing\\0\\map_sharing_settings_screen", FRONTEND_NET_FULL}, + {"pc\\modern\\network\\sharing\\2\\options_menu", FRONTEND_NET_FULL}, + {"pc\\modern\\network\\sharing\\3\\op_mcc_map_share", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\sharing\\4\\mcc_map_share_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\sharing\\5\\mcc_map_share_spinner", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\sharing\\6\\op_map_download", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\sharing\\7\\map_download_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\sharing\\8\\map_download_spinner", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\sharing\\9\\op_map_seed", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\sharing\\10\\map_seed_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\sharing\\11\\map_seed_spinner", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\sharing\\12\\op_map_seed_upload", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\sharing\\13\\map_seed_upload_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\sharing\\14\\map_seed_upload_spinner", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\sharing\\15\\op_mcc_packages", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\sharing\\16\\mcc_packages_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\sharing\\17\\op_mcc_downloads", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\sharing\\18\\mcc_downloads_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\sharing\\19\\button_bar", FRONTEND_NET_BAR}, + {"pc\\modern\\network\\sharing\\20\\button_defaults", FRONTEND_NET_BUTTON}, + {"pc\\modern\\network\\sharing\\21\\button_ok", FRONTEND_NET_BUTTON}, + {"pc\\modern\\network\\sharing\\22\\common_button_cancel", FRONTEND_NET_BUTTON}, + {"pc\\modern\\network\\sharing\\23\\help", FRONTEND_NET_DETAIL_WRAP}, + {"pc\\modern\\network\\sharing\\title", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\sharing\\help_panel", FRONTEND_NET_DETAIL}, + {"pc\\modern\\network\\sharing\\rule", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\sharing\\section", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\sharing\\prompts", FRONTEND_NET_STATUS}, + {"pc\\modern\\network\\sharing\\status", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\mcc_packages\\0\\mcc_packages_screen", FRONTEND_NET_FULL}, + {"pc\\modern\\network\\mcc_packages\\2\\options_menu", FRONTEND_NET_FULL}, + {"pc\\modern\\network\\mcc_packages\\3\\op_workshop_maps", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\mcc_packages\\4\\workshop_maps_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\mcc_packages\\5\\workshop_maps_spinner", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\mcc_packages\\6\\op_mcc_campaigns", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\mcc_packages\\7\\mcc_campaigns_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\mcc_packages\\8\\mcc_campaigns_spinner", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\mcc_packages\\9\\op_mcc_collections", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\mcc_packages\\10\\mcc_collections_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\mcc_packages\\11\\mcc_collections_spinner", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\mcc_packages\\12\\button_bar", FRONTEND_NET_BAR}, + {"pc\\modern\\network\\mcc_packages\\13\\button_defaults", FRONTEND_NET_BUTTON}, + {"pc\\modern\\network\\mcc_packages\\14\\button_ok", FRONTEND_NET_BUTTON}, + {"pc\\modern\\network\\mcc_packages\\15\\common_button_cancel", FRONTEND_NET_BUTTON}, + {"pc\\modern\\network\\mcc_packages\\16\\help", FRONTEND_NET_DETAIL_WRAP}, + {"pc\\modern\\network\\mcc_packages\\title", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\mcc_packages\\help_panel", FRONTEND_NET_DETAIL}, + {"pc\\modern\\network\\mcc_packages\\rule", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\mcc_packages\\section", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\mcc_packages\\prompts", FRONTEND_NET_STATUS}, + {"pc\\modern\\network\\mcc_packages\\status", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\coop\\0\\coop_options_screen", FRONTEND_NET_FULL}, + {"pc\\modern\\network\\coop\\2\\coop_options_menu", FRONTEND_NET_FULL}, + {"pc\\modern\\network\\coop\\3\\op_coop_friendly_fire", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\coop\\4\\coop_friendly_fire_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\coop\\5\\coop_friendly_fire_spinner", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\coop\\6\\op_coop_extra_enemies", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\coop\\7\\coop_extra_enemies_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\coop\\8\\coop_extra_enemies_spinner", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\coop\\9\\op_coop_extra_pickups", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\coop\\10\\coop_extra_pickups_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\coop\\11\\coop_extra_pickups_spinner", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\coop\\12\\op_coop_extra_vehicles", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\coop\\13\\coop_extra_vehicles_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\coop\\14\\coop_extra_vehicles_spinner", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\coop\\15\\op_coop_enemies_multiplier", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\coop\\16\\coop_enemies_multiplier_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\coop\\17\\coop_enemies_multiplier_spinner", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\coop\\18\\op_coop_enemies_per_player", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\coop\\19\\coop_enemies_per_player_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\coop\\20\\coop_enemies_per_player_spinner", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\coop\\21\\op_coop_player_collisions", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\coop\\22\\coop_player_collisions_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\coop\\23\\coop_player_collisions_spinner", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\coop\\24\\op_coop_ally_friendly_fire", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\coop\\25\\coop_ally_friendly_fire_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\coop\\26\\coop_ally_friendly_fire_spinner", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\coop\\27\\op_coop_team_wipe", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\coop\\28\\coop_team_wipe_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\coop\\29\\coop_team_wipe_spinner", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\coop\\30\\op_coop_vehicle_riding", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\coop\\31\\coop_vehicle_riding_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\coop\\32\\coop_vehicle_riding_spinner", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\coop\\33\\coop_options_button_bar", FRONTEND_NET_BAR}, + {"pc\\modern\\network\\coop\\34\\coop_options_button_ok", FRONTEND_NET_BUTTON}, + {"pc\\modern\\network\\coop\\35\\common_button_cancel", FRONTEND_NET_BUTTON}, + {"pc\\modern\\network\\coop\\36\\coop_options_help", FRONTEND_NET_DETAIL_WRAP}, + {"pc\\modern\\network\\coop\\title", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\coop\\help_panel", FRONTEND_NET_DETAIL}, + {"pc\\modern\\network\\coop\\rule", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\coop\\section", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\coop\\prompts", FRONTEND_NET_STATUS}, + {"pc\\modern\\network\\coop\\status", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\voice\\0\\voice_options_screen", FRONTEND_NET_FULL}, + {"pc\\modern\\network\\voice\\2\\voice_options_menu", FRONTEND_NET_FULL}, + {"pc\\modern\\network\\voice\\3\\op_voice_mode", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\voice\\4\\voice_mode_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\voice\\5\\voice_mode_spinner", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\voice\\6\\op_voice_lobby", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\voice\\7\\voice_lobby_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\voice\\8\\voice_lobby_spinner", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\voice\\9\\op_voice_kbps", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\voice\\10\\voice_kbps_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\voice\\11\\voice_kbps_spinner", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\voice\\12\\op_voice_proximity", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\voice\\13\\voice_proximity_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\voice\\14\\voice_proximity_spinner", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\voice\\15\\op_votekick", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\voice\\16\\votekick_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\voice\\17\\votekick_spinner", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\voice\\18\\op_text_chat", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\voice\\19\\text_chat_label", FRONTEND_NET_LABEL}, + {"pc\\modern\\network\\voice\\20\\text_chat_spinner", FRONTEND_NET_VALUE}, + {"pc\\modern\\network\\voice\\21\\voice_options_button_bar", FRONTEND_NET_BAR}, + {"pc\\modern\\network\\voice\\22\\voice_options_button_ok", FRONTEND_NET_BUTTON}, + {"pc\\modern\\network\\voice\\23\\common_button_cancel", FRONTEND_NET_BUTTON}, + {"pc\\modern\\network\\voice\\24\\voice_options_help", FRONTEND_NET_DETAIL_WRAP}, + {"pc\\modern\\network\\voice\\title", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\voice\\help_panel", FRONTEND_NET_DETAIL}, + {"pc\\modern\\network\\voice\\rule", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\voice\\section", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\voice\\prompts", FRONTEND_NET_STATUS}, + {"pc\\modern\\network\\voice\\status", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\campaign\\0\\solo_level_select_screen", FRONTEND_NET_FULL}, + {"pc\\modern\\network\\campaign\\2\\solo_level_select_list", FRONTEND_NET_FULL}, + {"pc\\modern\\network\\campaign\\3\\list_item_0_map_kind", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\campaign\\4\\list_item_0_map_kind_spinner", FRONTEND_NET_CHOOSER}, + {"pc\\modern\\network\\campaign\\5\\list_item_1", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\campaign\\6\\list_item_text", FRONTEND_NET_LABEL_FULL}, + {"pc\\modern\\network\\campaign\\14\\list_item_2", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\campaign\\15\\list_item_3", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\campaign\\16\\list_item_4", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\campaign\\17\\list_item_5", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\campaign\\18\\list_item_6", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\campaign\\19\\list_item_7", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\campaign\\20\\list_item_8", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\campaign\\21\\list_item_9", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\campaign\\22\\list_item_10", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\campaign\\23\\solo_level_select_button_bar", FRONTEND_NET_BAR}, + {"pc\\modern\\network\\campaign\\24\\solo_level_select_button_ok", FRONTEND_NET_BUTTON}, + {"pc\\modern\\network\\campaign\\25\\common_button_back", FRONTEND_NET_BUTTON}, + {"pc\\modern\\network\\campaign\\26\\solo_level_extended_desc", FRONTEND_NET_FULL}, + {"pc\\modern\\network\\campaign\\29\\replay_level_right_name", FRONTEND_NET_DETAIL}, + {"pc\\modern\\network\\campaign\\30\\replay_level_right_pic", FRONTEND_NET_DETAIL_FIXED}, + {"pc\\modern\\network\\campaign\\31\\replay_level_right_data", FRONTEND_NET_DETAIL_WRAP}, + {"pc\\modern\\network\\campaign\\32\\difficulty_indicator", FRONTEND_NET_DETAIL_ICON}, + {"pc\\modern\\network\\campaign\\33\\mp_map_right_name", FRONTEND_NET_DETAIL}, + {"pc\\modern\\network\\campaign\\34\\mp_map_right_pic", FRONTEND_NET_DETAIL_FIXED}, + {"pc\\modern\\network\\campaign\\35\\mp_map_right_data", FRONTEND_NET_DETAIL_WRAP}, + {"pc\\modern\\network\\campaign\\36\\mcc_folder_name", FRONTEND_NET_DETAIL}, + {"pc\\modern\\network\\campaign\\37\\mcc_folder_help", FRONTEND_NET_DETAIL_WRAP}, + {"pc\\modern\\network\\campaign\\title", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\campaign\\help_panel", FRONTEND_NET_DETAIL}, + {"pc\\modern\\network\\campaign\\rule", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\campaign\\section", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\campaign\\prompts", FRONTEND_NET_STATUS}, + {"pc\\modern\\network\\campaign\\status", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\difficulty\\0\\difficulty_select_list_screen", FRONTEND_NET_FULL}, + {"pc\\modern\\network\\difficulty\\1\\difficulty_select_list", FRONTEND_NET_FULL}, + {"pc\\modern\\network\\difficulty\\2\\kindergarten_difficulty_item", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\difficulty\\3\\normal_difficulty_item", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\difficulty\\4\\hard_difficulty_item", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\difficulty\\5\\impossible_difficulty_item", FRONTEND_NET_ROW}, + {"pc\\modern\\network\\difficulty\\6\\difficulty_select_button_bar", FRONTEND_NET_BAR}, + {"pc\\modern\\network\\difficulty\\7\\difficulty_select_button_ok", FRONTEND_NET_BUTTON}, + {"pc\\modern\\network\\difficulty\\8\\common_button_back", FRONTEND_NET_BUTTON}, + {"pc\\modern\\network\\difficulty\\9\\difficulty_ext_desc", FRONTEND_NET_FULL}, + {"pc\\modern\\network\\difficulty\\10\\difficulty_options", FRONTEND_NET_DETAIL_ICON}, + {"pc\\modern\\network\\difficulty\\11\\difficulty_extended_description", FRONTEND_NET_DETAIL_WRAP}, + {"pc\\modern\\network\\difficulty\\13\\warning_message", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\difficulty\\screen", FRONTEND_NET_FULL}, + {"pc\\modern\\network\\difficulty\\title", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\difficulty\\help_panel", FRONTEND_NET_DETAIL}, + {"pc\\modern\\network\\difficulty\\rule", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\difficulty\\section", FRONTEND_NET_HEADING}, + {"pc\\modern\\network\\difficulty\\prompts", FRONTEND_NET_STATUS}, + {"pc\\modern\\network\\difficulty\\status", FRONTEND_NET_HEADING}, +}; diff --git a/port/linux/game/frontend_network_routes.inl b/port/linux/game/frontend_network_routes.inl new file mode 100644 index 0000000000..4c9fbf3be2 --- /dev/null +++ b/port/linux/game/frontend_network_routes.inl @@ -0,0 +1,16 @@ +/* Generated by tools/frontend_menu.py; only explicitly migrated roots. */ +static struct { char const *legacy, *modern; } const frontend_network_routes[] = { + {"pc\\main_menu\\multiplayer_type_select\\connected\\connected_map_select_wrapper", "pc\\modern\\network\\maps\\0\\connected_map_select_wrapper"}, + {"pc\\main_menu\\multiplayer_type_select\\connected\\gametype_select_screen_wrapper", "pc\\modern\\network\\gametypes\\0\\gametype_select_screen_wrapper"}, + {"pc\\main_menu\\multiplayer_type_select\\server_settings\\server_settings_screen", "pc\\modern\\network\\server\\0\\server_settings_screen"}, + {"pc\\main_menu\\multiplayer_type_select\\server_settings\\session_options\\session_options_screen", "pc\\modern\\network\\session\\0\\session_options_screen"}, + {"pc\\main_menu\\multiplayer_type_select\\lobby\\lobby_screen", "pc\\modern\\network\\lobby\\0\\lobby_screen"}, + {"pc\\main_menu\\multiplayer_type_select\\lobby\\preview_screen", "pc\\modern\\network\\preview\\0\\preview_screen"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\bots\\bots_screen", "pc\\modern\\network\\bots\\0\\bots_screen"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\map_sharing\\map_sharing_settings_screen", "pc\\modern\\network\\sharing\\0\\map_sharing_settings_screen"}, + {"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\mcc_packages\\mcc_packages_screen", "pc\\modern\\network\\mcc_packages\\0\\mcc_packages_screen"}, + {"pc\\main_menu\\multiplayer_type_select\\server_settings\\coop_options\\coop_options_screen", "pc\\modern\\network\\coop\\0\\coop_options_screen"}, + {"pc\\main_menu\\multiplayer_type_select\\server_settings\\voice_options\\voice_options_screen", "pc\\modern\\network\\voice\\0\\voice_options_screen"}, + {"pc\\main_menu\\solo_level_select\\solo_level_select_screen", "pc\\modern\\network\\campaign\\0\\solo_level_select_screen"}, + {"pc\\main_menu\\difficulty_select\\difficulty_select_list_screen", "pc\\modern\\network\\difficulty\\screen"}, +}; diff --git a/port/linux/game/frontend_pages.inl b/port/linux/game/frontend_pages.inl new file mode 100644 index 0000000000..af1e015052 --- /dev/null +++ b/port/linux/game/frontend_pages.inl @@ -0,0 +1,21 @@ +/* Generated by tools/frontend_menu.py; page routes, never legacy widgets. */ +static struct { char const *path; short tab, parent; char const *paused; } const frontend_pages[] = { + {"pc\\modern\\settings", 0, 0, "pc\\modern\\paused\\settings"}, + {"pc\\modern\\audio\\settings", 1, 1, "pc\\modern\\paused\\audio\\settings"}, + {"pc\\modern\\controls\\settings", 2, 2, "pc\\modern\\paused\\controls\\settings"}, + {"pc\\modern\\online\\settings", 3, 3, "pc\\modern\\paused\\online\\settings"}, + {"pc\\modern\\interface\\settings", 4, 4, "pc\\modern\\paused\\interface\\settings"}, + {"pc\\modern\\profile\\settings", 5, 5, "pc\\modern\\paused\\profile\\settings"}, + {"pc\\modern\\graphics\\settings", 0, 0, "pc\\modern\\paused\\graphics\\settings"}, + {"pc\\modern\\first_person\\settings", 0, 0, "pc\\modern\\paused\\first_person\\settings"}, + {"pc\\modern\\lighting\\settings", 0, 6, "pc\\modern\\paused\\lighting\\settings"}, + {"pc\\modern\\bots\\settings", 3, 3, "pc\\modern\\paused\\bots\\settings"}, + {"pc\\modern\\sharing\\settings", 3, 3, "pc\\modern\\paused\\sharing\\settings"}, + {"pc\\modern\\browser\\settings", 3, 3, "pc\\modern\\paused\\browser\\settings"}, + {"pc\\modern\\hud\\settings", 4, 4, "pc\\modern\\paused\\hud\\settings"}, + {"pc\\modern\\streamer\\settings", 4, 4, "pc\\modern\\paused\\streamer\\settings"}, + {"pc\\modern\\touch\\settings", 2, 2, "pc\\modern\\paused\\touch\\settings"}, + {"pc\\modern\\third_person\\settings", 0, 0, "pc\\modern\\paused\\third_person\\settings"}, + {"pc\\modern\\extra_effects\\settings", 0, 6, "pc\\modern\\paused\\extra_effects\\settings"}, + {"pc\\modern\\mcc_packages\\settings", 3, 10, "pc\\modern\\paused\\mcc_packages\\settings"}, +}; diff --git a/port/linux/game/frontend_panel.c b/port/linux/game/frontend_panel.c new file mode 100644 index 0000000000..331ea03d9f --- /dev/null +++ b/port/linux/game/frontend_panel.c @@ -0,0 +1,58 @@ +/* Preserve the modern panels' rounded ends as their middle grows. The engine + * supplies its original Xbox plasma parameters, including screen-anchored waves. */ +#include "cseries.h" +#include "frontend_menu.h" +#include "rasterizer/rasterizer.h" +#include "tag_files/tag_files.h" +#include + +static int frontend_panel_active; + +void frontend_panel_begin(long tag) +{ + char const *name; + frontend_panel_active = 0; + if (!frontend_menu_available()) return; + name = tag_get_name(tag); + if (!name || strncmp(name, "pc\\modern\\", 10)) return; + name = strrchr(name, '\\') + 1; + frontend_panel_active = !strncmp(name, "row_", 4) || !strcmp(name, "help_panel"); + if (!strncmp(tag_get_name(tag), "pc\\modern\\network\\", 18)) + frontend_panel_active |= !strncmp(name, "op_", 3) || + (!strncmp(name, "list_item_", 10) && name[10] >= '0' && name[10] <= '9'); +} + +void frontend_panel_end(void) +{ + frontend_panel_active = 0; +} + +int frontend_panel_draw(struct rasterizer_dynamic_screen_geometry_parameters *parameters, + struct dynamic_screen_vertex *vertices, long source_width) +{ + struct dynamic_screen_vertex part[4]; + real x[4], u[4], cap = 18.0f; + int slice, i; + if (!frontend_panel_active || source_width <= 2 * cap || + vertices[1].position.x - vertices[0].position.x <= 2 * cap) return 0; + x[0] = vertices[0].position.x; + x[1] = x[0] + cap; + x[3] = vertices[1].position.x; + x[2] = x[3] - cap; + u[0] = vertices[0].texture_coordinates.x; + u[3] = vertices[1].texture_coordinates.x; + u[1] = u[0] + (u[3] - u[0]) * cap / source_width; + u[2] = u[3] - (u[3] - u[0]) * cap / source_width; + for (slice = 0; slice < 3; slice++) + { + memcpy(part, vertices, sizeof(part)); + for (i = 0; i < 4; i++) + { + int right = ((i + 1) & 2) != 0; + part[i].position.x = x[slice + right]; + part[i].texture_coordinates.x = u[slice + right]; + } + rasterizer_psuedo_dynamic_screen_quad_draw(parameters, part); + } + return 1; +} diff --git a/port/linux/game/frontend_prompts.c b/port/linux/game/frontend_prompts.c new file mode 100644 index 0000000000..24a6698be3 --- /dev/null +++ b/port/linux/game/frontend_prompts.c @@ -0,0 +1,110 @@ +/* Fixed menu actions are separate from the gameplay binding lookup in + * halo_keyboard.h. A remapped Jump key must never relabel menu Select. */ +#include "cseries.h" +#include "frontend_menu.h" +#include "frontend_prompts.h" +#include "frontend_input.h" +#include "keyboard_prompts.h" +#include "keyboard_glyphs.h" +#include "../src/port_config.h" +#include "tag_files/tag_files.h" +#include "rasterizer/rasterizer.h" +#include "text/draw_string.h" +#include + +void halo_input_shown_name(char const *binding, char *shown, unsigned int size); + +int frontend_prompt_button(int action) +{ + return action == FRONTEND_SELECT ? 0 : action == FRONTEND_CANCEL ? 1 : action == FRONTEND_STYLE ? 3 : -1; +} + +char const *frontend_prompt_key(int action) +{ + return action == FRONTEND_SELECT ? "Return" : action == FRONTEND_CANCEL ? "Escape" : action == FRONTEND_STYLE ? "Tab" : ""; +} + +static void frontend_prompt_text(rectangle2d *cursor, char const *text) +{ + wchar_t wide[160]; + rectangle2d ink, end; + unsigned int i; + for (i = 0; text[i] && i < NUMBEROF(wide) - 1; i++) wide[i] = (unsigned char)text[i]; + wide[i] = 0; + rasterizer_draw_unicode_string(cursor, cursor, NULL, 0, wide); + draw_unicode_string_compute_bounds(cursor, wide, &ink, &end); + cursor->x0 = (short)(ink.x1 + 8); +} + +static void frontend_prompt_action(rectangle2d *cursor, int device, int action, char const *caption, pixel32 color) +{ + char key[64]; + if (keyboard_prompt_menu_enabled(device)) + { + halo_input_shown_name(frontend_prompt_key(action), key, sizeof(key)); + keyboard_glyph_draw(key, cursor, color, TRUE); + } + else if (device >= 0) + { + if (!config_boolean("display.high_res_hud") || + !frontend_glyph_draw((short)device, (short)frontend_prompt_button(action), cursor, color)) + frontend_prompt_text(cursor, action == FRONTEND_SELECT ? "[South]" : action == FRONTEND_CANCEL ? "[East]" : "[North]"); + } + else if (device == -1) + { + halo_input_shown_name(frontend_prompt_key(action), key, sizeof(key)); + frontend_prompt_text(cursor, key); + } + frontend_prompt_text(cursor, caption); +} + +void frontend_prompts_draw(long tag, rectangle2d const *bounds) +{ + char const *name; + rectangle2d cursor; + real_argb_color color; + pixel32 packed; + int device, navigation; + if (!frontend_menu_available()) return; + name = tag_get_name(tag); + if (!name || strncmp(name, "pc\\modern\\", 10)) return; + navigation = !strncmp(name + 10, "multiplayer\\", 12) || !strncmp(name + 10, "host\\", 5) || !strncmp(name + 10, "network\\", 8); + name = strrchr(name, '\\') + 1; + if (strcmp(name, "prompts")) return; + device = frontend_input_device(); + /* A manual controller style is a display preference even when the mouse + * last moved. Automatic mode continues to follow the active input. */ + if (config_boolean("display.high_res_hud") && !config_boolean("input.auto_button_detection") && + !keyboard_prompt_menu_enabled(device)) + device = 0; + cursor = *bounds; + draw_string_get_color(&color); + packed = ((unsigned long)(color.alpha * 255.0f) << 24) | 0xffffffUL; + /* The generated footer uses left justification and the small font. */ + if (device == -2 && !keyboard_prompt_menu_enabled(device)) + frontend_prompt_text(&cursor, navigation ? "Tap an option to select it." : "Tap arrows to change a value. Tap OK or CANCEL."); + else + { + if (keyboard_prompt_menu_enabled(device)) + { + keyboard_glyph_draw("Up", &cursor, packed, TRUE); + keyboard_glyph_draw("Down", &cursor, packed, TRUE); + keyboard_glyph_draw("Left", &cursor, packed, TRUE); + keyboard_glyph_draw("Right", &cursor, packed, TRUE); + frontend_prompt_text(&cursor, "MOVE"); + } + else if (device >= 0 && config_boolean("display.high_res_hud") && + frontend_glyph_draw((short)device, 16, &cursor, packed)) + frontend_prompt_text(&cursor, "MOVE"); + else frontend_prompt_text(&cursor, device >= 0 ? "D-pad: MOVE" : "Arrows: MOVE"); + cursor.x0 = (short)(bounds->x0 + 180); + frontend_prompt_action(&cursor, device, FRONTEND_SELECT, "SELECT", packed); + cursor.x0 = (short)(bounds->x0 + 300); + frontend_prompt_action(&cursor, device, FRONTEND_CANCEL, navigation ? "BACK" : "CANCEL", packed); + if (!navigation) + { + cursor.x0 = (short)(bounds->x0 + 440); + frontend_prompt_action(&cursor, device, FRONTEND_STYLE, "TABS", packed); + } + } +} diff --git a/port/linux/game/frontend_prompts.h b/port/linux/game/frontend_prompts.h new file mode 100644 index 0000000000..414cb5a162 --- /dev/null +++ b/port/linux/game/frontend_prompts.h @@ -0,0 +1,10 @@ +#ifndef FRONTEND_PROMPTS_H +#define FRONTEND_PROMPTS_H +#include "math/integer_math.h" + +enum frontend_prompt_action { FRONTEND_SELECT, FRONTEND_CANCEL, FRONTEND_STYLE }; +int frontend_prompt_button(int action); +char const *frontend_prompt_key(int action); +void frontend_prompts_draw(long tag, rectangle2d const *bounds); +boolean frontend_glyph_draw(short port, short button, rectangle2d *cursor, pixel32 color); +#endif diff --git a/port/linux/game/gulch_build_label.inl b/port/linux/game/gulch_build_label.inl new file mode 100644 index 0000000000..7f295a7fd8 --- /dev/null +++ b/port/linux/game/gulch_build_label.inl @@ -0,0 +1,25 @@ +/* The executable's release number beneath the original Xbox build label. +The generated widget owns its text; the stock label and its input stay intact. */ + +#ifndef HALO_BUILD_NUMBER +#define HALO_BUILD_NUMBER 0 +#endif + +static boolean gulch_build_label_event(struct widget_instance *widget) +{ + char const *name; + char label[32] = "gulch build local"; + wchar_t wide_label[32]; + + if (!widget || widget->type != 1) + return FALSE; + name = tag_get_name(widget->definition_tag_index); + if (!name || strcmp(name, "pc\\main_menu\\gulch_build_number")) + return FALSE; + #if HALO_BUILD_NUMBER > 0 + snprintf(label, sizeof(label), "gulch build %d", HALO_BUILD_NUMBER); + #endif + halo_menus_utf16(label, (unsigned short *)wide_label, NUMBEROF(wide_label)); + text_set(widget, wide_label); + return TRUE; +} diff --git a/port/linux/game/hud_hires_tags.c b/port/linux/game/hud_hires_tags.c index 36c0cee5ea..d6139ebd5f 100644 --- a/port/linux/game/hud_hires_tags.c +++ b/port/linux/game/hud_hires_tags.c @@ -33,8 +33,8 @@ When the texture cannot be drawn, the sprites are drawn from their bitmap. #include "rasterizer/rasterizer.h" #include "text/draw_string.h" #include "hud_button_layout.h" -#include "hud_hires_crosshairs.h" #include "controller_glyphs.h" +#include "hud_hires_crosshairs.h" #include "keyboard_glyphs.h" #include "scenario/scenario_definitions.h" #include "cache/texture_cache.h" @@ -488,7 +488,7 @@ static boolean ce_hud_buttons_stock(struct icon_hud_element_definition const *ic return TRUE; } -/* Shared legacy glyph ownership for gameplay and optional menu legends. */ +/* Shared legacy artwork ownership for gameplay and both PC menu frontends. */ struct bitmap_data *hud_hires_button_bitmap(short style, short slot) { static char const *names[] = { diff --git a/port/linux/game/lighting_config.c b/port/linux/game/lighting_config.c new file mode 100644 index 0000000000..18b8904a00 --- /dev/null +++ b/port/linux/game/lighting_config.c @@ -0,0 +1,46 @@ +/* Avoid repeated locked, full-table configuration searches per light/draw. + Cache values only until the settings generation changes; names and defaults + remain owned by port_config.c. No map, object or host-policy state is cached. */ +#include "lighting_config.h" +#include + +int config_boolean(const char *name); +unsigned long config_changes(void); + +static struct +{ + const char *name; + int value; +} preferences[] = { + {"display.plasma_lighting", 0}, + {"display.muzzle_lighting", 0}, + {"display.plasma_occlusion", 0}, + {"display.ammo_counter_lighting", 0}, + {"display.needler_lighting", 0}, + {"display.jackal_shield_lighting", 0}, + {"display.covenant_shield_lighting", 0}, + {"display.fuel_rod_lighting", 0}, + {"display.weapon_glow", 0}, + {"display.plasma_prong_lighting", 0}, + {"display.vehicle_lighting", 0}, + {"display.world_lighting", 0} +}; + +int lighting_config_boolean(const char *name) +{ + static unsigned long changes; + static int ready; + unsigned int i; + if (!ready || changes != config_changes()) + { + /* A concurrent settings change must cause another refresh, rather + than label partially read preferences with the newer generation. */ + changes = config_changes(); + for (i = 0; i < sizeof(preferences) / sizeof(preferences[0]); i++) + preferences[i].value = config_boolean(preferences[i].name); + ready = 1; + } + for (i = 0; i < sizeof(preferences) / sizeof(preferences[0]); i++) + if (!strcmp(name, preferences[i].name)) return preferences[i].value; + return config_boolean(name); +} diff --git a/port/linux/game/lighting_config.h b/port/linux/game/lighting_config.h new file mode 100644 index 0000000000..4460ae7aab --- /dev/null +++ b/port/linux/game/lighting_config.h @@ -0,0 +1,5 @@ +/* Game/render-thread lighting preferences. Host policy is checked separately. */ +#ifndef LIGHTING_CONFIG_H +#define LIGHTING_CONFIG_H +int lighting_config_boolean(const char *name); +#endif diff --git a/port/linux/game/lighting_menu.c b/port/linux/game/lighting_menu.c new file mode 100644 index 0000000000..9e04b6ae6e --- /dev/null +++ b/port/linux/game/lighting_menu.c @@ -0,0 +1,57 @@ +/* Consolidated ON/OFF controls stage changes until the player saves. Old + preferences are reset once by the platform configuration loader. */ +#include "lighting_menu.h" +#include +#include + +int config_boolean(const char *name); +int config_write(const char *name, const char *value); + +static const struct lighting_menu_group +{ + const char *name; + const char *members[5]; +} groups[] = { + {"lighting.weapon_glow", {"display.weapon_glow", "display.fuel_rod_lighting", + "display.ammo_counter_lighting", "display.needler_lighting", NULL}}, + {"lighting.shield_emitters", {"display.jackal_shield_lighting", "display.covenant_shield_lighting", NULL}}, +}; + +static const struct lighting_menu_group *lighting_menu_group(const char *name) +{ + unsigned int i; + for (i = 0; i < sizeof(groups) / sizeof(groups[0]); i++) + if (!strcmp(name, groups[i].name)) + return &groups[i]; + return NULL; +} + +int lighting_menu_text(const char *name, char *text, unsigned int size, int defaults) +{ + const struct lighting_menu_group *group = lighting_menu_group(name); + int i, any = 0; + if (!group) + return -1; + if (!defaults) + for (i = 0; group->members[i]; i++) + { + int value = config_boolean(group->members[i]); + any |= value; + } + snprintf(text, size, "%s", defaults || !any ? "false" : "true"); + return 1; +} + +int lighting_menu_write(const char *name, const char *value) +{ + const struct lighting_menu_group *group = lighting_menu_group(name); + int i; + if (!group) + return -1; + if (strcmp(value, "true") && strcmp(value, "false")) + return 0; + for (i = 0; group->members[i]; i++) + if (!config_write(group->members[i], value)) + return 0; + return 1; +} diff --git a/port/linux/game/lighting_menu.h b/port/linux/game/lighting_menu.h new file mode 100644 index 0000000000..da16fcbf20 --- /dev/null +++ b/port/linux/game/lighting_menu.h @@ -0,0 +1,9 @@ +#ifndef LIGHTING_MENU_H +#define LIGHTING_MENU_H + +/* Group controls stage ON/OFF normally in the menu; no legacy CUSTOM state. + Return -1 for an unrelated setting, otherwise the operation's success. */ +int lighting_menu_text(const char *name, char *text, unsigned int size, int defaults); +int lighting_menu_write(const char *name, const char *value); + +#endif diff --git a/port/linux/game/material_prepare.c b/port/linux/game/material_prepare.c new file mode 100644 index 0000000000..1e42cb9b6a --- /dev/null +++ b/port/linux/game/material_prepare.c @@ -0,0 +1,221 @@ +/* Ask the existing model renderer for material variants during loading. + * Descriptors supply sampler types without loading pixels or spending the + * independent texture preparation budget. All state is local to this pass. */ +#include "cseries.h" +#include "cseries/errors.h" +#include "bitmaps/bitmap_group.h" +#include "cache/cache_files.h" +#include "math/real_math.h" +#include "rasterizer/rasterizer.h" +#include "rasterizer/rasterizer_console_vars.h" +#include "rasterizer/rasterizer_geometry.h" +#include "rasterizer/rasterizer_models.h" +#include "rasterizer/rasterizer_model_types.h" +#include "rasterizer/rasterizer_transparent_geometry.h" +#include "shaders/shader_definitions.h" +#include "material_prepare.h" +#include "../src/port_config.h" +#include +#include +#include + +#ifndef HALO_GLES +#define MATERIAL_PREPARE_LIMIT 512 +#define MATERIAL_BITMAP_LIMIT 4096 +#define MATERIAL_DRAW_LIMIT 8192 +static int preparing; +static unsigned prepared_draws; +static struct material_bitmap { + struct bitmap_data *bitmap; + D3DBaseTexture header; +} *bitmaps; +static unsigned bitmap_count; + +/* Native draw-packet layout from rasterizer_xbox_transparent_geometry.c. + * This standalone packet never enters the engine's sorted geometry queues. */ +struct transparent_geometry_group { + unsigned long geometry_flags; + long object_index,source_object_index; + struct shader *shader; + short shader_permutation_index,pad12,effect_type,pad16; + real effect_intensity; + byte reserved1C[0x20]; + real_vector2d model_base_map_scale; + long dynamic_triangle_buffer_index; + struct triangle_buffer const *triangle_buffer; + long first_triangle_index,triangle_count,dynamic_vertex_buffer_index; + struct vertex_buffer const *vertex_buffer; + struct bitmap_data const *lightmap; + void const *node_matrices; + short node_matrix_count; + word pad66; + struct render_lighting const *lighting; + struct render_animation const *animation; + real z_sort; + real_point3d centroid; + real_plane3d plane; + long sorted_index; + short previous_group_presorted_index,next_group_presorted_index; + long active_camouflage_transparent_source_object_index; + byte reserved9C; + boolean cortana_hack; + byte reserved9E[2]; +}; +typedef char material_packet_size[sizeof(struct transparent_geometry_group)==0xA0 ? 1 : -1]; +#endif + +int material_prepare_skip_shader(struct shader const *shader) +{ +#ifndef HALO_GLES + /* Extra layers can reference water, glass or effects requiring actual + * geometry/render targets. They retain their observed-recipe path. */ + return preparing && (!shader || (shader->base.type!=5 && shader->base.type!=6)); +#else + (void)shader; + return 0; +#endif +} + +int material_prepare_bitmap(struct bitmap_data *bitmap, void **header) +{ +#ifndef HALO_GLES + unsigned index; + if (!preparing) return 0; + *header=NULL; + if (!bitmap) return 1; + for (index=0;indexbase.type<3 || shader->base.type>6) continue; + count++; + variants=shader->base.type<=4 ? 24 : 18; + for (variant=0;variantbase.type<=4 ? types[2+choice/4] : types[choice]; + parameters.skinning.node_matrix_count=shader->base.type<=4 && (choice&1) ? 2 : 1; + /* NONE is an accepted empty light slot. The count selects the + * point-light program without borrowing or changing scene lights. */ + parameters.lighting.point_light_count=shader->base.type<=4 && (choice&2) ? 1 : 0; + parameters.geometry_flags=fog ? 0 : (1UL<<2); + global_window_parameters.fog.atmospheric_maximum_density=fog ? 1.0f : 0.0f; + global_window_parameters.fog.planar_mode=fog==2; + if (shader->base.type<=4) { + rasterizer_models_begin(FALSE); + rasterizer_model_begin(¶meters,FALSE); + rasterizer_model_draw(shader,0,NULL,NONE,0,&vertices,NONE); + rasterizer_model_end(); + rasterizer_models_end(); + } else { + transparent.shader=shader; + transparent.geometry_flags=parameters.geometry_flags; + rasterizer_transparent_geometry_group_draw(&transparent,TRUE); + } + } + } + preparing=0; + render_material_prepare_mode(0); + global_window_parameters=saved_window; + rasterizer_frame_statistics=saved_statistics; + rasterizer_debug_options.statistics_mode=saved_mode; + free(bitmaps);bitmaps=NULL;bitmap_count=0; + error(_error_silent,"shader preparation: selected %u materials in %u draw variants",count,prepared_draws); + prepared_draws=0; +#endif +} diff --git a/port/linux/game/material_prepare.h b/port/linux/game/material_prepare.h new file mode 100644 index 0000000000..6852cbce50 --- /dev/null +++ b/port/linux/game/material_prepare.h @@ -0,0 +1,13 @@ +/* Loading-only material selection; no geometry or texture pixels are drawn. */ +#ifndef MATERIAL_PREPARE_H +#define MATERIAL_PREPARE_H +struct bitmap_data; +struct shader; +void material_prepare_map(void); +int material_prepare_draw(void); +int material_prepare_skip_shader(struct shader const *shader); +int material_prepare_bitmap(struct bitmap_data *bitmap, void **header); +int render_material_prepare_mode(int enabled); +void render_material_prepare_draw(void); +int texture_cache_prepare_descriptor(struct bitmap_data *bitmap, void *header); +#endif diff --git a/port/linux/game/mcc_xbox_menu.inl b/port/linux/game/mcc_xbox_menu.inl new file mode 100644 index 0000000000..13054f95a1 --- /dev/null +++ b/port/linux/game/mcc_xbox_menu.inl @@ -0,0 +1,247 @@ +/* Included beside the menu instance helpers. Only the dedicated MCC browser + * owns this state; native Xbox/CE lists and their generated indices stay intact. */ +#define MCC_XBOX_ROOT "pc\\mcc_xbox\\" +#define MCC_XBOX_NATIVE "ui\\shell\\main_menu\\multiplayer_type_select\\" +#include "mcc_progress.h" + +static struct mcc_map_browser mcc_xbox_browser; +static boolean mcc_xbox_difficulty; +static short mcc_xbox_slot; +static long mcc_xbox_profile; + +static void mcc_xbox_reset(void) +{ + memset(&mcc_xbox_browser, 0, sizeof(mcc_xbox_browser)); + mcc_xbox_difficulty = FALSE; + mcc_xbox_slot = 0; + mcc_xbox_profile = NONE; +} + +static char const *mcc_xbox_route(char const *name) +{ + if (!strcmp(name, FRONTEND_MENU_XBOX)) + return config_boolean("game.mcc_campaigns") ? "campaign" : NULL; + if (!strcmp(name, MCC_XBOX_NATIVE "connected\\connected_map_select_wrapper")) return "connected"; + if (!strcmp(name, MCC_XBOX_NATIVE "split_screen\\splitscreen_map_select_wrapper")) return "split"; + if (!strcmp(name, MCC_XBOX_NATIVE "connected\\connected_map_select_postgame_wrapper")) return "connected_postgame"; + if (!strcmp(name, MCC_XBOX_NATIVE "split_screen\\splitscreen_map_select_postgame_wrapper")) return "split_postgame"; + return NULL; +} + +static boolean mcc_xbox_available(void) +{ + return frontend_menu_available() && main_menu_is_active() && !strcmp(frontend_menu_style(), "xbox"); +} + +static void mcc_xbox_attach(struct widget_instance *widget) +{ + struct widget_instance *entry, *last, *list, *before, *row; + char const *route; + if (!widget || widget->parent || !mcc_xbox_available()) return; + route = mcc_xbox_route(tag_get_name(widget->definition_tag_index)); + if (!route) return; + if (!strcmp(route, "campaign")) + { + list = named(widget, "main_menu_select_list", 0); + before = named(list, "multiplayer_item", 0); + if (!list || !before || named(list, "campaign_entry", 0)) return; + entry = ui_widget_load_by_name_or_tag(MCC_XBOX_ROOT "campaign_entry", + NONE, list, widget->local_player_index, NONE, NONE, NONE); + if (!entry) return; + /* Insert only a live MCC row. Native definitions and actions remain + * intact; subsequent rows retain the main menu's 36-pixel spacing. */ + entry->horizontal_offset = before->horizontal_offset; + entry->vertical_offset = before->vertical_offset; + entry->previous = before->previous; + entry->next = before; + if (before->previous) before->previous->next = entry; + else list->child = entry; + before->previous = entry; + for (row = before; row; row = row->next) row->vertical_offset += 36; + return; + } + entry = ui_widget_load_by_name_or_tag(MCC_XBOX_ROOT "multiplayer_entry", + NONE, widget, widget->local_player_index, NONE, NONE, NONE); + if (!entry) return; + last = widget->child; + while (last && last->next) last = last->next; + entry->previous = last; + if (last) last->next = entry; + else widget->child = entry; +} + +static boolean mcc_xbox_open(struct widget_instance *widget, boolean *deleted) +{ + struct widget_instance *root = screen_of(widget); + char const *route; + char path[64]; + if (!mcc_xbox_available()) return FALSE; + route = mcc_xbox_route(tag_get_name(root->definition_tag_index)); + if (!route) return FALSE; + snprintf(path, sizeof(path), MCC_XBOX_ROOT "%s", !strcmp(route, "campaign") ? "profiles" : route); + return ui_widget_port_open(widget, path, deleted); +} + +static boolean mcc_xbox_shortcut(struct widget_instance *widget, struct event_record *event) +{ + boolean deleted = FALSE; + if (!widget || widget->parent || event->type != 3 || event->data.button.index != BUTTON_X || + event->data.button.value != 1) return FALSE; + if (!strcmp(tag_get_name(widget->definition_tag_index), FRONTEND_MENU_XBOX)) return FALSE; + return mcc_xbox_open(widget, &deleted); +} + +static void mcc_xbox_show(struct widget_instance *root) +{ + struct widget_instance *card, *picture, *badge, *difficulty = named(root, "difficulty_list", 0); + short slot, row, index, marker, first = mcc_xbox_browser.chosen - mcc_xbox_slot; + unsigned completed; + wchar_t text[128]; + char name[32]; + visible_set(named(root, "heading_campaigns", 0), !mcc_xbox_difficulty && mcc_xbox_browser.campaign && !mcc_xbox_browser.package[0]); + visible_set(named(root, "heading_levels", 0), !mcc_xbox_difficulty && mcc_xbox_browser.campaign && mcc_xbox_browser.package[0]); + visible_set(named(root, "heading_maps", 0), !mcc_xbox_difficulty && !mcc_xbox_browser.campaign); + visible_set(named(root, "heading_difficulty", 0), mcc_xbox_difficulty); + visible_set(named(root, "previous", 0), !mcc_xbox_difficulty && mcc_xbox_browser.count > 1); + visible_set(named(root, "next", 0), !mcc_xbox_difficulty && mcc_xbox_browser.count > 1); + visible_set(difficulty, mcc_xbox_difficulty); + root->focused_child = mcc_xbox_difficulty ? difficulty : NULL; + for (slot = 0; slot < 3; slot++) + { + snprintf(name, sizeof(name), "card_%d", slot); + card = named(root, name, 0); + if (!card) continue; + row = first + slot; + card->visible = row < mcc_xbox_browser.count && !mcc_xbox_difficulty; + if (!card->visible) continue; + card->animation.current_frame_index = row == mcc_xbox_browser.chosen ? 1 : 0; + index = mcc_map_browser_index(&mcc_xbox_browser, row); + picture = named(card, "picture", 0); + if (picture) picture->animation.current_frame_index = index == NONE ? 13 : MCC_MAPS_FIRST_DISPLAY_INDEX + index; + mcc_map_browser_text(&mcc_xbox_browser, row, text); + text_set(named(card, "mcc_folder_name", 0), text); + text_set_length(named(card, "mcc_folder_help", 0), + index == NONE ? (mcc_xbox_browser.campaign ? L"Open folder to choose a mission." : + L"Open folder to choose a map.") : mcc_maps_description(index), 128); + completed = index == NONE || !mcc_xbox_browser.campaign ? 0 : + mcc_progress_flags(mcc_xbox_profile, mcc_maps_level_name(index)); + for (marker = 0; marker < 3; marker++) + { + snprintf(name, sizeof(name), "badge_%d", marker); + badge = named(card, name, 0); + if (badge) + { + badge->visible = (completed & (1u << (marker + 1))) != 0; + badge->animation.current_frame_index = marker + 1; + } + } + } + if (!mcc_xbox_browser.count) + text_set_length(named(root, "status", 0), L"No MCC maps found. Check MCC Packages in Settings.", 128); + else if (mcc_xbox_difficulty) + text_set_length(named(root, "status", 0), L"", 128); + else + { + usnprintf(text, NUMBEROF(text), L"%d / %d", mcc_xbox_browser.chosen + 1, mcc_xbox_browser.count); + text_set_length(named(root, "status", 0), text, 128); + } +} + +static boolean mcc_xbox_event(char const *action, struct widget_instance *widget, + struct event_record *event, boolean *deleted) +{ + struct widget_instance *root = screen_of(widget); + char const *name = tag_get_name(root->definition_tag_index), *route, *level, *destination; + short row, index; + struct player_profile profile; + if (!strcmp(action, "open")) return mcc_xbox_open(widget, deleted); + if (!mcc_xbox_available() || strncmp(name, MCC_XBOX_ROOT, sizeof(MCC_XBOX_ROOT) - 1)) return FALSE; + route = name + sizeof(MCC_XBOX_ROOT) - 1; + if (!strcmp(action, "profile")) + { + if (strcmp(route, "profiles") || !game_function("sp set p1 controller choice", root, event, deleted) || + !game_function("3wide plyr prof set for game", root, event, deleted)) return FALSE; + return ui_widget_port_open(root, MCC_XBOX_ROOT "campaign", deleted); + } + if (!strcmp(action, "init")) + { + mcc_maps_rescan(); + mcc_xbox_reset(); + mcc_map_browser_open(&mcc_xbox_browser, !strcmp(route, "campaign")); + mcc_xbox_profile = player_ui_get_active_player_profile_index(0); + } + else if (!strcmp(action, "back")) + { + if (mcc_xbox_difficulty) mcc_xbox_difficulty = FALSE; + else if (!mcc_map_browser_back(&mcc_xbox_browser)) + { + ui_widget_port_go_back(root); + *deleted = TRUE; + return TRUE; + } + ui_play_audio_feedback_sound(SOUND_BACK); + mcc_xbox_slot = (short)MIN(mcc_xbox_browser.chosen, 2); + } + else if (!strcmp(action, "left") || !strcmp(action, "right")) + { + short direction = !strcmp(action, "left") ? -1 : 1; + if (!mcc_xbox_difficulty && mcc_xbox_browser.count) + { + row = mcc_xbox_browser.chosen + direction; + if (row < 0) { row = mcc_xbox_browser.count - 1; mcc_xbox_slot = (short)MIN(row, 2); } + else if (row >= mcc_xbox_browser.count) { row = 0; mcc_xbox_slot = 0; } + else mcc_xbox_slot = (short)PIN(mcc_xbox_slot + direction, 0, 2); + mcc_map_browser_select(&mcc_xbox_browser, row); + } + } + else if (!strcmp(action, "choose") || !strcmp(action, "card")) + { + if (!strcmp(action, "card") && !mcc_xbox_difficulty) + { + name = tag_get_name(widget->definition_tag_index); + index = (short)(name[strlen(name) - 1] - '0'); + if (index < 0 || index > 2) return FALSE; + row = mcc_xbox_browser.chosen - mcc_xbox_slot + index; + if (row < 0 || row >= mcc_xbox_browser.count) return FALSE; + mcc_map_browser_select(&mcc_xbox_browser, row); + mcc_xbox_slot = index; + } + if (!mcc_xbox_difficulty && mcc_map_browser_enter(&mcc_xbox_browser, mcc_xbox_browser.chosen)) + { + mcc_xbox_slot = 0; + ui_play_audio_feedback_sound(SOUND_FORWARD); + } + else + { + index = mcc_map_browser_index(&mcc_xbox_browser, mcc_xbox_browser.chosen); + level = mcc_maps_level_name(index); + if (!level) return campaign_fail(); + if (mcc_xbox_browser.campaign) + { + if (!mcc_xbox_difficulty) mcc_xbox_difficulty = TRUE; + else + { + if (mcc_xbox_profile == NONE || player_ui_get_active_player_profile_index(0) != mcc_xbox_profile || + !player_profile_get(mcc_xbox_profile, &profile)) + { + text_set_length(named(root, "status", 0), L"Create a player profile in Campaign before starting a mission.", 128); + return campaign_fail(); + } + row = ui_widget_port_list_index(named(root, "difficulty_list", 0)); + if (row < 0 || row >= NUMBER_OF_GAME_DIFFICULTY_LEVELS) return campaign_fail(); + campaign_start(level, row, event->controller_index); + return TRUE; + } + } + else + { + if (!ui_widget_port_mcc_multiplayer_map_choose(level)) return campaign_fail(); + destination = !strncmp(route, "connected", 9) ? MCC_XBOX_NATIVE "connected\\gametype_select_screen_wrapper" : + MCC_XBOX_NATIVE "split_screen\\gametype_select_screen_wrapper"; + return ui_widget_port_open(root, destination, deleted); + } + } + } + mcc_xbox_show(root); + return TRUE; +} diff --git a/port/linux/game/menu_button_glyphs.c b/port/linux/game/menu_button_glyphs.c index dd7ea5eb17..b3d9b38179 100644 --- a/port/linux/game/menu_button_glyphs.c +++ b/port/linux/game/menu_button_glyphs.c @@ -20,6 +20,7 @@ struct bitmap_data *hud_hires_button_bitmap(short style, short slot); static boolean menu_button_glyph_enabled(short button, short port) { return button >= 0 && button < 4 && port >= 0 && port < 4 && + config_boolean("display.high_res_hud") && config_boolean("display.menu_button_glyphs") && !strcmp(config_string("display.menus"), "pc"); } diff --git a/port/linux/game/menu_button_widgets.inl b/port/linux/game/menu_button_widgets.inl new file mode 100644 index 0000000000..ee52175479 --- /dev/null +++ b/port/linux/game/menu_button_widgets.inl @@ -0,0 +1,110 @@ +/* Included by menu_functions.c: PC glyph layout uses its existing controller + * context without changing the widget definitions or input routing. */ +/* Only the PC join screen reuses this Xbox-authored label in a wider panel. + * Supply its parent's horizontal bounds; the feature owns mixed-run layout. */ +void pc_menu_widget_text_bounds(long tag, rectangle2d *bounds, short *text_offset); + +/* The compact pause footer has room after SELECT, but little before CANCEL. + * Recover its spare gap and balance the added width around its center. Full-size + * legends instead have spare space on their left. Shift the whole widget so + * its text and mouse target follow the keycap. */ +short menu_functions_glyph_offset(struct widget_instance *widget) +{ + struct widget_instance *sibling; + char const *name, *leaf; + rectangle2d bounds; + short text_offset, extra = 0, balance = 0, width, button, accept_x = 0, label_end = 0, gap = 0; + boolean compact; + if (!widget->parent || !menu_button_glyph_keyboard_active(controller_of(widget))) return 0; + if (menu_button_glyph_key_width(0) <= 0) return 0; + if (mcc_pause_owns(widget->parent->definition_tag_index)) + return mcc_pause_key_offset(widget->parent->definition_tag_index, + widget->definition_tag_index, menu_button_glyph_compact_key_width(0), menu_button_glyph_compact_key_width(1)); + name = tag_get_name(widget->parent->definition_tag_index); + leaf = name ? strrchr(name, '\\') : NULL; + if (!leaf || (strcmp(leaf, "\\button_key") && strcmp(leaf, "\\button_key_options") && + strcmp(leaf, "\\mp_button_key") && strcmp(leaf, "\\button_key_sm") && + strcmp(leaf, "\\confirm_buttons"))) return 0; + compact = !strcmp(leaf, "\\button_key_sm"); + /* Confirmation legends use confirm_buttons while containing the same + * small face-button slots as the pause footer. Match their authored slots. */ + for (sibling = widget->parent->child; sibling; sibling = sibling->next) + { + name = tag_get_name(sibling->definition_tag_index); + leaf = name ? strrchr(name, '\\') : NULL; + if (leaf && !strcmp(leaf, "\\a_butn_sm")) compact = TRUE; + } + if (compact) + { + /* These groups have varying authored gaps. Recover spare + * space or add missing space, keeping eight units after CANCEL. */ + for (sibling = widget->parent->child; sibling; sibling = sibling->next) + { + name = tag_get_name(sibling->definition_tag_index); + leaf = name ? strrchr(name, '\\') : NULL; + if (leaf && !strcmp(leaf, "\\a_butn_sm")) accept_x = sibling->horizontal_offset; + } + for (sibling = widget->parent->child; sibling; sibling = sibling->next) + { + name = tag_get_name(sibling->definition_tag_index); + leaf = name ? strrchr(name, '\\') : NULL; + if (!leaf || leaf[1] != '=' || sibling->horizontal_offset >= accept_x) continue; + pc_menu_widget_text_bounds(sibling->definition_tag_index, &bounds, &text_offset); + label_end = MAX(label_end, sibling->horizontal_offset + bounds.x1); + } + if (label_end) gap = accept_x - label_end - 8; + } + for (sibling = widget->parent->child; sibling; sibling = sibling->next) + { + name = tag_get_name(sibling->definition_tag_index); + leaf = name ? strrchr(name, '\\') : NULL; + if (!leaf) continue; + button = (!strcmp(leaf, "\\a_butn") || !strcmp(leaf, "\\a_butn_sm")) ? 0 : + (!strcmp(leaf, "\\b_butn") || !strcmp(leaf, "\\b_butn_sm")) ? 1 : + (!strcmp(leaf, "\\x_butn") || !strcmp(leaf, "\\x_butn_sm")) ? 2 : + (!strcmp(leaf, "\\y_butn") || !strcmp(leaf, "\\y_butn_sm")) ? 3 : NONE; + if (button == NONE) continue; + width = compact ? menu_button_glyph_compact_key_width(button) : menu_button_glyph_key_width(button); + pc_menu_widget_text_bounds(sibling->definition_tag_index, &bounds, &text_offset); + width = MAX(0, width - (bounds.x1 - bounds.x0)); + /* Compact footers are B/CANCEL followed by A/SELECT (or A/OK). + * Balance the extra width on both ends around the authored center. */ + if (compact && button == 0) width -= gap; + if (compact) balance += button == 0 ? width : button == 1 ? -width : 0; + if (compact ? button != 0 || sibling->horizontal_offset > widget->horizontal_offset : + sibling->horizontal_offset <= widget->horizontal_offset) continue; + extra += width; + } + return compact ? extra - balance / 2 : -extra; +} + +/* MCC owns its generated key items. Only keyboard mode asks it for their + * identities; native controller drawing and the Xbox menu choice stay intact. */ +short menu_functions_glyph_button(struct widget_instance *widget, short native) +{ + if (native == NONE && widget->parent && + menu_button_glyph_keyboard_active(controller_of(widget))) + return mcc_pause_key_button(widget->parent->definition_tag_index, widget->definition_tag_index); + return native; +} + +boolean menu_functions_glyph_text(struct widget_instance *widget, rectangle2d const *bounds) +{ + rectangle2d definition, parent; + short text_offset, ignored; + rectangle2d panel = *bounds; + char const *name, *parent_name; + if (!widget->parent) return FALSE; + name = tag_get_name(widget->definition_tag_index); + parent_name = tag_get_name(widget->parent->definition_tag_index); + if (!name || !parent_name || + !strstr(name, "\\press_start_to_join") || + !strstr(parent_name, "\\lobby\\join4_qtr_join")) return FALSE; + pc_menu_widget_text_bounds(widget->definition_tag_index, &definition, &text_offset); + pc_menu_widget_text_bounds(widget->parent->definition_tag_index, &parent, &ignored); + panel.x0 = bounds->x0 - definition.x0 - text_offset - + widget->horizontal_offset + parent.x0; + panel.x1 = panel.x0 + parent.x1 - parent.x0; + return menu_button_glyph_join_draw(widget->parameters.text_box.text, controller_of(widget), &panel); +} + diff --git a/port/linux/game/menu_functions.c b/port/linux/game/menu_functions.c index 11c2349fd2..a992c901fd 100644 --- a/port/linux/game/menu_functions.c +++ b/port/linux/game/menu_functions.c @@ -70,6 +70,9 @@ their handlers open opens. */ #include "cseries.h" +#include "third_person.h" +#include "lighting_menu.h" +#include "third_person_protocol.h" #include "cseries/errors.h" #include "input/input.h" @@ -80,6 +83,7 @@ their handlers open opens. #include "main/main.h" #include "networking/network_game_manager.h" #include "saved games/player_profile.h" +#include "saved games/game_state.h" #include "tag_files/tag_groups.h" #include "text/text_group.h" #include "text/unicode.h" @@ -355,6 +359,8 @@ or the profile's */ static boolean setting_text(char const *name, char *text, unsigned int size, boolean default_value) { short index; + int grouped = lighting_menu_text(name, text, size, default_value); + if (grouped >= 0) return grouped; /* (DISCORD ACCOUNT's LINK: no change, until one is chosen; the master a server that refused this machine for its VPN is listed by, chosen @@ -424,7 +430,11 @@ static boolean setting_text(char const *name, char *text, unsigned int size, boo static boolean setting_write(char const *name, char const *value) { short index; + int grouped = lighting_menu_write(name, value); + if (grouped >= 0) return grouped; + if (!strcmp(name, "display.third_person") && third_person_policy() != _third_person_player_choice) + return TRUE; /* (DISCORD ACCOUNT's LINK: done, not written: the master's page opened in the browser, or the account forgotten, player_link.c) */ if (!strcmp(name, "link.action")) @@ -479,15 +489,20 @@ static boolean setting_load(struct widget_instance *widget) static boolean setting_save(struct widget_instance *widget) { struct pc_menu_setting *setting = pc_menu_setting_get(widget->definition_tag_index); + int written; if (spinner_item(widget)) return TRUE; if (!setting || setting->loaded_index == NONE || widget->parameters.list.selected_index < 0 || widget->parameters.list.selected_index >= setting->value_count) return FALSE; + if (!strcmp(setting->setting, "display.third_person") && third_person_policy() != _third_person_player_choice) + return TRUE; if (widget->parameters.list.selected_index == setting->loaded_index) return TRUE; - if (!config_write(setting->setting, setting->values[widget->parameters.list.selected_index])) + written = lighting_menu_write(setting->setting, setting->values[widget->parameters.list.selected_index]); + if (written < 0) written = config_write(setting->setting, setting->values[widget->parameters.list.selected_index]); + if (!written) { platform_log("menus: could not write %s to config.toml", setting->setting); return FALSE; @@ -730,6 +745,9 @@ static void text_set(struct widget_instance *text_box, wchar_t const *text) text_set_length(text_box, text, ROW_TEXT_LENGTH); } +#include "changelog_menu_runtime.inl" +#include "gulch_build_label.inl" + /* one of our string lists' strings, on one line (its line breaks spaces), of up to size characters */ static void words_get(char const *list, short index, wchar_t *text, short size) @@ -1145,7 +1163,7 @@ static short map_kind_rows_update(struct widget_instance *list, short *first, sh text_set(named(child, "list_item_text", 0), text); } visible_set(named(child, "list_item_arrows", 0), - child == list->focused_child && strcmp(list->name, "select_screen_list_template")); + child == list->focused_child && strcmp(list->name, "select_screen_list_template")); visible_set(named(child, "scroll_up_button", 0), FALSE); visible_set(named(child, "scroll_down_button", 0), FALSE); } @@ -1783,10 +1801,17 @@ static struct widget_instance *screen_of(struct widget_instance *widget) } /* "port settings save" (OK): those changed written, and applied */ +boolean network_game_is_active(void); + static boolean setting_changed_save(struct widget_instance *spinner, struct pc_menu_setting *setting) { short index = spinner->parameters.list.selected_index; + /* A locked display value is never a change to the personal preference, + even if the host unlocks the lobby just before this menu closes. */ + if (!strcmp(setting->setting, "display.third_person") && + (third_person_policy() != _third_person_player_choice || setting->loaded_index == NONE)) + return TRUE; if (index < 0 || index >= setting->value_count || index == setting->loaded_index) return TRUE; if (!setting_write(setting->setting, setting->values[index])) @@ -1796,6 +1821,8 @@ static boolean setting_changed_save(struct widget_instance *spinner, struct pc_m } platform_log("menus: %s = %s", setting->setting, setting->values[index]); setting->loaded_index = index; + if (!strcmp(setting->setting, "display.menu_frontend") && main_menu_is_active() && + !network_game_is_active()) main_goto_main_menu(); return TRUE; } @@ -1809,14 +1836,45 @@ static boolean setting_default_show(struct widget_instance *spinner, struct pc_m return TRUE; } +#include "frontend_menu_runtime.inl" +#include "frontend_prompts.h" + +static boolean camera_setting_show(struct widget_instance *spinner, struct pc_menu_setting *setting) +{ + if (!strcmp(setting->setting, "display.third_person")) + { + if (third_person_policy() != _third_person_player_choice) + { + spinner->parameters.list.selected_index = setting_value_index(setting, third_person_enabled() ? "true" : "false"); + setting->loaded_index = NONE; + } + else if (setting->loaded_index == NONE) + { + setting->loaded_index = setting_value_index(setting, config_boolean("display.third_person") ? "true" : "false"); + spinner->parameters.list.selected_index = setting->loaded_index; + } + } + return TRUE; +} + /* "port settings help": the line of the row chosen (by its label's string: the buttons' is the first) */ static void settings_help(struct widget_instance *list) { struct widget_instance *help = list->parameters.list.extended_description; struct widget_instance *row = list->focused_child; + struct widget_instance *child; short index = 0; + /* Pointer focus clears the old descendant chain. Returning to a generated + setting row with the d-pad must reconnect its spinner to receive input. */ + if (row && !row->focused_child) + for (child = row->child; child; child = child->next) + if (child->type == 2 && pc_menu_setting_get(child->definition_tag_index)) + { + row->focused_child = child; + break; + } if (!help) return; if (row && row->child && row->child->type == 1 && strncmp(row->name, "button", 6)) @@ -2012,6 +2070,7 @@ The remaining options close the gap; the help and bottom buttons stay put. */ #include "controller_buttons.h" #include "keyboard_prompts.h" #include "menu_button_glyphs.h" +#include "frontend_input.h" #include "controller_button_menu.inl" static void hud_button_style_row_show(struct widget_instance *list) @@ -3756,9 +3815,15 @@ static struct { "controls.scoreboard", L"SHOW SCORES", 2 }, { "controls.pause", L"PAUSE MENU", 2 }, { "controls.screenshot", L"SCREENSHOT", 2 }, + { "controls.swap_shoulder", L"SWAP SHOULDER", 4 }, + { "controls.free_look", L"HOLD FREE LOOK", 4 }, + { "controls.toggle_perspective", L"TOGGLE PERSPECTIVE", 4 }, { "controls.push_to_talk", L"PUSH TO TALK", 3 }, { "controls.chat", L"CHAT", 3 }, { "controls.team_chat", L"TEAM CHAT", 3 }, + { "controls.camera_distance", L"CAMERA DISTANCE", 4 }, + { "controls.camera_height", L"CAMERA HEIGHT", 4 }, + { "controls.camera_offset", L"CAMERA OFFSET", 4 }, { "controls.vote_yes", L"VOTE YES", 3 }, { "controls.vote_no", L"VOTE NO", 3 }, }; @@ -4610,11 +4675,13 @@ boolean ui_widget_port_multiplayer_player(short controller_index, long profile_i boolean ui_widget_port_unjoin_player(struct widget_instance *widget, struct event_record *event, boolean *widget_deleted); void network_game_server_port_set_settings(wchar_t const *name, long maximum_players); +void network_game_server_port_set_camera_policy(short policy); void network_game_server_port_set_cooperative_friendly_fire(short friendly_fire); void network_game_server_port_set_cooperative_player_collisions(boolean player_collisions); void network_game_server_port_set_cooperative_ally_friendly_fire(boolean ally_friendly_fire); void *global_network_game_client_get(void); void *global_network_game_server_get(void); +#include "bots_menu.inl" boolean network_game_is_splitscreen_local(void); struct advertised_game *network_game_client_get_available_games(void *client); boolean network_game_client_advertised_game_is_valid(struct advertised_game *game); @@ -4950,6 +5017,7 @@ static void mcc_host_list_update(struct widget_instance *list) else mcc_browser_description(description, browser); profile_name_show(description); + frontend_multiplayer_difficulty(list, mcc_host_list.step == MAP_STEP_DIFFICULTIES ? mcc_host_list.chosen : NONE); } static boolean mcc_host_list_choose(struct widget_instance *list, boolean *widget_deleted) @@ -5135,6 +5203,7 @@ static void map_list_update(struct widget_instance *list) NONE); } profile_name_show(description); + frontend_multiplayer_difficulty(list, map_list.step == MAP_STEP_DIFFICULTIES ? map_list.chosen : NONE); } /* "mp level select" (the list's OK): the map chosen, or a level's @@ -5473,9 +5542,9 @@ tools/port_settings.py) */ #define COOPERATIVE_OPTIONS_HELP 12 #define COOPERATIVE_VOICE_OPTIONS_HELP 13 #define SERVER_PASSWORD_HELP 14 -#define MAP_SHARE_OPTIONS_HELP 15 +#define MAP_SHARE_OPTIONS_HELP 18 /* (LISTING's PUBLIC on a machine with a publisher key: server_master.c) */ -#define SERVER_LISTING_PUBLISHER_HELP 16 +#define SERVER_LISTING_PUBLISHER_HELP 19 /* whether this machine has a publisher key (read as Server Setup opens) */ static boolean server_settings_publisher; @@ -5544,10 +5613,70 @@ static void setting_options_each(struct widget_instance *list, boolean save); /* "server settings init": the game's name (player 1's, else the one given last), the most players, the gametype's copy (once: the screen is made again on coming back from an option's screen) */ +/* This submenu edits the host-owned session without reinitializing the +main setup's gametype copy, listing or other pending edits. */ +static boolean session_options_initialize(struct widget_instance *list) +{ + struct widget_instance *spinner = named(list, "session_compatibility_spinner", 0); + if (!spinner) return FALSE; + spinner->parameters.list.selected_index = third_person_session_active(); + spinner = named(list, "camera_policy_spinner", 0); + if (spinner) spinner->parameters.list.selected_index = third_person_session_active() ? third_person_policy() : third_person_host_policy(); + return TRUE; +} + +static boolean session_options_update(struct widget_instance *list) +{ + static char const *const policies[] = { "player_choice", "forced_on", "forced_off" }; + struct widget_instance *spinner = named(list, "session_compatibility_spinner", 0); + struct widget_instance *help = list->parameters.list.extended_description; + char text[TEXT_FIELD_LENGTH]; + short selected; + if (!spinner) return FALSE; + selected = spinner->parameters.list.selected_index != 0; + if (selected != third_person_session_active()) + { + third_person_session_set(selected); + session_options_initialize(list); + } + if (help) help->parameters.text_box.string_list_index = third_person_session_locked() ? 2 : third_person_session_active(); + visible_set(named(list, "op_camera_policy", 0), third_person_session_active()); + if (third_person_session_active() && (spinner = named(list, "camera_policy_spinner", 0)) != NULL) + { + selected = (short)PIN(spinner->parameters.list.selected_index, 0, 2); + if (selected != third_person_policy()) + { + network_game_server_port_set_camera_policy(selected); + if (selected == third_person_policy()) config_write("network.camera_policy", policies[selected]); + } + spinner->parameters.list.selected_index = third_person_policy(); + if (help && list->focused_child == named(list, "op_camera_policy", 0)) + help->parameters.text_box.string_list_index = 3 + third_person_policy(); + } + if (multiplayer.mode != _multiplayer_mode_host_internet) + snprintf(text, sizeof(text), "NONE: A LAN GAME"); + else if (!config_boolean("network.online")) + snprintf(text, sizeof(text), "INTERNET PLAY IS OFF (SETTINGS)"); + else if (!p2p_invite_link(text, sizeof(text))) + snprintf(text, sizeof(text), "MADE WHEN THE GAME STARTS"); + else + /* The 64-digit invite does not fit a menu value. The action copies + the complete link; show its purpose rather than a clipped address. */ + snprintf(text, sizeof(text), "SELECT TO COPY LINK"); + text_field_show(named(list, "invite_value", 0), text, FALSE); + if ((spinner = named(list, "op_invite", 0)) != NULL) + { + spinner->vertical_offset = third_person_session_active() ? 133 : 103; + if (help && list->focused_child == spinner) help->parameters.text_box.string_list_index = 6; + } + return TRUE; +} + static boolean server_settings_initialize(struct widget_instance *list) { struct widget_instance *spinner = named(list, "max_players_spinner", 0); + if (session_options_initialize(list)) return TRUE; /* (co-op has no gametype to edit) */ if (!hosting_cooperative()) gametype_setup_begin(); @@ -5590,18 +5719,12 @@ static void server_settings_update(struct widget_instance *list) struct widget_instance *row = named(list, "op_server_name", 0); char text[TEXT_FIELD_LENGTH]; + if (session_options_update(list)) return; if (spinner) *server_settings_maximum_players_index() = (short)PIN(spinner->parameters.list.selected_index, 0, NUMBEROF(maximum_players) - 1); wide_to_text(multiplayer.game_name, text, sizeof(text)); text_field_show(named(list, "server_name_value", 0), text, text_field_editing(row)); - if (multiplayer.mode != _multiplayer_mode_host_internet) - snprintf(text, sizeof(text), "NONE: A LAN GAME"); - else if (!config_boolean("network.online")) - snprintf(text, sizeof(text), "INTERNET PLAY IS OFF (SETTINGS)"); - else if (!p2p_invite_link(text, sizeof(text))) - snprintf(text, sizeof(text), "MADE WHEN THE GAME STARTS"); - text_field_show(named(list, "invite_value", 0), text, FALSE); { wchar_t type[ROW_TEXT_LENGTH]; @@ -5609,6 +5732,8 @@ static void server_settings_update(struct widget_instance *list) text_set(named(list, "game_type_value", 0), type); } settings_help(list); + if (list->parameters.list.extended_description && list->focused_child == named(list, "op_session_options", 0)) + list->parameters.list.extended_description->parameters.text_box.string_list_index = 15; { boolean cooperative = hosting_cooperative(); short row; @@ -5741,6 +5866,9 @@ void ui_widget_port_cooperative_settings_apply(void) static boolean server_start(void) { + static char const *const camera_policies[] = { "player_choice", "forced_on", "forced_off" }; + if (third_person_session_active()) + config_write("network.camera_policy", camera_policies[third_person_policy()]); if (text_field_editing(NULL)) text_field_end(TRUE); network_game_server_port_set_settings(multiplayer.game_name, @@ -7652,6 +7780,7 @@ extern void halo_virtual_gamepads_start(void); /* "port lobby open" (the lobby made, or come back to): no player being added */ static boolean lobby_join_reset(void) { + third_person_session_lock(); halo_virtual_gamepads_start(); lobby_join.adding = FALSE; lobby_join.controller = NONE; @@ -7867,122 +7996,18 @@ static struct unsigned long updated_at; } lobby_icons; +#include "menu_button_widgets.inl" + /* ui_widget.c's: a text box drawn, at the bounds its text was drawn in (its font and justification still set): a lobby row's player talking in voice chat (or muted) has a speaker just left of their name (port/linux/game/network_voice.c) */ -/* Only the PC join screen reuses this Xbox-authored label in a wider panel. - * Supply its parent's horizontal bounds; the feature owns mixed-run layout. */ -void pc_menu_widget_text_bounds(long tag, rectangle2d *bounds, short *text_offset); - -/* The compact pause footer has room after SELECT, but little before CANCEL. - * Recover its spare gap and balance the added width around its center. Full-size - * legends instead have spare space on their left. Shift the whole widget so - * its text and mouse target follow the keycap. */ -short menu_functions_glyph_offset(struct widget_instance *widget) -{ - struct widget_instance *sibling; - char const *name, *leaf; - rectangle2d bounds; - short text_offset, extra = 0, balance = 0, width, button, accept_x = 0, label_end = 0, gap = 0; - boolean compact; - if (!widget->parent || !menu_button_glyph_keyboard_active(controller_of(widget))) return 0; - if (menu_button_glyph_key_width(0) <= 0) return 0; - if (mcc_pause_owns(widget->parent->definition_tag_index)) - return mcc_pause_key_offset(widget->parent->definition_tag_index, - widget->definition_tag_index, menu_button_glyph_compact_key_width(0), menu_button_glyph_compact_key_width(1)); - name = tag_get_name(widget->parent->definition_tag_index); - leaf = name ? strrchr(name, '\\') : NULL; - if (!leaf || (strcmp(leaf, "\\button_key") && strcmp(leaf, "\\button_key_options") && - strcmp(leaf, "\\mp_button_key") && strcmp(leaf, "\\button_key_sm") && - strcmp(leaf, "\\confirm_buttons"))) return 0; - compact = !strcmp(leaf, "\\button_key_sm"); - /* Confirmation legends use confirm_buttons while containing the same - * small face-button slots as the pause footer. Match their authored slots. */ - for (sibling = widget->parent->child; sibling; sibling = sibling->next) - { - name = tag_get_name(sibling->definition_tag_index); - leaf = name ? strrchr(name, '\\') : NULL; - if (leaf && !strcmp(leaf, "\\a_butn_sm")) compact = TRUE; - } - if (compact) - { - /* These groups have varying authored gaps. Recover spare - * space or add missing space, keeping eight units after CANCEL. */ - for (sibling = widget->parent->child; sibling; sibling = sibling->next) - { - name = tag_get_name(sibling->definition_tag_index); - leaf = name ? strrchr(name, '\\') : NULL; - if (leaf && !strcmp(leaf, "\\a_butn_sm")) accept_x = sibling->horizontal_offset; - } - for (sibling = widget->parent->child; sibling; sibling = sibling->next) - { - name = tag_get_name(sibling->definition_tag_index); - leaf = name ? strrchr(name, '\\') : NULL; - if (!leaf || leaf[1] != '=' || sibling->horizontal_offset >= accept_x) continue; - pc_menu_widget_text_bounds(sibling->definition_tag_index, &bounds, &text_offset); - label_end = MAX(label_end, sibling->horizontal_offset + bounds.x1); - } - if (label_end) gap = accept_x - label_end - 8; - } - for (sibling = widget->parent->child; sibling; sibling = sibling->next) - { - name = tag_get_name(sibling->definition_tag_index); - leaf = name ? strrchr(name, '\\') : NULL; - if (!leaf) continue; - button = (!strcmp(leaf, "\\a_butn") || !strcmp(leaf, "\\a_butn_sm")) ? 0 : - (!strcmp(leaf, "\\b_butn") || !strcmp(leaf, "\\b_butn_sm")) ? 1 : - (!strcmp(leaf, "\\x_butn") || !strcmp(leaf, "\\x_butn_sm")) ? 2 : - (!strcmp(leaf, "\\y_butn") || !strcmp(leaf, "\\y_butn_sm")) ? 3 : NONE; - if (button == NONE) continue; - width = compact ? menu_button_glyph_compact_key_width(button) : menu_button_glyph_key_width(button); - pc_menu_widget_text_bounds(sibling->definition_tag_index, &bounds, &text_offset); - width = MAX(0, width - (bounds.x1 - bounds.x0)); - /* Compact footers are B/CANCEL followed by A/SELECT (or A/OK). - * Balance the extra width on both ends around the authored center. */ - if (compact && button == 0) width -= gap; - if (compact) balance += button == 0 ? width : button == 1 ? -width : 0; - if (compact ? button != 0 || sibling->horizontal_offset > widget->horizontal_offset : - sibling->horizontal_offset <= widget->horizontal_offset) continue; - extra += width; - } - return compact ? extra - balance / 2 : -extra; -} - -/* MCC owns its generated key items. Only keyboard mode asks it for their - * identities; native controller drawing and the Xbox menu choice stay intact. */ -short menu_functions_glyph_button(struct widget_instance *widget, short native) -{ - if (native == NONE && widget->parent && - menu_button_glyph_keyboard_active(controller_of(widget))) - return mcc_pause_key_button(widget->parent->definition_tag_index, widget->definition_tag_index); - return native; -} - -boolean menu_functions_glyph_text(struct widget_instance *widget, rectangle2d const *bounds) -{ - rectangle2d definition, parent; - short text_offset, ignored; - rectangle2d panel = *bounds; - char const *name, *parent_name; - if (!widget->parent) return FALSE; - name = tag_get_name(widget->definition_tag_index); - parent_name = tag_get_name(widget->parent->definition_tag_index); - if (!name || !parent_name || - !strstr(name, "\\press_start_to_join") || - !strstr(parent_name, "\\lobby\\join4_qtr_join")) return FALSE; - pc_menu_widget_text_bounds(widget->definition_tag_index, &definition, &text_offset); - pc_menu_widget_text_bounds(widget->parent->definition_tag_index, &parent, &ignored); - panel.x0 = bounds->x0 - definition.x0 - text_offset - - widget->horizontal_offset + parent.x0; - panel.x1 = panel.x0 + parent.x1 - parent.x0; - return menu_button_glyph_join_draw(widget->parameters.text_box.text, controller_of(widget), &panel); -} - void menu_functions_text_box_drawn(struct widget_instance *widget, rectangle2d const *bounds) { short row; + frontend_prompts_draw(widget->definition_tag_index, bounds); + /* (the Mods screen's texts: the fonts and widths their lines are measured in, mods_text_fits) */ for (row = 0; widget->name && row < NUMBER_OF_MOD_TEXT_BOXES; row++) @@ -9671,9 +9696,21 @@ boolean pc_menu_event_function_invoke( if (!name) return FALSE; + if (!strncmp(name, "port frontend ", 14)) + return frontend_menu_event(widget, name, widget_deleted); + if (!strncmp(name, "port bots ", 10)) + return bots_menu_event(widget, name); if (!strncmp(name, "port controller ", 16)) return pad_editor_event(widget, name); - if (!strcmp(name, "main menu quit game")) + if (!strncmp(name, "port changelog ", 15)) + { + return changelog_menu_event(widget, name); + } + else if (!strcmp(name, "port gulch build label")) + { + return gulch_build_label_event(widget); + } + else if (!strcmp(name, "main menu quit game")) { platform_request_quit(); } @@ -9846,6 +9883,10 @@ boolean pc_menu_event_function_invoke( { return map_list_back(widget, widget_deleted); } + else if (!strncmp(name, "port mcc xbox ", 14)) + { + return mcc_xbox_event(name + 14, widget, event, widget_deleted); + } else if (!strcmp(name, "port mcc host folder back")) { return mcc_host_back(widget, widget_deleted); @@ -10149,7 +10190,9 @@ void pc_menu_game_data_function_invoke( /* (a text field whose screen has gone: let go of) */ if (text_field.row && system_milliseconds() - text_field_shown_time > 500) text_field_end(FALSE); - if (!strcmp(name, "solo map list update")) + if (!strcmp(name, "port changelog focus update")) + changelog_menu_focus_update(widget); + else if (!strcmp(name, "solo map list update")) level_list_update(widget); else if (!strcmp(name, "mp map list update")) map_list_update(widget); @@ -10178,6 +10221,12 @@ void pc_menu_game_data_function_invoke( preview_update(widget); else if (!strcmp(name, "port lobby update")) lobby_update(widget); + else if (!strcmp(name, "port frontend update")) + frontend_menu_help(widget); + else if (!strcmp(name, "port frontend navigation update")) + frontend_navigation_update(widget); + else if (!strcmp(name, "port frontend multiplayer update")) + frontend_multiplayer_update(widget); else if (!strcmp(name, "port map vote update")) map_vote_update(widget); else if (!strcmp(name, "port join4 update")) @@ -10190,6 +10239,12 @@ void pc_menu_game_data_function_invoke( discord_account_show(widget); hdr_calibration_row_show(widget); settings_help(widget); + settings_each(widget, camera_setting_show); + if (third_person_policy() != _third_person_player_choice && + widget->parameters.list.extended_description && + widget->focused_child == named(widget, "op_third_person", 0)) + /* FOV And Viewmodels: eight rows, one category, then this help. */ + widget->parameters.list.extended_description->parameters.text_box.string_list_index = 10; } else if (!strcmp(name, "port hdr calibration")) hdr_calibration_update(widget); @@ -10254,7 +10309,7 @@ void pc_menu_map_list_update(struct widget_instance *widget) char const *const *names; map_list_update(widget); short last; - + { struct widget_instance *row_top = named(widget, "list_item_0", 0); struct widget_instance *row_end = named(widget, "list_item_10", 0); @@ -10382,4 +10437,4 @@ boolean pc_menu_activate_screen( if (deleted) *widget_deleted = TRUE; return found; -} \ No newline at end of file +} diff --git a/port/linux/game/menu_tags.c b/port/linux/game/menu_tags.c index 1fe3ed9b56..f1343ba5fe 100644 --- a/port/linux/game/menu_tags.c +++ b/port/linux/game/menu_tags.c @@ -42,6 +42,7 @@ menu gets FRIENDLY FIRE too. #include "rasterizer/xbox/rasterizer_xbox_hardware_bitmaps.h" #include "halo_menus.h" +#include "frontend_menu.h" #include "mcc_ui.h" #include "mcc_cache.h" #include "mcc_menu_preview.h" @@ -369,7 +370,11 @@ static char const *const port_function_names[] = "port setup edit", "port setup options init", "port setup options save", "port map list back", - "port mcc solo folder back", "port mcc host folder back", + "port mcc solo folder back", + "port mcc host folder back", + "port mcc xbox init", "port mcc xbox open", "port mcc xbox choose", "port mcc xbox back", + "port mcc xbox left", "port mcc xbox right", "port mcc xbox card", + "port mcc xbox profile", "port mcc share download", "port mcc share workshop", "port mcc share cancel", "port mcc share closed", "port mcc downloads open", "port mcc downloads previous", "port mcc downloads next", "port mcc downloads remove", "port pause end game", "port coop friendly fire", @@ -404,10 +409,18 @@ static char const *const port_function_names[] = /* (the main menu's Mods: menu_functions.c) */ "port mods init", "port mods close", "port mods toggle", "port mods move up", "port mods move down", "port mods save", - "port controller init", "port controller close", "port controller defaults", "port controller save", "port controller bind", "port controller left", "port controller right", - /* (a dedicated server's map vote: menu_functions.c) */ - "port map vote open", "port map vote choose", + "port changelog init", "port changelog up", "port changelog down", + "port gulch build label", + "port changelog corner focus", "port changelog main focus", + "port controller init", "port controller close", "port controller defaults", + "port controller save", "port controller bind", "port controller left", "port controller right", "port controller clear", "port controller cancel", + "port bots init", "port bots command", "port bots host entry", "port bots settings save", + "port frontend apply", "port frontend cancel", + "port frontend init", "port frontend defaults", + "port frontend back", "port frontend page", "port frontend next tab", "port frontend editor", + "port frontend navigation init", + "port map vote open", "port map vote choose", }; /* the PC version's game data functions that the Xbox's have not, from @@ -420,7 +433,7 @@ static char const *const port_game_data_input_names[] = "server settings update", "audio menu update", "mp prof vehicles update", "solo map list update", "mp map list update", "gt select list update", "gt edit list update", "load game list update", "direct ip connect update", "network settings update", - "port settings help", "color picker update", "3wide player profile list update", "port lobby update", + "port frontend update", "port frontend navigation update", "port frontend multiplayer update", "port settings help", "color picker update", "3wide player profile list update", "port lobby update", "port lobby preview update", "port join4 update", /* (the gametype editor's: the Xbox's stops the game on the buttons' row; the Xbox's read only player_ui's gametype, not Server Setup's) */ @@ -429,8 +442,12 @@ static char const *const port_game_data_input_names[] = /* (the profile settings' picture: the Xbox's of the button settings, on Gamepad Setup's row) */ "port gamepad layout preview", + "port controller update", /* (the main menu's Mods) */ + "port mcc share update", "port mcc share text", + "port mcc downloads update", "port mcc downloads text", "port mods update", + "port changelog focus update", "port mcc share update", "port mcc share text", "port mcc downloads update", "port mcc downloads text", /* (network co-op's pause menu's FRIENDLY FIRE: its text, ON or OFF) */ @@ -2519,6 +2536,10 @@ void menu_tags_loaded( boolean game_map = strcmp(map_name, "ui") != 0; boolean campaign = game_map && full_screen_campaign_map(); boolean coop = game_map && network_coop_campaign_map(); + boolean frontend; + + frontend_menu_map_loaded(map_name, mcc_cache_tags_loaded()); + frontend = frontend_menu_requested(); /* MCC owns its pause menus and uses these native Settings screens. Do not patch embedded MCC campaign widgets. */ @@ -2535,12 +2556,12 @@ void menu_tags_loaded( campaign's too, single player's or network co-op's, which also gets FRIENDLY FIRE) */ if ((game_map && tag_loaded('Soul', MULTIPLAYER_COLLECTION) == NONE && !campaign) || - !menus_pc_chosen()) + (!menus_pc_chosen() && !frontend)) { return; } mcc_settings: - menus = halo_menus_load(); + menus = frontend ? frontend_menu_files_load() : halo_menus_load(); if (!menus) return; memset(&build, 0, sizeof(build)); @@ -2694,6 +2715,7 @@ void menu_tags_unloaded( void) { mcc_menu_preview_clear(); + frontend_menu_unloaded(); if (menu_tags.loaded || menu_tags.block_count) menu_tags_release(); } diff --git a/port/linux/game/muzzle_lighting.c b/port/linux/game/muzzle_lighting.c new file mode 100644 index 0000000000..b5a7b3cc3c --- /dev/null +++ b/port/linux/game/muzzle_lighting.c @@ -0,0 +1,296 @@ +/* Short, render-owned light pulses. Successful shots only record identities; + they never allocate engine lights or alter the weapon's authored effects. */ +#include "cseries.h" +#include "objects/objects.h" +#include "objects/object_lights.h" +#include "items/weapons.h" +#include "units/units.h" +#include "interface/first_person_weapons.h" +#include "camera/observer.h" +#include "game/players.h" +#include "tag_files/tag_files.h" +#include "muzzle_lighting.h" +#include "plasma_occlusion.h" +#include + +#include "lighting_config.h" +real render_interpolation_game_time_sec(long ticks); +long light_port_glow_definition_get(void); +boolean light_port_glow_set(long light, long owner, real_rgb_color const *color, real radius); +boolean light_port_glow_move(long light, real_point3d const *position); + +static const struct muzzle_profile +{ + const char *tag; + real_rgb_color color; + real radius, duration; + short triggers; /* bit mask; zero keeps the existing shared pulse */ + boolean vehicle_occlusion; + const char *marker; + real forward_offset; +} muzzle_profiles[] = { + {"weapons\\assault rifle\\assault rifle", {1.0f, 0.65f, 0.25f}, 1.8f, 0.10f}, + {"weapons\\pistol\\pistol", {1.0f, 0.65f, 0.25f}, 1.8f, 0.12f}, + {"weapons\\shotgun\\shotgun", {1.0f, 0.55f, 0.18f}, 2.2f, 0.14f}, + {"weapons\\sniper rifle\\sniper rifle", {1.0f, 0.70f, 0.35f}, 2.0f, 0.12f}, + {"weapons\\plasma rifle\\plasma rifle", {0.15f, 0.75f, 1.0f}, 1.6f, 0.10f}, + {"weapons\\plasma pistol\\plasma pistol", {0.25f, 1.0f, 0.12f}, 1.6f, 0.12f}, + {"weapons\\needler\\mp_needler", {0.85f, 0.20f, 1.0f}, 1.3f, 0.09f}, + {"weapons\\needler\\needler", {0.85f, 0.20f, 1.0f}, 1.3f, 0.09f}, + {"weapons\\rocket launcher\\rocket launcher", {1.0f, 0.50f, 0.15f}, 2.0f, 0.14f}, + {"weapons\\flamethrower\\flamethrower", {1.0f, 0.40f, 0.10f}, 1.4f, 0.08f}, + /* The model-less turret weapon uses the vehicle's rendered muzzle marker. + A wider warm pulse lights the hull and ground without changing its flash. */ + {"vehicles\\warthog\\warthog gun", {1.0f, 0.75f, 0.35f}, 5.0f, 0.16f, 0, TRUE}, + /* Separate triggers retain both pulses when the tank fires both guns. + The cannon flash is ahead of its projectile marker; move the coaxial + source just beyond its barrel so the vehicle can occlude it correctly. */ + {"vehicles\\scorpion\\scorpion cannon", {1.0f, 0.78f, 0.42f}, 7.0f, 0.22f, 1, TRUE, "cannon flash", 0.0f}, + {"vehicles\\scorpion\\scorpion cannon", {1.0f, 0.75f, 0.35f}, 5.0f, 0.12f, 2, TRUE, "secondary trigger", 0.08f}, +}; +enum { MUZZLE_LIGHTS = 8 }; +static struct muzzle_pulse +{ + int active, connected, profile, pending; + long weapon, owner, light, rasterizer, shot_tick; + short trigger; + real start, radius, duration; +} pulses[MUZZLE_LIGHTS]; +static const real_rgb_color muzzle_black = {0, 0, 0}; + +/* Zero slope at both ends, evaluated at render time rather than tick count. */ +static real muzzle_envelope(real age, real duration) +{ + real t = PIN(age / duration, 0.0f, 1.0f); + return (1.0f - t) * (1.0f - t) * (1.0f + 2.0f * t); +} + +static void muzzle_release(struct muzzle_pulse *pulse) +{ + if (pulse->active && pulse->light != NONE && + light_port_glow_set(pulse->light, NONE, &muzzle_black, 0.0f)) + light_delete(pulse->light); + memset(pulse, 0, sizeof(*pulse)); +} + +void muzzle_lighting_shot(long weapon_index, short trigger_index) +{ + struct weapon_datum *weapon; + const char *name; + struct muzzle_pulse *pulse; + int i, profile, slot = NONE; + if (!lighting_config_boolean("display.muzzle_lighting") || trigger_index < 0 || trigger_index > 1) + return; + weapon = weapon_try_and_get(weapon_index); + if (!weapon || !unit_try_and_get(weapon->object.parent_object_index)) + return; + name = tag_get_name(weapon->definition_index); + if (!name) + return; + for (profile = 0; profile < NUMBEROF(muzzle_profiles); profile++) + if (!strcmp(name, muzzle_profiles[profile].tag) && + (!muzzle_profiles[profile].triggers || TEST_FLAG(muzzle_profiles[profile].triggers, trigger_index))) + break; + if (profile == NUMBEROF(muzzle_profiles)) + return; /* unfamiliar custom weapons retain their authored effects */ + for (i = 0; i < MUZZLE_LIGHTS; i++) + { + if (pulses[i].active && pulses[i].weapon == weapon_index && + (!muzzle_profiles[profile].triggers || pulses[i].trigger == trigger_index)) + { + slot = i; + break; + } + if (!pulses[i].active && slot == NONE) + slot = i; + } + if (slot == NONE) + return; /* never evict a fading light to admit another */ + pulse = &pulses[slot]; + if (pulse->active && pulse->shot_tick == game_time_get() && pulse->trigger == trigger_index) + return; + if (!pulse->active) + { + pulse->light = pulse->rasterizer = NONE; + pulse->connected = FALSE; + } + pulse->active = pulse->pending = TRUE; + pulse->weapon = weapon_index; + pulse->owner = weapon->object.parent_object_index; + pulse->shot_tick = game_time_get(); + pulse->trigger = trigger_index; + pulse->profile = profile; + pulse->radius = muzzle_profiles[profile].radius; + pulse->duration = muzzle_profiles[profile].duration; + if (!strcmp(name, "weapons\\plasma pistol\\plasma pistol") && trigger_index == 1) + { + pulse->radius = 2.2f; + pulse->duration = 0.16f; + } +} + +static int muzzle_position(struct muzzle_pulse *pulse, real_point3d *position) +{ + struct weapon_datum *weapon = weapon_try_and_get(pulse->weapon); + struct unit_datum *unit = unit_try_and_get(pulse->owner); + struct object_marker marker; + const char *name = pulse->trigger ? "secondary trigger" : "primary trigger"; + short player; + real_vector3d forward, up; + const struct muzzle_profile *profile = &muzzle_profiles[pulse->profile]; + if (!weapon || !unit || weapon->object.parent_object_index != pulse->owner || + unit->unit.current_weapon_index < 0 || unit->unit.current_weapon_index >= MAXIMUM_WEAPONS_PER_UNIT || + unit_inventory_get_weapon(pulse->owner, unit->unit.current_weapon_index) != pulse->weapon) + return FALSE; + if (profile->marker) + name = profile->marker; + if (!first_person_weapon_adjust_light(pulse->weapon, name, position, &forward, &up)) + { + long object = TEST_FLAG(weapon->object.flags, _object_invisible_bit) ? pulse->owner : pulse->weapon; + if (object_get(object)->object.node_matrices.size < sizeof(real_matrix4x3) || + !object_get_marker_by_name(object, name, &marker, 1)) + return FALSE; + *position = marker.matrix.position; + forward = marker.matrix.forward; + } + if (profile->forward_offset != 0.0f) + { + position->x += forward.i * profile->forward_offset; + position->y += forward.j * profile->forward_offset; + position->z += forward.k * profile->forward_offset; + } + for (player = local_player_get_next(NONE); player != NONE; player = local_player_get_next(player)) + { + const struct observer_result *camera = observer_get_camera(player); + if (camera && distance3d(position, &camera->position) <= 25.0f) + return TRUE; + } + return FALSE; +} + +void muzzle_lighting_update(void) +{ + int i; + real now = render_interpolation_game_time_sec(game_time_get()); + for (i = 0; i < MUZZLE_LIGHTS; i++) + { + struct muzzle_pulse *pulse = &pulses[i]; + real_point3d position; + real_rgb_color color; + real strength; + long definition; + if (!pulse->active) + continue; + if (!lighting_config_boolean("display.muzzle_lighting") || game_time_get() < pulse->shot_tick || + (pulse->pending && game_time_get() - pulse->shot_tick > 2) || + !muzzle_position(pulse, &position)) + { + muzzle_release(pulse); + continue; + } + if (pulse->pending) + { + pulse->start = now; + pulse->pending = FALSE; + } + strength = muzzle_envelope(now - pulse->start, pulse->duration); + if (now < pulse->start || strength <= 0.0f) + { + muzzle_release(pulse); + continue; + } + color = muzzle_profiles[pulse->profile].color; + color.red *= strength; + color.green *= strength; + color.blue *= strength; + if (pulse->light == NONE) + { + definition = light_port_glow_definition_get(); + if (definition != NONE) + pulse->light = light_new_unattached(definition, NONE, 0, &position, global_forward3d, 0.0f); + } + if (!light_port_glow_set(pulse->light, NONE, &color, pulse->radius) || + !light_port_glow_move(pulse->light, &position)) + { + muzzle_release(pulse); + continue; + } + pulse->connected = TRUE; + } +} + +void muzzle_lighting_frame_end(void) +{ + int i; + for (i = 0; i < MUZZLE_LIGHTS; i++) + { + struct muzzle_pulse *pulse = &pulses[i]; + if (!pulse->active) + continue; + if (!lighting_config_boolean("display.muzzle_lighting")) + muzzle_release(pulse); + else if (pulse->connected && light_port_glow_set(pulse->light, NONE, &muzzle_black, 0.0f)) + { + light_disconnect_from_map(pulse->light); + pulse->connected = FALSE; + } + pulse->rasterizer = NONE; + } +} + +void muzzle_lighting_forget(void) +{ + memset(pulses, 0, sizeof(pulses)); +} + +void muzzle_lighting_window_begin(void) +{ + int i; + for (i = 0; i < MUZZLE_LIGHTS; i++) + pulses[i].rasterizer = NONE; +} + +void muzzle_lighting_submitted(long light_index, long rasterizer_index) +{ + int i; + for (i = 0; i < MUZZLE_LIGHTS; i++) + if (pulses[i].active && pulses[i].light == light_index) + { + pulses[i].rasterizer = rasterizer_index; + plasma_occlusion_submit(light_index, rasterizer_index); + } +} + +int muzzle_lighting_selected(long rasterizer_index) +{ + int i; + if (!lighting_config_boolean("display.muzzle_lighting") || rasterizer_index == NONE) + return FALSE; + for (i = 0; i < MUZZLE_LIGHTS; i++) + if (pulses[i].active && pulses[i].rasterizer == rasterizer_index) + return TRUE; + return FALSE; +} + +float muzzle_lighting_radius(long light_index, float radius) +{ + int i; + if (!lighting_config_boolean("display.muzzle_lighting")) + return radius; + for (i = 0; i < MUZZLE_LIGHTS; i++) + if (pulses[i].active && pulses[i].light == light_index) + return MAX(radius, pulses[i].radius); + return radius; +} + +int muzzle_lighting_vehicle_occlusion(long light) +{ + int i; + if (light == NONE || !lighting_config_boolean("display.muzzle_lighting")) + return FALSE; + for (i = 0; i < MUZZLE_LIGHTS; i++) + if (pulses[i].active && pulses[i].light == light && + muzzle_profiles[pulses[i].profile].vehicle_occlusion) + return TRUE; + return FALSE; +} diff --git a/port/linux/game/muzzle_lighting.h b/port/linux/game/muzzle_lighting.h new file mode 100644 index 0000000000..9b3a83375d --- /dev/null +++ b/port/linux/game/muzzle_lighting.h @@ -0,0 +1,15 @@ +#ifndef MUZZLE_LIGHTING_H +#define MUZZLE_LIGHTING_H + +void muzzle_lighting_shot(long weapon_index, short trigger_index); +void muzzle_lighting_update(void); +void muzzle_lighting_frame_end(void); +void muzzle_lighting_forget(void); +void muzzle_lighting_window_begin(void); +void muzzle_lighting_submitted(long light_index, long rasterizer_index); +int muzzle_lighting_selected(long rasterizer_index); +float muzzle_lighting_radius(long light_index, float radius); + +int muzzle_lighting_vehicle_occlusion(long light); + +#endif diff --git a/port/linux/game/needler_lighting.c b/port/linux/game/needler_lighting.c new file mode 100644 index 0000000000..19460795fc --- /dev/null +++ b/port/linux/game/needler_lighting.c @@ -0,0 +1,106 @@ +/* Exposed Needler crystals illuminate the holder and nearby surfaces; + the emitter module owns allocation, fading and frame cleanup. */ +#include "cseries.h" +#include "objects/objects.h" +#include "items/weapons.h" +#include "units/units.h" +#include "interface/first_person_weapons.h" +#include "needler_lighting.h" +#include "shaders/shader_definitions.h" +#include "rasterizer/xbox/rasterizer_xbox_pixel_shader.h" +#include + +#include "lighting_config.h" + +int needler_lighting_position(long index, real_point3d *position, real_vector3d *direction) +{ + struct weapon_datum *weapon; + struct unit_datum *unit; + struct object_marker marker; + real_vector3d forward, up; + const char *name; + if (!lighting_config_boolean("display.needler_lighting")) + return FALSE; + weapon = weapon_try_and_get(index); + if (!weapon || TEST_FLAG(weapon->object.flags, _object_invisible_bit)) + return FALSE; + name = tag_get_name(weapon->definition_index); + if (!name || strcmp(name, "weapons\\needler\\needler")) + return FALSE; + unit = unit_try_and_get(weapon->object.parent_object_index); + if (!unit || TEST_FLAG(unit->object.flags, _object_invisible_bit) || + unit->unit.current_weapon_index < 0 || unit->unit.current_weapon_index >= MAXIMUM_WEAPONS_PER_UNIT || + unit_inventory_get_weapon(weapon->object.parent_object_index, unit->unit.current_weapon_index) != index) + return FALSE; + /* Stock FP and world smoke markers share the needle-cluster position: + (-.031742, 0, .080221). Sample the interpolated pose for each view. */ + if (!first_person_weapon_adjust_light(index, "smoke", position, &forward, &up)) + { + if (weapon->object.node_matrices.size < sizeof(real_matrix4x3) || + !object_get_marker_by_name(index, "smoke", &marker, 1)) + return FALSE; + *position = marker.matrix.position; + up = marker.matrix.up; + } + *direction = up; + return TRUE; +} + +/* Cache only within a loaded map; the emitter lifecycle clears this pointer. */ +static struct shader *needler_material; +static int needler_material_checked; +static struct shader *needler_core, *needler_world_crystals; +static int needler_crystals_checked; + +void needler_lighting_forget(void) +{ + needler_material = NULL; + needler_core = needler_world_crystals = NULL; + needler_crystals_checked = FALSE; + needler_material_checked = FALSE; +} + +void needler_lighting_material(struct shader *shader, real_rgb_color *color) +{ + long index; + if (!lighting_config_boolean("display.needler_lighting")) + return; + if (!needler_material_checked) + { + index = tag_loaded('soso', "weapons\\needler\\shaders\\needler dull"); + needler_material = index == NONE ? NULL : shader_definition_get(index); + needler_material_checked = TRUE; + } + if (!shader || shader != needler_material) + return; + /* Both models share the dull needle material and its authored mask. + Retain the transparent crystal layers and any brighter animation. */ + color->red = MAX(color->red, 1.0f); + color->green = MAX(color->green, 0.30f); + color->blue = MAX(color->blue, 0.85f); +} + +/* Boost only the authored crystal colour stage, before fog. Alpha, texture + masks, blending and camouflage remain controlled by the stock shader. */ +void needler_lighting_transparent(struct shader *shader, struct pixel_shader_definition *pixel, int stages) +{ + long index; + unsigned long *output; + if (!lighting_config_boolean("display.needler_lighting") || stages < 1 || stages > 8) + return; + if (!needler_crystals_checked) + { + index = tag_loaded('sotr', "weapons\\needler\\shaders\\needler core"); + needler_core = index == NONE ? NULL : shader_definition_get(index); + index = tag_loaded('schi', "weapons\\needler\\shaders\\needler luminous 3p"); + needler_world_crystals = index == NONE ? NULL : shader_definition_get(index); + needler_crystals_checked = TRUE; + } + if (!shader || (shader != needler_core && shader != needler_world_crystals)) + return; + output = &pixel->rgb_outputs[stages - 1]; + /* NV2A output mapping 0x10 (bits 12+) doubles RGB, with normal clamping. + Leave custom biased/scaled stages alone rather than replacing them. */ + if ((*output & 0x38000UL) == 0) + *output |= 0x10000UL; +} diff --git a/port/linux/game/needler_lighting.h b/port/linux/game/needler_lighting.h new file mode 100644 index 0000000000..2b07bc8a1d --- /dev/null +++ b/port/linux/game/needler_lighting.h @@ -0,0 +1,12 @@ +#ifndef NEEDLER_LIGHTING_H +#define NEEDLER_LIGHTING_H + +int needler_lighting_position(long weapon, real_point3d *position, real_vector3d *direction); + +struct shader; +void needler_lighting_material(struct shader *shader, real_rgb_color *color); +void needler_lighting_forget(void); +struct pixel_shader_definition; +void needler_lighting_transparent(struct shader *shader, struct pixel_shader_definition *pixel, int stages); + +#endif diff --git a/port/linux/game/network_damage.c b/port/linux/game/network_damage.c index d0434e5af4..9a25026712 100644 --- a/port/linux/game/network_damage.c +++ b/port/linux/game/network_damage.c @@ -68,6 +68,7 @@ being hit looks and feels like on the clients). #include "units/units.h" #include "network_distributed.h" #include "mcc_grenades.h" +#include "third_person.h" #include @@ -480,7 +481,7 @@ static struct damage_trail_point real radius; real eye; boolean mounted; - /* (the muzzle the player's machine said: a hand, not a vehicle's gun) */ + /* A client-reported hand, rather than a host-owned vehicle/shoulder muzzle. */ boolean hand; real_point3d muzzle; } damage_trails[MAXIMUM_TRACKED_PLAYERS][PLAYER_TRAIL_POINTS]; @@ -1575,6 +1576,10 @@ static void distributed_note_targets( point->mounted = distributed_vehicle_muzzle(vehicle_index, &point->muzzle); } } + /* Shoulder origins come from the host's own weapon pose. + The existing visibility check still traces eye-to-muzzle. */ + else if (third_person_muzzle_history(unit_index, &point->muzzle)) + point->mounted = TRUE; /* on foot, shots that leave from elsewhere than the camera (a VR player's hand, which may be past a corner the camera is behind): from there as from a vehicle's diff --git a/port/linux/game/network_distributed.c b/port/linux/game/network_distributed.c index 494cd2b114..95f421ee39 100644 --- a/port/linux/game/network_distributed.c +++ b/port/linux/game/network_distributed.c @@ -102,6 +102,8 @@ machine (their datum identifiers need not be). #include #include #include +#include "third_person.h" +#include "third_person_protocol.h" /* network_game_globals.c's and network_server_message_handler.c's */ boolean network_distributed_client_send(void *message, word size); @@ -433,6 +435,7 @@ the tick after (distributed_relayed_action_write) */ struct distributed_relayed_action { byte player_index; + byte shoulder; signed char desired_weapon_index; signed char desired_grenade_index; signed char desired_zoom_level; @@ -3954,6 +3957,8 @@ static void distributed_handle_inputs( action = input->action; /* Only the defined input bits are accepted; forced-off wins. */ action.control_flags &= 0x1FFFFUL; + if (third_person_policy() == _third_person_forced_off) + SET_FLAG(action.control_flags, THIRD_PERSON_INPUT_BIT, FALSE); action.throttle.i = PIN(action.throttle.i, -1.0f, 1.0f); action.throttle.j = PIN(action.throttle.j, -1.0f, 1.0f); action.primary_trigger = PIN(action.primary_trigger, 0.0f, 1.0f); @@ -4047,6 +4052,7 @@ static boolean distributed_relayed_action_from( csmemset(relayed, 0, sizeof(*relayed)); relayed->player_index = (byte)player_index; + relayed->shoulder = TEST_FLAG(action->control_flags, THIRD_PERSON_INPUT_BIT) != 0; relayed->desired_weapon_index = (signed char)action->desired_weapon_index; relayed->desired_grenade_index = (signed char)action->desired_grenade_index; relayed->desired_zoom_level = (signed char)MIN(action->desired_zoom_level, 127); @@ -4057,6 +4063,7 @@ static boolean distributed_relayed_action_from( relayed->control_flags[history] = past ? (unsigned short)past->control_flags : 0; if (history > 0 && (!past || relayed->control_flags[history] != relayed->control_flags[history - 1] || + TEST_FLAG(past->control_flags ^ action->control_flags, THIRD_PERSON_INPUT_BIT) || past->desired_weapon_index != action->desired_weapon_index || past->desired_grenade_index != action->desired_grenade_index || past->desired_zoom_level != action->desired_zoom_level)) @@ -4085,6 +4092,8 @@ static word distributed_relayed_action_write( byte *cursor = buffer + 2; short history; + if (third_person_session_active()) + cursor = distributed_put(cursor, &relayed->shoulder, sizeof(relayed->shoulder)); cursor = distributed_put(cursor, &relayed->desired_weapon_index, sizeof(relayed->desired_weapon_index)); cursor = distributed_put(cursor, &relayed->desired_grenade_index, sizeof(relayed->desired_grenade_index)); cursor = distributed_put(cursor, &relayed->desired_zoom_level, sizeof(relayed->desired_zoom_level)); @@ -4121,6 +4130,8 @@ static word distributed_relayed_action_read( csmemset(relayed, 0, sizeof(*relayed)); if (!distributed_take(&cursor, end, &relayed->player_index, sizeof(relayed->player_index)) || !distributed_take(&cursor, end, &parts, sizeof(parts)) || + (third_person_session_active() && (!distributed_take(&cursor, end, &relayed->shoulder, sizeof(relayed->shoulder)) || + relayed->shoulder > 1)) || !distributed_take(&cursor, end, &relayed->desired_weapon_index, sizeof(relayed->desired_weapon_index)) || !distributed_take(&cursor, end, &relayed->desired_grenade_index, sizeof(relayed->desired_grenade_index)) || !distributed_take(&cursor, end, &relayed->desired_zoom_level, sizeof(relayed->desired_zoom_level)) || @@ -4392,7 +4403,7 @@ static void distributed_host_send_players( &distributed_host_update_number, sizeof(distributed_host_update_number)); for (player_index = 0; player_index < MAXIMUM_TRACKED_PLAYERS; player_index++) { - byte entry[DISTRIBUTED_RELAYED_ACTION_MAXIMUM_SIZE]; + byte entry[DISTRIBUTED_RELAYED_ACTION_MAXIMUM_SIZE + 1]; /* optional camera byte */ if (TEST_FLAG(distributed_sends[machine_index][player_index], _distributed_send_action_bit)) { @@ -4440,6 +4451,7 @@ static void distributed_handle_actions( data += size; csmemset(&action, 0, sizeof(action)); action.control_flags = relayed.control_flags[0]; + SET_FLAG(action.control_flags, THIRD_PERSON_INPUT_BIT, relayed.shoulder); action.desired_facing.yaw = distributed_angle_unpack(relayed.yaw, FALSE); action.desired_facing.pitch = distributed_angle_unpack(relayed.pitch, TRUE); action.throttle.i = PIN((real)relayed.throttle_i / 127.0f, -1.0f, 1.0f); diff --git a/port/linux/game/network_test.c b/port/linux/game/network_test.c index 77b7abf77d..d96a970c29 100644 --- a/port/linux/game/network_test.c +++ b/port/linux/game/network_test.c @@ -56,6 +56,7 @@ Called from the main loop every frame (main.c). */ #include "cseries.h" +#include "third_person.h" #include "game_modes.h" #include "main/main.h" #include "bink/bink_playback.h" @@ -79,6 +80,7 @@ Called from the main loop every frame (main.c). #include "scenario/scenario.h" #include "tag_files/tag_files.h" #include "camera/observer.h" +#include "mcc_cache.h" #include "hs/hs.h" #include "../src/p2p.h" /* port: port/linux/src/p2p.c, p2p_lobby.c */ @@ -169,6 +171,7 @@ static struct short chat_lines_said; long score_to_win; long logged_time; + long sample_time; boolean public_game; boolean browsing; boolean browse_listed; @@ -448,6 +451,7 @@ static void network_test_log_players( platform_log("network test: tick %ld%s | items %ld (+%ld -%ld !%ld x%ld) | %s to %ld | sent %ld received %ld corrected %ld" " | hits %ld dealt %ld rejected %ld replayed %ld | local %ld camera (%.1f %.1f %.1f) respawn %ld" + " | camera-policy %d preference %d effective %d active %d" " | drift %ld %ld %.6f %.6f", game_time_get(), line, ground_items, creates, deletes, failures, removed, game_engine_can_score() ? "playing" : "game over", @@ -457,6 +461,8 @@ static void network_test_log_players( local_player_index == NONE ? -1L : (long)DATUM_INDEX_TO_ABSOLUTE_INDEX(local_player_index), camera ? camera->position.x : 0.0f, camera ? camera->position.y : 0.0f, camera ? camera->position.z : 0.0f, local_player_index == NONE ? 0L : (long)player_get(local_player_index)->respawn_timer, + (int)third_person_policy(), config_boolean("display.third_person"), + (int)third_person_enabled(), (int)third_person_active(0), divergence_samples, divergence_apart, divergence_mean, divergence_largest); } } @@ -1170,10 +1176,22 @@ void network_test_update( } if (game_in_progress() && !main_menu_loaded) network_test_run_cues(); + /* Observe the first frame in each absolute simulation second. A late join + * must not permanently offset the sample cadence; report the actual tick, + * never backfill missed states. Scripted actions retain their old cadence. */ + if (game_in_progress() && !main_menu_loaded) + { + if (game_time_get() < network_test.sample_time) + network_test.sample_time = 0; + if (game_time_get() / TICKS_PER_SECOND > network_test.sample_time / TICKS_PER_SECOND) + { + network_test.sample_time = game_time_get(); + network_test_log_players(); + } + } if (game_in_progress() && !main_menu_loaded && game_time_get() - network_test.logged_time >= TICKS_PER_SECOND) { network_test.logged_time = game_time_get(); - network_test_log_players(); if (network_test.shoot_interval > 0.0f && game_time_get() % MAX(1, (long)(network_test.shoot_interval * TICKS_PER_SECOND)) < TICKS_PER_SECOND) { @@ -1491,7 +1509,9 @@ void network_test_update( } } - if (!main_menu_loaded) + /* The real menu waits for profile enumeration before accepting input. + Starting a lobby sooner can block its join on the profile mutex. */ + if (!main_menu_loaded || filesystem_check_thread_is_active()) return; /* the intro movie skipped first, as a button press does: the movie holds the texture cache's spare memory, which starting the map @@ -1620,8 +1640,12 @@ void network_test_update( { /* (the Map screen's co-op: menu_functions.c) */ extern boolean ui_widget_port_cooperative_level_choose(char const *map_name, short difficulty); + extern boolean ui_widget_port_mcc_cooperative_level_choose(char const *map_name, short difficulty); - if (!ui_widget_port_cooperative_level_choose(path, _game_difficulty_level_normal)) + /* Exercise the same independent MCC route as its campaign menu. */ + if (!(mcc_level_name(path) ? + ui_widget_port_mcc_cooperative_level_choose(path, _game_difficulty_level_normal) : + ui_widget_port_cooperative_level_choose(path, _game_difficulty_level_normal))) platform_log("network test: %s is not a campaign level, for co-op", path); platform_log("network test: game %d, co-op", network_test.variant_index + 1); } diff --git a/port/linux/game/object_mesh.c b/port/linux/game/object_mesh.c deleted file mode 100644 index 705637842e..0000000000 --- a/port/linux/game/object_mesh.c +++ /dev/null @@ -1,361 +0,0 @@ -/* -OBJECT_MESH.C - -An object's drawn surface (object_mesh.h), which first_person_legs.c finds -the waist's rim in: the triangles of its model's most detailed geometry, in -the permutation of each region the object shows, read from the vertex and -index buffers the game draws them from (as powerup_render_bounds.c reads -them), with each vertex's nodes and weight. Opaque parts only (no glass, no -effects), and none the game doesn't draw (stripped parts). The last mesh -read is kept, in memory taken the first time one is (none, unless an effect -asks: about 400 KB). -*/ - -#include "cseries.h" -#include "math/real_math.h" -#include "models/model_definitions.h" -#include "objects/objects.h" -#include "objects/object_definitions.h" -#include "rasterizer/rasterizer.h" -#include "rasterizer/rasterizer_geometry.h" -#include "rasterizer/rasterizer_model_types.h" -#include "shaders/shader_definitions.h" -#include "shaders/shaders.h" -#include "tag_files/tag_groups.h" -#include "tag_files/tag_files.h" - -#include "object_mesh.h" - -#include -#include -#include - -/* ---------- constants */ - -enum -{ - OBJECT_MESH_DETAIL_LEVELS = 5, /* (models.c's NUMBER_OF_DETAIL_LEVELS_PER_MODEL) */ -}; - -enum -{ - _object_mesh_part_stripped_bit = 0, - _object_mesh_part_local_nodes_bit, -}; - -/* ---------- structures */ - -/* this build's model geometry and part (models.c's; no header declares -them) */ -struct object_mesh_model_geometry -{ - byte reserved[0x24]; - struct tag_block parts; -}; - -struct object_mesh_model_geometry_part -{ - unsigned long flags; - short shader_index; - char previous_part_index; - char next_part_index; - short centroid_primary_node_index; - short centroid_secondary_node_index; - real centroid_primary_node_weight; - real centroid_secondary_node_weight; - real_point3d centroid; - struct tag_block uncompressed_vertices; - struct tag_block compressed_vertices; - struct tag_block triangles; - struct triangle_buffer triangle_buffer; - struct vertex_buffer vertex_buffer; -}; - -typedef char verify_object_mesh_model_geometry_part_size[sizeof(struct object_mesh_model_geometry_part) == 0x68 ? 1 : -1]; - -struct object_mesh_model_shader_reference -{ - struct tag_reference shader; - short permutation_index; - word pad; - long unused[3]; -}; - -/* ---------- globals */ - -/* the mesh kept (its vertices and triangles NULL until one is asked for) */ -static struct object_mesh object_mesh_kept = { NONE }; - -/* ---------- private code */ - -/* (a key for the model and the permutations it shows) */ -static long object_mesh_key( - long model_index, - byte const *permutations) -{ - unsigned long key = (unsigned long)model_index * 2654435761ul; - short index; - - for (index = 0; index < MAXIMUM_REGIONS_PER_OBJECT; index++) - key = (key ^ permutations[index]) * 16777619ul; - key &= 0x7fffffff; - return key == (unsigned long)NONE ? 0 : (long)key; -} - -/* a part's triangles and vertices onto the mesh; FALSE when it can't be read -(the mesh is then not used) */ -static boolean object_mesh_add_part( - struct object_mesh *mesh, - struct model const *model, - struct object_mesh_model_geometry_part const *part) -{ - struct vertex_buffer const *vertex_buffer = &part->vertex_buffer; - struct triangle_buffer const *triangle_buffer = &part->triangle_buffer; - byte *vertices = NULL; - BYTE *indices = NULL; - long stride; - long first_vertex = mesh->vertex_count; - long index_count; - long index; - - /* (only what the game draws, opaque) */ - if (TEST_FLAG(part->flags, _object_mesh_part_stripped_bit)) - return TRUE; - if (VALID_INDEX(part->shader_index, model->shaders.count)) - { - struct object_mesh_model_shader_reference const *reference = TAG_BLOCK_GET_ELEMENT( - &model->shaders, part->shader_index, struct object_mesh_model_shader_reference); - struct shader *shader = reference->shader.index != NONE && reference->shader.index != 0 ? - shader_definition_get(reference->shader.index) : NULL; - - if (!shader || !shader_type_is_valid_for_model(shader->base.type) || shader_type_is_transparent(shader->base.type)) - return TRUE; - } - else - return TRUE; - if (!vertex_buffer->hardware_format || - vertex_buffer->count <= 0 || !triangle_buffer->hardware_format || - triangle_buffer->count <= 0) - { - return TRUE; - } - if (vertex_buffer->type == _rasterizer_vertex_type_model_compressed) - stride = sizeof(struct model_vertex_compressed); - else if (vertex_buffer->type == _rasterizer_vertex_type_model_uncompressed) - stride = sizeof(struct model_vertex_uncompressed); - else - return TRUE; - if (triangle_buffer->type == 1) - index_count = triangle_buffer->count + 2; /* a strip */ - else if (triangle_buffer->type == 0) - index_count = triangle_buffer->count * 3; /* a list */ - else - return TRUE; - if (mesh->vertex_count + vertex_buffer->count > OBJECT_MESH_MAXIMUM_VERTICES) - return FALSE; - - IDirect3DVertexBuffer8_Lock((IDirect3DVertexBuffer8 *)vertex_buffer->hardware_format, 0, 0, &vertices, D3DLOCK_READONLY); - IDirect3DIndexBuffer8_Lock((IDirect3DIndexBuffer8 *)triangle_buffer->hardware_format, 0, 0, &indices, D3DLOCK_READONLY); - if (!vertices || !indices) - { - if (vertices) - IDirect3DVertexBuffer8_Unlock((IDirect3DVertexBuffer8 *)vertex_buffer->hardware_format); - if (indices) - IDirect3DIndexBuffer8_Unlock((IDirect3DIndexBuffer8 *)triangle_buffer->hardware_format); - return TRUE; - } - - /* its vertices, with their nodes */ - for (index = 0; index < vertex_buffer->count; index++) - { - struct object_mesh_vertex *out = &mesh->vertices[mesh->vertex_count + index]; - long node0; - long node1; - real weight; - - if (vertex_buffer->type == _rasterizer_vertex_type_model_compressed) - { - struct model_vertex_compressed const *in = (struct model_vertex_compressed const *)(vertices + index * stride); - - out->position = in->position; - node0 = in->nodes[0] / 3; - node1 = in->nodes[1] / 3; - weight = (real)in->node_weight * (1.f / 32767.f); - } - else - { - struct model_vertex_uncompressed const *in = (struct model_vertex_uncompressed const *)(vertices + index * stride); - - out->position = in->position; - node0 = in->nodes[0]; - node1 = in->nodes[1]; - weight = in->node_weights[0]; - } - /* (a part with its own node map, which this build's part doesn't - carry: held to the node its middle is on; a tree's trunk, a rock) */ - if (TEST_FLAG(part->flags, _object_mesh_part_local_nodes_bit)) - { - node0 = node1 = VALID_INDEX(part->centroid_primary_node_index, mesh->node_count) ? - part->centroid_primary_node_index : 0; - weight = 1.f; - } - if (!VALID_INDEX(node0, mesh->node_count)) - node0 = 0; - if (!VALID_INDEX(node1, mesh->node_count)) - { - node1 = node0; - weight = 1.f; - } - if (!valid_real(out->position.x) || !valid_real(out->position.y) || !valid_real(out->position.z)) - out->position.x = out->position.y = out->position.z = 0.f; - out->nodes[0] = (byte)node0; - out->nodes[1] = (byte)node1; - out->weight = (short)(PIN(valid_real(weight) ? weight : 1.f, 0.f, 1.f) * 32767.f); - } - mesh->vertex_count += vertex_buffer->count; - - /* its triangles: a strip's every one (turning, its degenerate ones left - out), or a list's */ - { - unsigned short const *list = (unsigned short const *)indices; - - for (index = 0; index + 2 < index_count && mesh->triangle_count < OBJECT_MESH_MAXIMUM_TRIANGLES; - index += (triangle_buffer->type == 1) ? 1 : 3) - { - unsigned short a = list[index]; - unsigned short b = list[index + 1]; - unsigned short c = list[index + 2]; - unsigned short *out = mesh->triangles[mesh->triangle_count]; - - if (a == b || b == c || a == c || - a >= vertex_buffer->count || b >= vertex_buffer->count || c >= vertex_buffer->count) - { - continue; - } - /* (a strip's odd triangles turn the other way) */ - if (triangle_buffer->type == 1 && (index & 1)) - { - unsigned short swap = b; - - b = c; - c = swap; - } - out[0] = (unsigned short)(first_vertex + a); - out[1] = (unsigned short)(first_vertex + b); - out[2] = (unsigned short)(first_vertex + c); - mesh->triangle_count++; - } - } - - IDirect3DVertexBuffer8_Unlock((IDirect3DVertexBuffer8 *)vertex_buffer->hardware_format); - IDirect3DIndexBuffer8_Unlock((IDirect3DIndexBuffer8 *)triangle_buffer->hardware_format); - return TRUE; -} - -static boolean object_mesh_build( - struct object_mesh *mesh, - long model_index, - byte const *permutations) -{ - struct model *model = model_definition_get(model_index); - short region_index; - short node_index; - - mesh->model_index = model_index; - mesh->vertex_count = 0; - mesh->triangle_count = 0; - if (!model || !model->nodes.address || model->nodes.count <= 0 || !model->regions.address || - model->geometries.count <= 0 || !model->geometries.address) - { - return FALSE; - } - mesh->node_count = (short)MIN(model->nodes.count, OBJECT_MESH_MAXIMUM_NODES); - for (node_index = 0; node_index < mesh->node_count; node_index++) - { - struct model_node const *node = TAG_BLOCK_GET_ELEMENT(&model->nodes, node_index, struct model_node); - - mesh->inverse[node_index] = node->runtime_default_inverse_matrix; - } - for (region_index = 0; region_index < MIN(model->regions.count, MAXIMUM_REGIONS_PER_OBJECT); region_index++) - { - struct model_region const *region = TAG_BLOCK_GET_ELEMENT(&model->regions, region_index, struct model_region); - short permutation_index = permutations[region_index]; - struct model_region_permutation const *permutation; - short geometry_index; - short level; - - if (!VALID_INDEX(permutation_index, region->permutations.count) || !region->permutations.address) - continue; - permutation = TAG_BLOCK_GET_ELEMENT(®ion->permutations, permutation_index, struct model_region_permutation); - /* (its most detailed geometry) */ - geometry_index = NONE; - for (level = OBJECT_MESH_DETAIL_LEVELS - 1; level >= 0 && !VALID_INDEX(geometry_index, model->geometries.count); level--) - geometry_index = permutation->geometry_indices[level]; - if (!VALID_INDEX(geometry_index, model->geometries.count)) - continue; - { - struct object_mesh_model_geometry const *geometry = TAG_BLOCK_GET_ELEMENT( - &model->geometries, geometry_index, struct object_mesh_model_geometry); - long part_index; - - if (geometry->parts.count <= 0 || geometry->parts.count > MAXIMUM_PARTS_PER_MODEL_GEOMETRY || !geometry->parts.address) - continue; - for (part_index = 0; part_index < geometry->parts.count; part_index++) - { - struct object_mesh_model_geometry_part const *part = TAG_BLOCK_GET_ELEMENT( - &geometry->parts, part_index, struct object_mesh_model_geometry_part); - - /* (full: what it has) */ - if (!object_mesh_add_part(mesh, model, part)) - return mesh->triangle_count > 0; - } - } - } - return mesh->triangle_count > 0; -} - -/* ---------- public code */ - -void object_mesh_reset( - void) -{ - object_mesh_kept.key = NONE; -} - -struct object_mesh const *object_mesh_get( - long object_index) -{ - struct object_datum *object = object_try_and_get(object_index); - struct object_definition *definition; - struct object_mesh *mesh = &object_mesh_kept; - long model_index; - long key; - - if (!object) - return NULL; - definition = object_definition_get(object->definition_index); - model_index = definition ? definition->object.model.index : NONE; - if (model_index == NONE) - return NULL; - key = object_mesh_key(model_index, object->object.region_permutations); - if (mesh->key == key && mesh->model_index == model_index) - return mesh->triangle_count > 0 ? mesh : NULL; - if (!mesh->vertices) - { - mesh->vertices = malloc(sizeof(*mesh->vertices) * OBJECT_MESH_MAXIMUM_VERTICES); - mesh->triangles = malloc(sizeof(*mesh->triangles) * OBJECT_MESH_MAXIMUM_TRIANGLES); - if (!mesh->vertices || !mesh->triangles) - { - free(mesh->vertices); - free(mesh->triangles); - mesh->vertices = NULL; - mesh->triangles = NULL; - return NULL; - } - } - mesh->key = key; - /* (remembered when it has none, too) */ - if (!object_mesh_build(mesh, model_index, object->object.region_permutations)) - mesh->triangle_count = 0; - return mesh->triangle_count > 0 ? mesh : NULL; -} diff --git a/port/linux/game/object_mesh.h b/port/linux/game/object_mesh.h deleted file mode 100644 index 264b32cc8f..0000000000 --- a/port/linux/game/object_mesh.h +++ /dev/null @@ -1,52 +0,0 @@ -/* -OBJECT_MESH.H - -An object's drawn surface, as the game draws it (port/linux/game/object_mesh.c): -the triangles of its model's most detailed opaque geometry, in the -permutations the object shows, in the model's own space, each vertex bound -to the nodes that move it as the game draws it. first_person_legs.c finds -the waist in it. -*/ - -#ifndef __OBJECT_MESH_H -#define __OBJECT_MESH_H -#pragma once - -enum -{ - OBJECT_MESH_MAXIMUM_NODES = 64, - OBJECT_MESH_MAXIMUM_VERTICES = 16384, - OBJECT_MESH_MAXIMUM_TRIANGLES = 24576, -}; - -struct object_mesh_vertex -{ - real_point3d position; /* the model's space (its default pose) */ - byte nodes[2]; - short weight; /* of nodes[0], of 32767 (the rest nodes[1]'s) */ -}; - -struct object_mesh -{ - long key; /* NONE: none */ - long model_index; - short node_count; - long vertex_count; - long triangle_count; - struct object_mesh_vertex *vertices; - unsigned short (*triangles)[3]; - /* each node's default inverse: the model's space to the node's */ - real_matrix4x3 inverse[OBJECT_MESH_MAXIMUM_NODES]; -}; - -/* the object's mesh as it shows now, or NULL (no model, or none that can be -read). The last one read is kept, until another is asked for: its memory is -taken the first time one is */ -struct object_mesh const *object_mesh_get( - long object_index); - -/* forget the mesh kept (a new map) */ -void object_mesh_reset( - void); - -#endif // __OBJECT_MESH_H diff --git a/port/linux/game/overshield_effect.c b/port/linux/game/overshield_effect.c index 6c758ab8ae..74fda1babf 100644 --- a/port/linux/game/overshield_effect.c +++ b/port/linux/game/overshield_effect.c @@ -1,7 +1,7 @@ /* OVERSHIELD_EFFECT.C -The overshield, as this machine draws it (Video Setup > Graphics > +The overshield, as this machine draws it (Video Setup > Extra Effects > Overshield, display.overshield_effect; off, the game's own): - As it charges, the shield's flare rises up the body from the feet to the @@ -10,10 +10,10 @@ Overshield, display.overshield_effect; off, the game's own): a full shield, or 3 seconds when the shield was down (the charge's from nothing); from any other shield, 2. Meanwhile the shield's own flares (its hits, its recharge) are not drawn over it. -- The flare's energy moves at 30% of its speed, in the overshield's own - color (the powerup's), whatever shield color its player chose. -- On the first-person arms (with display.viewmodel_shield) it comes up as - the rise reaches them, and stays. +- The flare's energy moves at 30% of its speed. Above 200% shield it is + green; the remaining layer through 200% is reddish-pink. +- On the first-person arms (with display.viewmodel_shield, + viewmodel_shield.c) it comes up as the rise passes them, and stays. - A hit on it plays what a hit on an Elite's shield plays (the hitting projectile's own effect for an Elite's energy shield: its sound, sparks and light), when the map has it. @@ -31,6 +31,8 @@ from below its lowest node to above its highest. #include "cseries.h" #include "real_math.h" +#include "shield_look.h" +#include "overshield_effect.h" #include "objects/objects.h" #include "objects/object_definitions.h" #include "models/model_definitions.h" @@ -46,13 +48,11 @@ from below its lowest node to above its highest. #include "sound/sound_definitions.h" #include "objects/light_definitions.h" #include "network_shield_effects.h" - -/* port/linux/game/view_fov.c */ -boolean viewmodel_shield_is_visible(void); +#include enum { - _shader_type_transparent_plasma_glow = 10, /* (shader_get_and_verify_type's plasma, as shield_glow.c has it) */ + _shader_type_transparent_plasma_glow = 10, /* shader_get_and_verify_type's plasma */ OVERSHIELD_EFFECT_MAXIMUM = 16, OVERSHIELD_EFFECT_MODELS = 8, }; @@ -67,15 +67,18 @@ from a down one (the charge's own times: 2 and 3 of shield a second) */ #define OVERSHIELD_EFFECT_ENERGY_SPEED 0.3f /* the soft edge, as a share of the body's height */ #define OVERSHIELD_EFFECT_EDGE 0.12f -/* where on the rise the arms come up, and over how much of it */ +/* where on the rise the arms come up (the chest and shoulders: the rise +counts from the edge below the feet to the edge over the head), and over +how much of it */ #define OVERSHIELD_EFFECT_ARMS_START 0.55f #define OVERSHIELD_EFFECT_ARMS_LENGTH 0.3f /* effects.c's _effect_definition_must_be_deterministic_bit, of an effect definition's flags (its enum is effects.c's own) */ #define EFFECT_MUST_BE_DETERMINISTIC_BIT 1 -/* the overshield's color: the powerup's */ +/* Remaining overshield layers: inner reddish-pink, outer green. */ static real_rgb_color const overshield_effect_rgb = { 0.992f, 0.306f, 0.455f }; /* (253, 78, 116) */ +static real_rgb_color const overshield_effect_outer_rgb = { 0.306f, 0.992f, 0.455f }; /* (78, 253, 116) */ /* the plasma shader's fields after its header (rasterizer_xbox_plasma_energy.c's) */ struct overshield_effect_plasma @@ -90,10 +93,13 @@ struct overshield_effect real start; /* the game's seconds (render_interpolation_game_time_sec) */ real rise; real last_seen; + real shield_vitality; /* current layer, shared by body and arms */ /* the values the unit's modifier shader is drawn with, its intensity's - full: one copy for the body, one for the arms */ + full */ real body_values[4]; - real arms_values[4]; + /* the first-person arms' copy, which viewmodel_shield.c keeps (NULL: + none) */ + real const *arms_values; /* this frame's: how far up (0..1, eased), and the model's heights */ real progress; real bottom; @@ -118,24 +124,43 @@ static short overshield_effect_next_model = 0; int config_boolean(const char *name); unsigned long config_changes(void); +/* Model tags and queued draw identities never cross a map or light-array reset. */ +void overshield_effect_reset(void) +{ + short i; + memset(overshield_effects, 0, sizeof(overshield_effects)); + for (i = 0; i < OVERSHIELD_EFFECT_MAXIMUM; i++) + overshield_effects[i].unit_index = NONE; + memset(overshield_effect_models, 0, sizeof(overshield_effect_models)); + for (i = 0; i < OVERSHIELD_EFFECT_MODELS; i++) + overshield_effect_models[i].model_index = NONE; + overshield_effect_next_model = 0; + overshield_effects_initialized = TRUE; +} + +static real_rgb_color const *overshield_effect_layer_color(struct overshield_effect const *effect) +{ + return effect->shield_vitality > 2.f ? &overshield_effect_outer_rgb : &overshield_effect_rgb; +} + /* display.overshield_effect; in a network game, the host's (network_shield_effects.c) */ -static boolean overshield_effect_enabled( - void) +static boolean overshield_effect_enabled(void) { static unsigned long changes = (unsigned long)-1; - static boolean enabled = FALSE; + static boolean local_enabled = FALSE; short effects = network_shield_effects(); - - if (effects != NONE) - { - changes = (unsigned long)-1; - return effects >= _shield_effects_overshield; - } + boolean enabled; if (changes != config_changes()) { changes = config_changes(); - enabled = config_boolean("display.overshield_effect") != 0; + local_enabled = config_boolean("display.overshield_effect") != 0; + } + enabled = effects != NONE ? effects >= _shield_effects_overshield : local_enabled; + if (!enabled && overshield_effects_initialized) + { + overshield_effect_reset(); + overshield_effects_initialized = FALSE; } return enabled; } @@ -209,6 +234,8 @@ static short overshield_effect_intensity_source( if (!definition || definition->object.modifier_shader.index == NONE) return NONE; shader = shader_definition_get(definition->object.modifier_shader.index); + /* The selected appearance also owns the animated intensity channel. */ + shader = shield_look_body(unit_index, shader); if (!shader || shader->base.type != _shader_type_transparent_plasma_glow) return NONE; source = ((struct overshield_effect_plasma const *)((byte const *)shader + sizeof(struct shader)))-> @@ -228,28 +255,24 @@ static struct overshield_effect *overshield_effect_get( real now; short index; + if (!overshield_effect_enabled()) + return NULL; if (!overshield_effects_initialized) - { - for (index = 0; index < OVERSHIELD_EFFECT_MAXIMUM; index++) - overshield_effects[index].unit_index = NONE; - for (index = 0; index < OVERSHIELD_EFFECT_MODELS; index++) - overshield_effect_models[index].model_index = NONE; - overshield_effects_initialized = TRUE; - } + overshield_effect_reset(); now = global_frame_parameters.game_time_sec; for (index = 0; index < OVERSHIELD_EFFECT_MAXIMUM; index++) { struct overshield_effect *each = &overshield_effects[index]; /* (one not looked at for a while: its unit gone, or out of sight) */ - if (each->unit_index != NONE && (now - each->last_seen > 1.f || now < each->last_seen - 1.f)) + if (each->unit_index != NONE && (now - each->last_seen > 1.f || now < each->last_seen)) each->unit_index = NONE; if (each->unit_index == unit_index) effect = each; else if (each->unit_index == NONE && !free_effect) free_effect = each; } - if (!unit || !overshield_effect_enabled()) + if (!unit) return NULL; charging = TEST_FLAG(unit->object.damage_flags, _object_shield_over_charging_bit); if (TEST_FLAG(unit->object.damage_flags, _object_dead_bit) || @@ -267,6 +290,7 @@ static struct overshield_effect *overshield_effect_get( return NULL; effect = free_effect; effect->unit_index = unit_index; + effect->arms_values = NULL; effect->rise = charging && shield <= OVERSHIELD_EFFECT_DOWN ? OVERSHIELD_EFFECT_RISE_FROM_DOWN : OVERSHIELD_EFFECT_RISE; /* (seen part of the way through its charge: as far on; seen charged, @@ -278,6 +302,7 @@ static struct overshield_effect *overshield_effect_get( effect->start = now - MIN(shield - 1.f, effect->rise); } effect->last_seen = now; + effect->shield_vitality = unit->object.shield_vitality; { real t = PIN((now - effect->start) / effect->rise, 0.f, 1.f); @@ -299,12 +324,11 @@ boolean overshield_effect_active( } /* the values a unit's modifier shader is drawn with, given its own: with an -overshield, a copy whose intensity is full (on the body, or the arms) that +overshield, a copy whose intensity is full on the body that overshield_effect_draw knows again; otherwise its own */ real const *overshield_effect_values( long unit_index, - real const *values, - boolean arms) + real const *values) { struct overshield_effect *effect; short source; @@ -316,70 +340,92 @@ real const *overshield_effect_values( source = effect ? overshield_effect_intensity_source(unit_index) : NONE; if (!effect || source == NONE) return values; - copy = arms ? effect->arms_values : effect->body_values; + copy = effect->body_values; csmemcpy(copy, values, sizeof(effect->body_values)); - if (arms) + copy[source] = 1.f; + if (!overshield_effect_model_heights( + object_definition_get(object_get(unit_index)->definition_index)->object.model.index, + &effect->bottom, &effect->top)) { - copy[source] = PIN((effect->progress - OVERSHIELD_EFFECT_ARMS_START) / OVERSHIELD_EFFECT_ARMS_LENGTH, 0.f, 1.f); - } - else - { - copy[source] = 1.f; - if (!overshield_effect_model_heights( - object_definition_get(object_get(unit_index)->definition_index)->object.model.index, - &effect->bottom, &effect->top)) - { - effect->bottom = effect->top = 0.f; - } + effect->bottom = effect->top = 0.f; } return copy; } -/* a plasma shader drawn with values from overshield_effect_values: the -speed its energy moves at, and the height it fades above on its model (the -fade's inverse softness and height: 0 and 0 for none); FALSE for values not -from it */ -boolean overshield_effect_draw( +/* the values a unit's first-person arms' modifier shader is drawn with, +given its own, written to arms (viewmodel_shield.c's copy): with an +overshield, its intensity coming up as the rise passes the arms, and TRUE +(overshield_effect_draw then knows arms again); otherwise FALSE, and arms +not written */ +boolean overshield_effect_arms_values( + long unit_index, real const *values, - real *energy_speed, - real *inverse_softness, - real *height) + real *arms) { + struct overshield_effect *effect; + short source; short index; - if (!values) + /* (another unit's overshield no longer draws on these arms) */ + for (index = 0; index < OVERSHIELD_EFFECT_MAXIMUM; index++) + { + if (overshield_effects[index].arms_values == arms) + overshield_effects[index].arms_values = NULL; + } + if (!values || !overshield_effect_enabled()) + return FALSE; + effect = overshield_effect_get(unit_index); + source = effect ? overshield_effect_intensity_source(unit_index) : NONE; + if (!effect || source == NONE) return FALSE; + csmemcpy(arms, values, sizeof(effect->body_values)); + arms[source] = PIN((effect->progress - OVERSHIELD_EFFECT_ARMS_START) / OVERSHIELD_EFFECT_ARMS_LENGTH, 0.f, 1.f); + effect->arms_values = arms; + return TRUE; +} + +/* Queued body and arms draws share the same identity and activation rules. */ +static struct overshield_effect const *overshield_effect_find_values(real const *values) +{ + short index; + if (!values || !overshield_effect_enabled()) + return NULL; for (index = 0; index < OVERSHIELD_EFFECT_MAXIMUM; index++) { struct overshield_effect const *effect = &overshield_effects[index]; - - if (effect->unit_index == NONE || (values != effect->body_values && values != effect->arms_values)) - continue; - *energy_speed = OVERSHIELD_EFFECT_ENERGY_SPEED; - *inverse_softness = 0.f; - *height = 0.f; - if (values == effect->body_values && effect->top > effect->bottom && effect->progress < 1.f) - { - real edge = OVERSHIELD_EFFECT_EDGE * (effect->top - effect->bottom); - - /* (from all of the edge below the feet to all of it above the - head) */ - *inverse_softness = 1.f / edge; - *height = effect->bottom + (effect->top - effect->bottom + edge) * effect->progress; - } - return TRUE; + if (effect->unit_index != NONE && (values == effect->body_values || values == effect->arms_values)) + return effect; } - return FALSE; + return NULL; } -/* the unit's overshield's flare, for its glow (shield_glow.c): 0..1, or -NONE (-1) for no overshield */ -real overshield_effect_flare( - long unit_index) +/* a plasma shader drawn with values from overshield_effect_values (or +overshield_effect_arms_values, with no fade): the speed its energy moves +at, and the height it fades above on its model (the fade's inverse softness +and height: 0 and 0 for none); FALSE for values not from it */ +boolean overshield_effect_draw( + real const *values, + real *energy_speed, + real *inverse_softness, + real *height) { - struct overshield_effect *effect = overshield_effect_get(unit_index); + struct overshield_effect const *effect = overshield_effect_find_values(values); + if (!effect) + return FALSE; + *energy_speed = OVERSHIELD_EFFECT_ENERGY_SPEED; + *inverse_softness = 0.f; + *height = 0.f; + /* (the arms come up whole: they are not on the body's heights) */ + if (values == effect->body_values && effect->top > effect->bottom && effect->progress < 1.f) + { + real edge = OVERSHIELD_EFFECT_EDGE * (effect->top - effect->bottom); - return effect ? effect->progress : -1.f; + /* (from all of the edge below the feet to all of it above the + head) */ + *inverse_softness = 1.f / edge; + *height = effect->bottom + (effect->top - effect->bottom + edge) * effect->progress; + } + return TRUE; } /* whether an effect a hit on an overshield may play in place of its own: @@ -422,22 +468,42 @@ boolean overshield_effect_hit_effect_allowed( } /* the color a plasma shader drawn with values from overshield_effect_values -is drawn in, the overshield's own; FALSE for values not from it */ +(or overshield_effect_arms_values) is drawn in, the overshield's own; FALSE +for values not from it */ boolean overshield_effect_color( real const *values, - real_rgb_color *color) + real_rgb_color *perpendicular, + real_rgb_color *parallel) { - real energy_speed, inverse_softness, height; + struct overshield_effect const *effect = overshield_effect_find_values(values); + real peak; + real perpendicular_brightness; + real parallel_brightness; + real_rgb_color const *color; - if (!overshield_effect_draw(values, &energy_speed, &inverse_softness, &height)) + if (!effect) return FALSE; - *color = overshield_effect_rgb; + color = overshield_effect_layer_color(effect); + /* Keep the shader's brightness while using the overshield effect's hue. */ + peak = MAX(color->red, MAX(color->green, color->blue)); + perpendicular_brightness = MAX(perpendicular->red, MAX(perpendicular->green, perpendicular->blue)); + parallel_brightness = MAX(parallel->red, MAX(parallel->green, parallel->blue)); + perpendicular->red = color->red / peak * perpendicular_brightness; + perpendicular->green = color->green / peak * perpendicular_brightness; + perpendicular->blue = color->blue / peak * perpendicular_brightness; + parallel->red = color->red / peak * parallel_brightness; + parallel->green = color->green / peak * parallel_brightness; + parallel->blue = color->blue / peak * parallel_brightness; return TRUE; } -/* the overshield's color, for its glow */ -real_rgb_color const *overshield_effect_glow_color( - void) +/* One sample supplies both layer hue and visible charge coverage to lighting. */ +boolean overshield_effect_light_sample(long unit_index, real_rgb_color *color, real *coverage) { - return &overshield_effect_rgb; + struct overshield_effect *effect = overshield_effect_get(unit_index); + if (!effect) + return FALSE; + *color = *overshield_effect_layer_color(effect); + *coverage = effect->progress; + return TRUE; } diff --git a/port/linux/game/overshield_effect.h b/port/linux/game/overshield_effect.h new file mode 100644 index 0000000000..9b15e0349c --- /dev/null +++ b/port/linux/game/overshield_effect.h @@ -0,0 +1,5 @@ +#ifndef OVERSHIELD_EFFECT_H +#define OVERSHIELD_EFFECT_H +void overshield_effect_reset(void); +boolean overshield_effect_light_sample(long unit_index, real_rgb_color *color, real *coverage); +#endif diff --git a/port/linux/game/plasma_collision.c b/port/linux/game/plasma_collision.c new file mode 100644 index 0000000000..e331ff5fcc --- /dev/null +++ b/port/linux/game/plasma_collision.c @@ -0,0 +1,382 @@ +/* A depth-only batch for the visibility field. The simulation cannot advance + during these synchronous render queries. Cache cluster membership and object + metadata for this batch, but use the engine's exact BSP/model intersection + routines for every ray. Overflow or unsupported inputs use the stock query. */ +#include "cseries.h" +#include "plasma_collision.h" +#include "physics/collisions.h" +#include "physics/collision_bsp.h" +#include "physics/collision_bsp_definitions.h" +#include "physics/collision_models.h" +#include "physics/breakable_surfaces.h" +#include "objects/objects.h" +#include "structures/structure_bsp_definitions.h" +#include "scenario/scenario.h" +#include +#include + +extern boolean debug_collision_skip_vectors, debug_collision_skip_objects; + +enum { TRACE_OBJECTS = 512, TRACE_REFERENCES = 4096 }; +struct trace_object +{ + long index, next, child; + real_point3d center; + real radius; + real_point3d relative; + real sphere_distance; + int eligible, model_state; + struct collision_model_instance model; + unsigned int pending[PLASMA_COLLISION_WORDS]; +}; +static struct +{ + int active, failed, count, references, defer_models; + unsigned long flags, ray; + long ignore; + real_point3d const *point; + struct structure_bsp const *structure; + struct collision_bsp const *bsp; + real extent; + real vector_squared; + struct { int ready; long node; short depth; } prefixes[8]; + struct collision_bsp_vector_cache cache[8]; + struct trace_object objects[TRACE_OBJECTS]; + unsigned short lookup[MAXIMUM_OBJECTS_PER_MAP]; + unsigned long visited[MAXIMUM_OBJECTS_PER_MAP]; + struct { int ready, first, count; unsigned long visited; } clusters[MAXIMUM_CLUSTERS_PER_STRUCTURE]; + long roots[TRACE_REFERENCES]; +} batch; + +/* All endpoints, and the origin, must lie strictly on the same side. + The margin leaves rounding and borderline planes to engine traversal. */ +static int trace_side(real_plane3d const *plane, real distance, int octant) +{ + real bound, margin, low, high, components[3]; + int axis; + bound = batch.extent * (fabsf(plane->n.i) + fabsf(plane->n.j) + fabsf(plane->n.k)); + margin = 0.0001f * (1 + bound + fabsf(plane->d) + fabsf(plane->n.i * batch.point->x) + + fabsf(plane->n.j * batch.point->y) + fabsf(plane->n.k * batch.point->z)); + low = high = distance; + components[0] = plane->n.i; + components[1] = plane->n.j; + components[2] = plane->n.k; + for (axis = 0; axis < 3; axis++) + { + real endpoint = components[axis] * ((octant & (1 << axis)) ? batch.extent : -batch.extent); + if (endpoint < 0) low += endpoint; + else high += endpoint; + } + return low > margin ? 1 : high < -margin ? 0 : -1; +} + +/* Prepare only the part of the world tree that this ray octant can reach. + One-sided chains below branches are just as invariant as the common root + prefix. Keep exact engine traversal at intersecting/borderline planes. + The bounded cache may evict entries; a miss only loses the optimisation. */ +static void trace_prepare(long index, short depth, int octant, int *work, long *target, short *skipped) +{ + struct bsp3d_node const *node; + real_plane3d const *plane; + real distance; + long child_target, slot; + short child_skipped; + int side; + *target = index; + *skipped = 0; + if (index & LONG_MIN) return; + if (*work <= 0 || index >= batch.bsp->bsp3d.nodes.count || + depth >= MAXIMUM_BSP3D_TRAVERSAL_DEPTH || depth >= batch.bsp->bsp3d.nodes.count) return; + --*work; + node = TAG_BLOCK_GET_ELEMENT(&batch.bsp->bsp3d.nodes, index, struct bsp3d_node); + if (node->plane_designator < 0 || node->plane_designator >= batch.bsp->bsp3d.planes.count) return; + plane = TAG_BLOCK_GET_ELEMENT(&batch.bsp->bsp3d.planes, node->plane_designator, real_plane3d); + distance = plane3d_distance_to_point(plane, batch.point); + side = trace_side(plane, distance, octant); + if (side >= 0) + { + trace_prepare(node->children[side], depth + 1, octant, work, target, skipped); + ++*skipped; + } + else + { + trace_prepare(node->children[0], depth + 1, octant, work, &child_target, &child_skipped); + trace_prepare(node->children[1], depth + 1, octant, work, &child_target, &child_skipped); + } + slot = (unsigned long)index % COLLISION_VECTOR_CACHE_NODES; + batch.cache[octant].nodes[slot].index_plus_one = index + 1; + batch.cache[octant].nodes[slot].node = node; + batch.cache[octant].nodes[slot].plane = plane; + batch.cache[octant].nodes[slot].distance = distance; + batch.cache[octant].nodes[slot].skip_node = *target; + batch.cache[octant].nodes[slot].skip_count = *skipped; +} + +/* Each octant shares the origin and one eighth of the batch's endpoint cube. + Prove its common tree prefix once, then retain the original traversal below + it. Both the origin and the entire endpoint box must be strictly on one + side; convexity then covers every segment. Margins leave borderline planes + to the stock arithmetic. Malformed trees keep the original root entry. */ +static void trace_start(int octant) +{ + long node_index = 0; + short depth = 0; + real extent = batch.extent; + if (!(extent > 0 && extent < 1000)) return; + while (!(node_index & LONG_MIN)) + { + struct bsp3d_node const *node; + real_plane3d const *plane; + real distance; + int side; + if (node_index >= batch.bsp->bsp3d.nodes.count || + depth >= MAXIMUM_BSP3D_TRAVERSAL_DEPTH || depth >= batch.bsp->bsp3d.nodes.count) + return; + node = TAG_BLOCK_GET_ELEMENT(&batch.bsp->bsp3d.nodes, node_index, struct bsp3d_node); + if (node->plane_designator < 0 || node->plane_designator >= batch.bsp->bsp3d.planes.count) + return; + plane = TAG_BLOCK_GET_ELEMENT(&batch.bsp->bsp3d.planes, node->plane_designator, real_plane3d); + distance = plane3d_distance_to_point(plane, batch.point); + side = trace_side(plane, distance, octant); + if (side < 0) break; + node_index = node->children[side]; + depth++; + } + batch.prefixes[octant].node = node_index; + batch.prefixes[octant].depth = depth; +} + +static struct trace_object *trace_object(long index) +{ + unsigned long slot = DATUM_INDEX_TO_ABSOLUTE_INDEX(index); + struct trace_object *cached; + struct object_datum const *object; + real bound, margin; + if (slot >= MAXIMUM_OBJECTS_PER_MAP) { batch.failed = 1; return NULL; } + if (batch.lookup[slot]) + { + cached = &batch.objects[batch.lookup[slot]-1]; + if (cached->index == index) return cached; + batch.failed = 1; + return NULL; + } + if (batch.count == TRACE_OBJECTS) { batch.failed = 1; return NULL; } + object = object_get(index); + cached = &batch.objects[batch.count++]; + batch.lookup[slot] = (unsigned short)batch.count; + cached->index = index; + cached->next = object->object.next_object_index; + cached->child = object->object.first_child_object_index; + cached->center = object->object.bounding_sphere_center; + cached->radius = object->object.bounding_sphere_radius; + cached->relative.x = batch.point->x - cached->center.x; + cached->relative.y = batch.point->y - cached->center.y; + cached->relative.z = batch.point->z - cached->center.z; + cached->sphere_distance = cached->relative.x * cached->relative.x + + cached->relative.y * cached->relative.y + cached->relative.z * cached->relative.z - cached->radius * cached->radius; + cached->eligible = index != batch.ignore && !TEST_FLAG(object->object.flags, _object_invisible_bit) && + TEST_FLAG(batch.flags, object->object.type + _collision_test_objects_first_type_bit); + /* Every ray endpoint stays inside the batch cube. Reject a disjoint + sphere once per batch, rather than rechecking it for every ray. Leave + borderline and invalid bounds to the original sphere arithmetic. */ + bound = batch.extent + cached->radius; + margin = 0.0001f * (1 + fabsf(batch.point->x) + fabsf(batch.point->y) + + fabsf(batch.point->z) + fabsf(bound)); + if (cached->radius >= 0 && batch.extent > 0 && + (fabsf(cached->center.x - batch.point->x) > bound + margin || + fabsf(cached->center.y - batch.point->y) > bound + margin || + fabsf(cached->center.z - batch.point->z) > bound + margin)) + cached->eligible = FALSE; + return cached; +} + +/* The same finite-segment predicate as fast_vector_intersects_sphere. Its + origin/sphere terms are constant for the batch and its vector length is + constant for the ray. Keep the original arithmetic and strict comparisons, + including tangencies; only move invariant work out of the object loop. */ +static int trace_sphere(struct trace_object const *object, real_vector3d const *vector) +{ + real b, disc, neg_a_minus_b; + if (object->sphere_distance < 0.f) return TRUE; + b = vector->i * object->relative.x + vector->j * object->relative.y + vector->k * object->relative.z; + if (b >= 0.f) return FALSE; + disc = b * b - batch.vector_squared * object->sphere_distance; + if (disc <= 0.f) return FALSE; + neg_a_minus_b = -batch.vector_squared - b; + return neg_a_minus_b < 0.f || neg_a_minus_b * neg_a_minus_b < disc; +} + +static void trace_objects(long index, real_vector3d const *vector, real *depth, int nesting) +{ + int siblings = 0; + if (nesting >= TRACE_OBJECTS) { batch.failed = 1; return; } + while (index != NONE && !batch.failed) + { + struct trace_object *object = trace_object(index); + if (!object) return; + if (++siblings > TRACE_OBJECTS) { batch.failed = 1; return; } + if (object->eligible && trace_sphere(object, vector)) + { + if (batch.defer_models) + object->pending[(batch.ray - 1) / 32] |= 1U << ((batch.ray - 1) % 32); + else + { + struct collision_model_test_vector_result result; + if (!object->model_state) + object->model_state = collision_model_instance_new(&object->model, index) ? 1 : -1; + if (object->model_state > 0 && collision_model_test_vector(&object->model, + FLAG(_collision_test_front_facing_surfaces_bit) | FLAG(_collision_test_back_facing_surfaces_bit), + batch.point, vector, &result) && *depth > result.bsp_result.t) + *depth = result.bsp_result.t; + } + /* Children are tested only after the parent's eligibility and sphere, + exactly as in object_test_vector; siblings are always considered. */ + if (object->child != NONE) trace_objects(object->child, vector, depth, nesting+1); + } + index = object->next; + } +} + +static void trace_cluster(long cluster, real_vector3d const *vector, real *depth) +{ + int i; + if (batch.clusters[cluster].visited == batch.ray) return; + batch.clusters[cluster].visited = batch.ray; + if (!batch.clusters[cluster].ready) + { + long reference, index; + batch.clusters[cluster].first = batch.references; + for (index = cluster_get_first_collideable_object(&reference, (short)cluster); index != NONE; + index = cluster_get_next_collideable_object(&reference)) + { + struct trace_object *object = trace_object(index); + if (!object) return; + if (!object->eligible && object->next == NONE) continue; + if (batch.references == TRACE_REFERENCES) { batch.failed = 1; return; } + batch.roots[batch.references++] = index; + } + batch.clusters[cluster].count = batch.references - batch.clusters[cluster].first; + batch.clusters[cluster].ready = 1; + } + for (i = 0; i < batch.clusters[cluster].count && !batch.failed; i++) + { + long index = batch.roots[batch.clusters[cluster].first+i]; + unsigned long slot = DATUM_INDEX_TO_ABSOLUTE_INDEX(index); + if (batch.visited[slot] != batch.ray) + { + batch.visited[slot] = batch.ray; + trace_objects(index, vector, depth, 0); + } + } +} + +void plasma_collision_begin(unsigned long flags, real_point3d const *point, long ignore) +{ + unsigned long supported = FLAG(_collision_test_structure_bit) | FLAG(_collision_test_objects_bit) | + FLAG(_collision_test_front_facing_surfaces_bit) | FLAG(_collision_test_back_facing_surfaces_bit) | + FLAG(_collision_test_objects_scenery_bit) | FLAG(_collision_test_objects_machines_bit); + memset(&batch, 0, sizeof(batch)); + batch.active = flags == supported || flags == (supported | FLAG(_collision_test_objects_vehicles_bit)); + batch.flags = flags; + batch.point = point; + batch.ignore = ignore; + if (batch.active) + { + batch.structure = global_structure_bsp_get(); + batch.bsp = global_collision_bsp_get(); + } +} + +float plasma_collision_depth(unsigned long flags, real_point3d const *point, real_vector3d const *vector, long ignore) +{ + struct collision_result fallback; + struct collision_bsp_test_vector_result result; + real depth = 1.0f; + int i, hit, use_start, octant; + if (!batch.active || batch.failed || flags != batch.flags || point != batch.point || ignore != batch.ignore) + goto stock; + if (debug_collision_skip_vectors) return 2.0f; + if (!batch.ray) batch.extent = MAX(fabsf(vector->i), MAX(fabsf(vector->j), fabsf(vector->k))); + use_start = fabsf(vector->i) <= batch.extent && fabsf(vector->j) <= batch.extent && + fabsf(vector->k) <= batch.extent; + /* Cached object rejection applies only inside the original cube. */ + if (!use_start) goto stock; + octant = (vector->i >= 0) | ((vector->j >= 0) << 1) | ((vector->k >= 0) << 2); + if (!batch.prefixes[octant].ready) + { + long target; + short skipped; + int work = COLLISION_VECTOR_CACHE_NODES; + batch.prefixes[octant].ready = 1; + trace_start(octant); + if (batch.extent > 0 && batch.extent < 1000) + trace_prepare(batch.prefixes[octant].node, batch.prefixes[octant].depth, octant, &work, &target, &skipped); + } + batch.ray++; + batch.vector_squared = vector->i * vector->i + vector->j * vector->j + vector->k * vector->k; + hit = collision_bsp_test_vector_from_node(FLAG(_collision_test_front_facing_surfaces_bit) | + FLAG(_collision_test_back_facing_surfaces_bit), batch.bsp, + MAXIMUM_BREAKABLE_SURFACES_PER_MAP, breakable_surface_flags_get(), point, vector, REAL_MAX, &result, + batch.prefixes[octant].node, batch.prefixes[octant].depth, &batch.cache[octant]); + if (hit) depth = result.t; + if (!debug_collision_skip_objects) + for (i = 0; i < result.leaf_count && !batch.failed; i++) + { + long leaf = result.leaf_indices[i], cluster; + if (leaf == NONE) continue; + if ((leaf & LONG_MAX) >= batch.structure->leaves.count) goto stock; + cluster = TAG_BLOCK_GET_ELEMENT(&batch.structure->leaves, leaf & LONG_MAX, struct structure_leaf)->cluster_index; + if (cluster < 0 || cluster >= MAXIMUM_CLUSTERS_PER_STRUCTURE) continue; + trace_cluster(cluster, vector, &depth); + } + if (batch.failed) goto stock; + return hit || depth < 1.0f ? depth : 2.0f; +stock: + if (batch.defer_models) batch.failed = 1; + return collision_test_vector(flags, point, vector, ignore, &fallback) ? fallback.t : 2.0f; +} + +void plasma_collision_depths(unsigned long flags, real_point3d const *point, + real_vector3d const *vectors, int count, long ignore, float *depths) +{ + int ray, object_index, word; + plasma_collision_begin(flags, point, ignore); + batch.defer_models = count > 0 && count <= PLASMA_COLLISION_RAYS; + if (batch.active && batch.defer_models) + { + /* Preserve cluster, sphere and parent/child gates for every ray. Only + defer the expensive model queries; a bitset deduplicates identical + queries reached through more than one object/cluster reference. */ + for (ray = 0; ray < count && !batch.failed; ray++) + depths[ray] = plasma_collision_depth(flags, point, &vectors[ray], ignore); + if (!batch.failed) + for (object_index = 0; object_index < batch.count; object_index++) + { + struct trace_object *object = &batch.objects[object_index]; + for (word = 0; word < (count + 31) / 32; word++) + if (object->pending[word]) break; + if (word == (count + 31) / 32) continue; + if (collision_model_instance_new(&object->model, object->index)) + plasma_collision_model_depths(&object->model, point, vectors, count, object->pending, depths); + } + } + else batch.failed = 1; + if (batch.failed) + for (ray = 0; ray < count; ray++) + { + struct collision_result result; + depths[ray] = collision_test_vector(flags, point, &vectors[ray], ignore, &result) ? result.t : 2.0f; + } + plasma_collision_end(); +} + +void plasma_collision_end(void) +{ + /* Model instances borrow tag and object matrices only during the batch. */ + memset(batch.objects, 0, (size_t)batch.count * sizeof(batch.objects[0])); + batch.active = 0; + batch.point = NULL; + batch.structure = NULL; + batch.bsp = NULL; + memset(&batch.cache, 0, sizeof(batch.cache)); +} diff --git a/port/linux/game/plasma_collision_models.c b/port/linux/game/plasma_collision_models.c new file mode 100644 index 0000000000..ffcd1dfce5 --- /dev/null +++ b/port/linux/game/plasma_collision_models.c @@ -0,0 +1,71 @@ +/* The model-major phase of render-only ray batches. The stock query transforms + the same origin and looks up the same node/permutation for each ray. Here + one node serves all eligible rays before its borrowed data is discarded. */ +#include "cseries.h" +#include "plasma_collision.h" +#include "physics/collisions.h" +#include "physics/collision_bsp.h" +#include "physics/collision_bsp_definitions.h" +#include "physics/collision_model_definitions.h" +#include "physics/collision_models.h" +#include "objects/object_definitions.h" +#include + +void plasma_collision_model_depths(struct collision_model_instance const *instance, + real_point3d const *point, real_vector3d const *vectors, int count, + unsigned int const *pending, float *depths) +{ + real closest[PLASMA_COLLISION_RAYS]; + struct collision_bsp_vector_cache cache; + unsigned long flags = FLAG(_collision_test_front_facing_surfaces_bit) | FLAG(_collision_test_back_facing_surfaces_bit); + int ray; + short node_index; + /* Invalid regions keep the original diagnostics and query behavior. + Validate before changing any output, so fallback cannot mix results. */ + if (count < 1 || count > PLASMA_COLLISION_RAYS) goto fallback; + for (node_index = 0; node_index < instance->node_count; node_index++) + { + struct collision_node const *node = TAG_BLOCK_GET_ELEMENT(&instance->model->nodes, node_index, struct collision_node); + if (node->region_index != NONE && (node->region_index < 0 || node->region_index >= MAXIMUM_REGIONS_PER_OBJECT)) goto fallback; + } + for (ray = 0; ray < count; ray++) closest[ray] = REAL_MAX; + for (node_index = 0; node_index < instance->node_count; node_index++) + { + struct collision_node const *node = TAG_BLOCK_GET_ELEMENT(&instance->model->nodes, node_index, struct collision_node); + short permutation; + struct collision_bsp const *bsp; + real_matrix4x3 inverse; + real_point3d origin; + if (node->region_index == NONE) continue; + permutation = instance->region_permutation_indices[node->region_index]; + if (permutation == NONE || node->bsps.count <= 0) continue; + permutation = PIN(permutation, 0, node->bsps.count - 1); + bsp = TAG_BLOCK_GET_ELEMENT(&node->bsps, permutation, struct collision_bsp); + if (bsp->bsp3d.nodes.count <= 0) continue; + matrix4x3_inverse(&instance->matrices[node_index], &inverse); + matrix4x3_transform_point(&inverse, point, &origin); + memset(&cache, 0, sizeof(cache)); + for (ray = 0; ray < count; ray++) + if (pending[ray / 32] & (1U << (ray % 32))) + { + real_vector3d vector; + struct collision_bsp_test_vector_result result; + matrix4x3_transform_vector(&inverse, &vectors[ray], &vector); + /* Same node order and nearest-node limit as the original model + query. Cache only the fixed BSP/origin inside this node. */ + if (collision_bsp_test_vector_from_node(flags, bsp, 0, NULL, &origin, &vector, + closest[ray], &result, 0, 0, &cache)) closest[ray] = result.t; + } + } + for (ray = 0; ray < count; ray++) + if (closest[ray] < 1.0f && closest[ray] < depths[ray]) depths[ray] = closest[ray]; + return; +fallback: + for (ray = 0; ray < count; ray++) + if (pending[ray / 32] & (1U << (ray % 32))) + { + struct collision_model_test_vector_result result; + if (collision_model_test_vector(instance, flags, point, &vectors[ray], &result) && + result.bsp_result.t < 1.0f && result.bsp_result.t < depths[ray]) depths[ray] = result.bsp_result.t; + } +} diff --git a/port/linux/game/plasma_collision_scene.c b/port/linux/game/plasma_collision_scene.c new file mode 100644 index 0000000000..971e9ae723 --- /dev/null +++ b/port/linux/game/plasma_collision_scene.c @@ -0,0 +1,98 @@ +/* Exact collision-input snapshots for stationary visibility fields. Store + values, never borrowed object/tag pointers. Moving lights still trace at + their existing cadence; any changed blocker invalidates stationary reuse. */ +#include "cseries.h" +#include "objects/objects.h" +#include "physics/breakable_surfaces.h" +#include "physics/collision_models.h" +#include "scenario/scenario.h" +#include "plasma_collision.h" +#include +#include + +extern boolean debug_collision_skip_vectors, debug_collision_skip_objects; +static int scene_append(struct plasma_collision_scene *scene, int *offset, const void *data, int size) +{ + int changed; + if (*offset < 0 || size < 0 || size > PLASMA_COLLISION_SCENE_BYTES - *offset || (!data && size)) + { + *offset = -1; + return TRUE; + } + if (!size) return FALSE; + changed = *offset + size > scene->size || memcmp(scene->bytes + *offset, data, size); + if (changed) memcpy(scene->bytes + *offset, data, size); + *offset += size; + return changed; +} + +unsigned long plasma_collision_scene_revision(struct plasma_collision_scene *scene, + real_point3d const *point, float extent, int vehicles) +{ + struct object_iterator iterator; + struct object_datum *object; + unsigned long mask = _object_mask_scenery | _object_mask_machine; + int offset = 0, changed = FALSE; +#define SNAPSHOT(value) changed |= scene_append(scene, &offset, &(value), sizeof(value)) + SNAPSHOT(global_scenario_index); + SNAPSHOT(global_structure_bsp_index); + SNAPSHOT(debug_collision_skip_vectors); + SNAPSHOT(debug_collision_skip_objects); + changed |= scene_append(scene, &offset, breakable_surface_flags_get(), MAXIMUM_BREAKABLE_SURFACES_PER_MAP / 8); + if (vehicles) mask |= _object_mask_vehicle; + object_iterator_new(&iterator, mask, 0); + while ((object = object_iterator_next(&iterator)) != NULL && offset >= 0) + { + unsigned long eligibility = object->object.flags & (FLAG(_object_invisible_bit) | FLAG(_object_has_collision_model_bit)); + int connected = object->object.first_cluster_reference_index != NONE; + struct collision_model_instance model; + struct object_cluster_iterator clusters; + short cluster; + int has_model; + real bound = extent + object->object.bounding_sphere_radius; + real margin = 0.0001f * (1 + fabsf(point->x) + fabsf(point->y) + fabsf(point->z) + fabsf(bound)); + /* Every ray stays in this cube. Objects outside it cannot pass the + engine's sphere gate. Include a margin and all borderline/invalid + bounds; unrelated animated doors must not invalidate every light. */ + if (object->object.bounding_sphere_radius >= 0 && bound >= 0 && (fabsf(object->object.bounding_sphere_center.x - point->x) > bound + margin || + fabsf(object->object.bounding_sphere_center.y - point->y) > bound + margin || + fabsf(object->object.bounding_sphere_center.z - point->z) > bound + margin)) + continue; + SNAPSHOT(iterator.index); + SNAPSHOT(object->definition_index); + SNAPSHOT(eligibility); + SNAPSHOT(connected); + SNAPSHOT(object->object.type); + /* Compare actual cluster membership, not allocation handles. Include + its terminator so changed list lengths cannot alias following data. */ + cluster = object_get_first_cluster(&clusters, iterator.index); + for (;;) + { + SNAPSHOT(cluster); + if (cluster == NONE || offset < 0) break; + cluster = object_get_next_cluster(&clusters, iterator.index); + } + SNAPSHOT(object->object.next_object_index); + SNAPSHOT(object->object.first_child_object_index); + SNAPSHOT(object->object.parent_object_index); + SNAPSHOT(object->object.bounding_sphere_center); + SNAPSHOT(object->object.bounding_sphere_radius); + SNAPSHOT(object->object.region_permutations); + has_model = collision_model_instance_new(&model, iterator.index); + SNAPSHOT(has_model); + if (has_model) + { + SNAPSHOT(model.node_count); + /* Visual-only nodes cannot change collision. Use the exact node + count/poses accepted by the engine's collision instance. */ + changed |= scene_append(scene, &offset, model.matrices, model.node_count * sizeof(real_matrix4x3)); + } + } +#undef SNAPSHOT + /* Overflow takes the uncached path on every view. No incomplete snapshot + can certify unchanged geometry. Object insertion/removal changes size. */ + if (changed || offset != scene->size || offset < 0 || !scene->revision) + scene->revision++; + scene->size = MAX(offset, 0); + return scene->revision; +} diff --git a/port/linux/game/plasma_falloff.c b/port/linux/game/plasma_falloff.c new file mode 100644 index 0000000000..0df61205d8 --- /dev/null +++ b/port/linux/game/plasma_falloff.c @@ -0,0 +1,139 @@ +/* Feature-owned attenuation for the existing additive world-light pass. */ +#include "cseries.h" +#include +#include "game/game_globals.h" +#include "rasterizer/common/rasterizer_common.h" +#include "rasterizer/xbox/rasterizer_xbox.h" +#include "rasterizer/rasterizer_swizzle.h" +#include "rasterizer/rasterizer.h" +#include "rasterizer/rasterizer_lights.h" +#include "plasma_lighting.h" +#include "plasma_occlusion.h" +#include + +enum { PLASMA_FALLOFF_SIZE = 64 }; +static IDirect3DVolumeTexture8 *plasma_falloff_texture; +static boolean plasma_falloff_bound; +static int plasma_falloff_stage; +static int plasma_falloff_filter; +static unsigned long plasma_specular_tint = 0x00FFFFFFUL; + +void plasma_specular_begin(long rasterizer_index) +{ + real_rgb_color tint; + real peak; + plasma_specular_tint = 0x00FFFFFFUL; + if (rasterizer_index < 0 || rasterizer_index >= rasterizer_lights.light_count || + !plasma_lighting_selected(rasterizer_index)) + return; + tint = rasterizer_lights.lights[rasterizer_index].color; + peak = MAX(tint.red, MAX(tint.green, tint.blue)); + /* The stock pass already applies scalar brightness. Preserve that peak, + but retain the source hue in both material reflection colours. */ + if (peak > 0.0f) + { + tint.red /= peak; + tint.green /= peak; + tint.blue /= peak; + } + plasma_specular_tint = real_rgb_color_to_pixel32(&tint); +} + +unsigned long plasma_specular_color(unsigned long material) +{ + unsigned long result = material & 0xFF000000UL; + int shift; + if (plasma_specular_tint == 0x00FFFFFFUL) + return material; + for (shift = 0; shift < 24; shift += 8) + result |= ((((material >> shift) & 255) * + ((plasma_specular_tint >> shift) & 255) + 127) / 255) << shift; + return result; +} + +/* Zero value and zero slope at the radius, without a hard luminous rim. */ +static real plasma_falloff_value(real distance_squared) +{ + real remaining = MAX(0.0f, 1.0f - distance_squared); + return remaining * remaining; +} + +static boolean plasma_falloff_create(void) +{ + D3DLOCKED_BOX locked; + unsigned long *pixels; + int x, y, z; + boolean success = FALSE; + + pixels = malloc(PLASMA_FALLOFF_SIZE * PLASMA_FALLOFF_SIZE * PLASMA_FALLOFF_SIZE * sizeof(*pixels)); + if (!pixels) + return FALSE; + for (z = 0; z < PLASMA_FALLOFF_SIZE; z++) + for (y = 0; y < PLASMA_FALLOFF_SIZE; y++) + for (x = 0; x < PLASMA_FALLOFF_SIZE; x++) + { + real dx = 2.0f * (x + 0.5f) / PLASMA_FALLOFF_SIZE - 1.0f; + real dy = 2.0f * (y + 0.5f) / PLASMA_FALLOFF_SIZE - 1.0f; + real dz = 2.0f * (z + 0.5f) / PLASMA_FALLOFF_SIZE - 1.0f; + unsigned long value = (unsigned long)(255.0f * plasma_falloff_value(dx*dx + dy*dy + dz*dz) + 0.5f); + pixels[(z * PLASMA_FALLOFF_SIZE + y) * PLASMA_FALLOFF_SIZE + x] = value * 0x01010101UL; + } + if (D3DDevice_CreateVolumeTexture(PLASMA_FALLOFF_SIZE, PLASMA_FALLOFF_SIZE, PLASMA_FALLOFF_SIZE, + 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, &plasma_falloff_texture) >= 0) + { + if (IDirect3DVolumeTexture8_LockBox(plasma_falloff_texture, 0, &locked, NULL, 0) >= 0 && locked.pBits) + { + rasterizer_xbox_bitmap_swizzle3d_long(locked.pBits, pixels, + PLASMA_FALLOFF_SIZE, PLASMA_FALLOFF_SIZE, PLASMA_FALLOFF_SIZE); + success = IDirect3DVolumeTexture8_UnlockBox(plasma_falloff_texture, 0) >= 0; + } + } + free(pixels); + if (!success) + plasma_falloff_dispose(); + return success; +} + +static void plasma_falloff_bind(long rasterizer_index, int stage, int stock_filter) +{ + D3DBaseTexture *occlusion; + if (!plasma_lighting_selected(rasterizer_index)) + return; + if (!plasma_falloff_texture && !plasma_falloff_create()) + return; /* allocation failure leaves the stock pass intact */ + occlusion = plasma_occlusion_texture(rasterizer_index, stage == 1); + D3DDevice_SetTexture(stage, occlusion ? occlusion : (D3DBaseTexture *)plasma_falloff_texture); + D3DDevice_SetTextureState_Deferred(stage, D3DTSS_MINFILTER, D3DTEXF_LINEAR); + plasma_falloff_stage = stage; + plasma_falloff_filter = stock_filter; + plasma_falloff_bound = TRUE; +} + +void plasma_falloff_begin(long rasterizer_index) +{ + plasma_falloff_bind(rasterizer_index, 2, D3DTEXF_POINT); +} + +void plasma_falloff_specular_begin(long rasterizer_index) +{ + plasma_falloff_bind(rasterizer_index, 1, D3DTEXF_LINEAR); +} + +void plasma_falloff_end(void) +{ + plasma_specular_tint = 0x00FFFFFFUL; + if (!plasma_falloff_bound) + return; + rasterizer_set_texture_direct(plasma_falloff_stage, global_rasterizer_data->distance_attenuation.index, 0); + D3DDevice_SetTextureState_Deferred(plasma_falloff_stage, D3DTSS_MINFILTER, plasma_falloff_filter); + plasma_falloff_bound = FALSE; +} + +void plasma_falloff_dispose(void) +{ + plasma_occlusion_reset(); + plasma_falloff_end(); + if (plasma_falloff_texture) + D3DResource_Release((D3DResource *)plasma_falloff_texture); + plasma_falloff_texture = NULL; +} diff --git a/port/linux/game/plasma_lighting.c b/port/linux/game/plasma_lighting.c new file mode 100644 index 0000000000..9d87450322 --- /dev/null +++ b/port/linux/game/plasma_lighting.c @@ -0,0 +1,241 @@ +/* Optional rendering for authored projectile lights. Reuse the rendered + attachment pose without editing tags or advancing projectile simulation. + rocket_lighting.c owns additional flight lights where rockets have none. */ +#include "cseries.h" +#include "objects/objects.h" +#include "tag_files/tag_files.h" +#include "plasma_lighting.h" +#include "authored_emitter_lighting.h" +#include "plasma_model_shader.h" +#include "plasma_occlusion.h" +#include "rocket_lighting.h" +#include "covenant_lighting.h" +#include "covenant_emitter_lighting.h" +#include "muzzle_lighting.h" +#include "shield_glow.h" +#include "rasterizer/rasterizer.h" +#include "rasterizer/rasterizer_lights.h" +#include + +#include "lighting_config.h" + +enum { PLASMA_LIGHTING_MAXIMUM = 128 }; +static struct +{ + long light_index; + long object_index; + long rasterizer_index; + int was_dynamic, category; + float radius_scale, saved_radius; +} plasma_lighting_attachments[PLASMA_LIGHTING_MAXIMUM]; +static int plasma_lighting_count; +static unsigned int plasma_model_mask; + +void plasma_model_lighting_reset(void) +{ + plasma_model_mask = 0; + plasma_occlusion_model_slot(NONE, 0); + plasma_occlusion_model_slot(NONE, 1); +} + +void plasma_model_lighting_slot(long light_index, short slot) +{ + if (slot < 0 || slot >= 2) + return; + plasma_model_mask &= ~(1U << slot); + plasma_occlusion_model_slot(light_index, slot); + if (plasma_lighting_selected(light_index)) + plasma_model_mask |= 1U << slot; +} + +unsigned int plasma_model_lighting_mask(void) +{ + return (lighting_config_boolean("display.plasma_lighting") || lighting_config_boolean("display.muzzle_lighting") || + covenant_emitter_lighting_enabled() || authored_emitter_lighting_enabled() || shield_glow_enabled()) ? plasma_model_mask : 0; +} + +void plasma_lighting_prepare(long light_index, long object_index, long definition_index) +{ + struct object_datum *object; + const char *name; + int index, category; + float covenant_scale, authored_scale = 1.0f; + + if ((!lighting_config_boolean("display.plasma_lighting") && !authored_emitter_lighting_enabled()) || object_index == NONE) + return; + if (covenant_lighting_owns(light_index, object_index)) + return; /* Owned glows have their own radius and frame cleanup. */ + object = object_try_and_get(object_index); + if (!object) + return; + category = authored_emitter_lighting_profile(object_index, definition_index, &authored_scale); + if (!category && (!lighting_config_boolean("display.plasma_lighting") || object->object.type != _object_type_projectile)) + return; + name = tag_get_name(object->definition_index); + covenant_scale = covenant_lighting_scale(name); + /* Exact tag policies keep unrelated custom projectiles stock. */ + /* The pistol overcharge uses a tag in the rifle directory. */ + if (!category && (!name || (!covenant_scale && strcmp(name, "weapons\\plasma rifle\\bolt") && + strcmp(name, "weapons\\plasma pistol\\bolt") && + strcmp(name, "weapons\\plasma rifle\\charged bolt") && + strcmp(name, "weapons\\rocket launcher\\rocket")))) + return; + for (index = 0; index < plasma_lighting_count; index++) + if (plasma_lighting_attachments[index].light_index == light_index && + plasma_lighting_attachments[index].object_index == object_index) + return; /* shared by split-screen views */ + if (plasma_lighting_count == PLASMA_LIGHTING_MAXIMUM) + return; /* excess lights retain stock behavior */ + if (!light_port_attachment_radius(light_index, object_index, + &plasma_lighting_attachments[plasma_lighting_count].saved_radius, FALSE)) + return; + plasma_lighting_attachments[plasma_lighting_count].light_index = light_index; + plasma_lighting_attachments[plasma_lighting_count].was_dynamic = light_port_dynamic_set(light_index, object_index, TRUE); + plasma_lighting_attachments[plasma_lighting_count].rasterizer_index = NONE; + plasma_lighting_attachments[plasma_lighting_count].object_index = object_index; + /* Wider soft falloff increases useful illumination without clipping colour. + Pistol shots start with smaller authored radii than rifle bolts. */ + plasma_lighting_attachments[plasma_lighting_count].radius_scale = + category ? authored_scale : covenant_scale ? covenant_scale : + !strcmp(name, "weapons\\plasma pistol\\bolt") ? 2.25f : + !strcmp(name, "weapons\\plasma rifle\\charged bolt") ? 2.75f : 1.75f; + plasma_lighting_attachments[plasma_lighting_count].category = category; + plasma_lighting_count++; + if (!light_port_refresh_attachment(light_index, object_index)) + { + /* Disconnected engine attachments stay out of render selection. */ + plasma_lighting_count--; + light_port_dynamic_set(light_index, object_index, + plasma_lighting_attachments[plasma_lighting_count].was_dynamic); + } +} + +float plasma_lighting_radius(long light_index, long object_index, float radius) +{ + int index; + if (!lighting_config_boolean("display.plasma_lighting") && !authored_emitter_lighting_enabled()) + return radius; + for (index = 0; index < plasma_lighting_count; index++) + if (plasma_lighting_attachments[index].light_index == light_index && + plasma_lighting_attachments[index].object_index == object_index && + authored_emitter_lighting_category_enabled(plasma_lighting_attachments[index].category)) + return radius * plasma_lighting_attachments[index].radius_scale; + return radius; +} + +void plasma_lighting_frame_end(void) +{ + int index; + + shield_glow_frame_end(); + muzzle_lighting_frame_end(); + covenant_emitter_lighting_frame_end(); + covenant_lighting_frame_end(); + rocket_lighting_frame_end(); + plasma_falloff_end(); /* Also close a pass if drawing ended early. */ + /* Called after render interpolation ends, even if the option was disabled. + Restore positions AND cluster membership before the next simulation tick. */ + for (index = 0; index < plasma_lighting_count; index++) + { + plasma_lighting_attachments[index].radius_scale = 1.0f; + light_port_attachment_radius(plasma_lighting_attachments[index].light_index, + plasma_lighting_attachments[index].object_index, + &plasma_lighting_attachments[index].saved_radius, TRUE); + light_port_dynamic_set(plasma_lighting_attachments[index].light_index, + plasma_lighting_attachments[index].object_index, plasma_lighting_attachments[index].was_dynamic); + light_port_refresh_attachment(plasma_lighting_attachments[index].light_index, + plasma_lighting_attachments[index].object_index); + } + plasma_lighting_reset(); + if (!lighting_config_boolean("display.plasma_occlusion") && !lighting_config_boolean("display.muzzle_lighting") && + !covenant_emitter_lighting_enabled() && !authored_emitter_lighting_enabled() && !shield_glow_enabled()) + plasma_occlusion_reset(); + if (!lighting_config_boolean("display.plasma_lighting") && !lighting_config_boolean("display.muzzle_lighting") && + !covenant_emitter_lighting_enabled() && !authored_emitter_lighting_enabled() && !shield_glow_enabled()) + plasma_falloff_dispose(); +} + +void plasma_lighting_reset(void) +{ + /* No tag pointers or object identities survive unloading or light recovery. */ + plasma_lighting_count = 0; + plasma_model_lighting_reset(); +} + +void plasma_lighting_window_begin(void) +{ + int index; + plasma_occlusion_window(); + shield_glow_window_begin(); + muzzle_lighting_window_begin(); + covenant_emitter_lighting_window_begin(); + covenant_lighting_window_begin(); + rocket_lighting_window_begin(); + plasma_model_lighting_reset(); + for (index = 0; index < plasma_lighting_count; index++) + plasma_lighting_attachments[index].rasterizer_index = NONE; +} + +void plasma_lighting_submitted(long light_index, long rasterizer_index) +{ + int index; + shield_glow_submitted(light_index, rasterizer_index); + muzzle_lighting_submitted(light_index, rasterizer_index); + covenant_emitter_lighting_submitted(light_index, rasterizer_index); + covenant_lighting_submitted(light_index, rasterizer_index); + rocket_lighting_submitted(light_index, rasterizer_index); + for (index = 0; index < plasma_lighting_count; index++) + if (plasma_lighting_attachments[index].light_index == light_index) + { + plasma_lighting_attachments[index].rasterizer_index = rasterizer_index; + plasma_occlusion_submit(light_index, rasterizer_index); + } +} + +int plasma_lighting_selected(long rasterizer_index) +{ + int index; + if (shield_glow_selected(rasterizer_index) || muzzle_lighting_selected(rasterizer_index) || covenant_emitter_lighting_selected(rasterizer_index)) + return TRUE; + if (rasterizer_index == NONE || (!lighting_config_boolean("display.plasma_lighting") && !authored_emitter_lighting_enabled())) + return FALSE; + if (covenant_lighting_selected(rasterizer_index) || rocket_lighting_selected(rasterizer_index)) + return TRUE; + for (index = 0; index < plasma_lighting_count; index++) + if (plasma_lighting_attachments[index].rasterizer_index == rasterizer_index && + authored_emitter_lighting_category_enabled(plasma_lighting_attachments[index].category)) + return TRUE; + return FALSE; +} + +int plasma_lighting_prong_cone(long rasterizer, float axis[3], float origin[3], float *radius) +{ + int i; + struct rasterizer_light_submit_parameters *light; + if (!lighting_config_boolean("display.plasma_prong_lighting") || rasterizer < 0 || rasterizer >= rasterizer_lights.light_count) + return FALSE; + for (i = 0; i < plasma_lighting_count; i++) + if (plasma_lighting_attachments[i].category == 4 && plasma_lighting_attachments[i].rasterizer_index == rasterizer) + { + light = &rasterizer_lights.lights[rasterizer]; + axis[0] = light->forward.i; axis[1] = light->forward.j; axis[2] = light->forward.k; + origin[0] = light->position.x; origin[1] = light->position.y; origin[2] = light->position.z; + *radius = light->radius; + return 3; + } + return FALSE; +} + +/* Headlights include their own vehicle in the collision field, even when + the general emitter occlusion option is off. Keep the authored beam cone. */ +int plasma_lighting_vehicle_occlusion(long light_index) +{ + int index; + if (light_index == NONE || !lighting_config_boolean("display.vehicle_lighting")) + return FALSE; + for (index = 0; index < plasma_lighting_count; index++) + if (plasma_lighting_attachments[index].light_index == light_index && + plasma_lighting_attachments[index].category == 2) + return TRUE; + return FALSE; +} diff --git a/port/linux/game/plasma_lighting.h b/port/linux/game/plasma_lighting.h new file mode 100644 index 0000000000..5f1e3a6730 --- /dev/null +++ b/port/linux/game/plasma_lighting.h @@ -0,0 +1,25 @@ +#ifndef PLASMA_LIGHTING_H +#define PLASMA_LIGHTING_H + +void plasma_lighting_prepare(long light_index, long object_index, long definition_index); +float plasma_lighting_radius(long light_index, long object_index, float radius); +int light_port_attachment_radius(long light_index, long object_index, float *radius, int restore); +int plasma_lighting_vehicle_occlusion(long light_index); +void plasma_lighting_frame_end(void); +void plasma_lighting_reset(void); +void plasma_lighting_window_begin(void); +void plasma_lighting_submitted(long light_index, long rasterizer_index); +int plasma_lighting_selected(long rasterizer_index); +int plasma_lighting_prong_cone(long rasterizer, float axis[3], float origin[3], float *radius); +void plasma_falloff_begin(long rasterizer_index); +void plasma_falloff_specular_begin(long rasterizer_index); +void plasma_specular_begin(long rasterizer_index); +unsigned long plasma_specular_color(unsigned long material); +void plasma_falloff_end(void); +void plasma_falloff_dispose(void); + +/* object_lights.c: validate the owner before refreshing an attachment. */ +int light_port_refresh_attachment(long light_index, long object_index); +int light_port_dynamic_set(long light_index, long object_index, int enabled); + +#endif diff --git a/port/linux/game/plasma_occlusion.c b/port/linux/game/plasma_occlusion.c new file mode 100644 index 0000000000..551ddbd077 --- /dev/null +++ b/port/linux/game/plasma_occlusion.c @@ -0,0 +1,821 @@ +/* A filtered local visibility field avoids rejecting a whole model at a door. + Queries see structure, scenery and machines, plus vehicles for turret flashes. + The field + is approximate within one cell of an edge; this is not a shadow renderer. */ +#include "plasma_occlusion.h" +#if defined(__SSE2__) +#include +#endif +#include "plasma_collision.h" +#include "ammo_counter_falloff.h" +#include "cseries.h" +#include "physics/collisions.h" +#include "plasma_lighting.h" +#include "authored_emitter_lighting.h" +#include "muzzle_lighting.h" +#include "shield_glow.h" +#include "covenant_emitter_lighting.h" +#include "rasterizer/rasterizer.h" +#include "rasterizer/rasterizer_lights.h" +#include "rasterizer/rasterizer_swizzle.h" +#include +#include +#include + +#include "lighting_config.h" +enum +{ + OCC_SIZE = 16, + OCC_COUNT = 4096, + OCC_LIGHTS = 8, + OCC_SUBMITTED = 128 +}; +static struct occlusion_field +{ + long identity; + unsigned long used, updated, window, admitted, traced; + unsigned long scene_revision; + struct plasma_collision_scene scene; + int fading, texture_mask; + real admission; + real center[3], extent, radius, specular; + real visibility[OCC_COUNT]; + real targets[OCC_COUNT]; + real depths[6][OCC_SIZE * OCC_SIZE], trace_center[3], trace_extent; + IDirect3DVolumeTexture8 *texture[3]; + /* Exact last successful uploads, bounded to 384 KiB across all fields. + Identical texels need no memory-watch fault, decoding or GPU upload. */ + unsigned long uploaded[3][OCC_COUNT]; + int uploaded_mask; + int directional; + real direction[3]; + int valid; +} fields[OCC_LIGHTS]; +static struct +{ + long identity, rasterizer; +} submitted[OCC_SUBMITTED]; +/* Only overflow identities need admission history; no engine pointers persist. */ +static struct +{ + long identity; + unsigned long seen; + int valid; +} overflow[OCC_SUBMITTED]; +static void remember_overflow(long identity, unsigned long now) +{ + int i, oldest = 0; + for (i = 0; i < OCC_SUBMITTED; i++) + { + if (overflow[i].valid && overflow[i].identity == identity) + { + oldest = i; + break; + } + if (!overflow[i].valid) + { + oldest = i; + break; + } + if (now - overflow[i].seen > now - overflow[oldest].seen) + oldest = i; + } + overflow[oldest].identity = identity; + overflow[oldest].seen = now; + overflow[oldest].valid = 1; +} +static int submitted_count; +static int updates_this_window; +static int fields_dirty; +static unsigned long current_window; +static long model_slots[2] = {NONE, NONE}; +static int enabled(void) +{ + return ((lighting_config_boolean("display.plasma_lighting") || authored_emitter_lighting_enabled() || covenant_emitter_lighting_enabled() || shield_glow_enabled()) && + lighting_config_boolean("display.plasma_occlusion")) || + lighting_config_boolean("display.muzzle_lighting") || lighting_config_boolean("display.vehicle_lighting"); +} +struct sample_axis +{ + int a, b, inside; + real t; +}; +static void sample_axis_initialize(struct sample_axis *axis, real coordinate) +{ + real p = MAX(0.0f, MIN((real)(OCC_SIZE - 1), coordinate * OCC_SIZE - 0.5f)); + axis->a = (int)p; + axis->b = MIN(axis->a + 1, OCC_SIZE - 1); + axis->t = p - axis->a; + axis->inside = coordinate >= 0 && coordinate <= 1; +} +static real sample_axes(const real *values, const struct sample_axis *x, + const struct sample_axis *y, const struct sample_axis *z) +{ + int row0 = (z->a * OCC_SIZE + y->a) * OCC_SIZE; + int row1 = (z->a * OCC_SIZE + y->b) * OCC_SIZE; + int row2 = (z->b * OCC_SIZE + y->a) * OCC_SIZE; + int row3 = (z->b * OCC_SIZE + y->b) * OCC_SIZE; + real a = values[row0+x->a], b = values[row1+x->a]; + real c = values[row2+x->a], d = values[row3+x->a]; + /* Seven linear interpolations replace eight three-factor weights. This + render-only field tolerates sub-texel rounding, before 8-bit upload. */ + a += (values[row0+x->b] - a) * x->t; + b += (values[row1+x->b] - b) * x->t; + c += (values[row2+x->b] - c) * x->t; + d += (values[row3+x->b] - d) * x->t; + a += (b - a) * y->t; + c += (d - c) * y->t; + return a + (c - a) * z->t; +} +static real sample_field(const real *values, real x, real y, real z) +{ + struct sample_axis axes[3]; + sample_axis_initialize(&axes[0], x); + sample_axis_initialize(&axes[1], y); + sample_axis_initialize(&axes[2], z); + return sample_axes(values, &axes[0], &axes[1], &axes[2]); +} + +static void half_sample_axes(struct sample_axis axes[3][OCC_SIZE]) +{ + int axis, i; + /* With a half-size receiver volume, coordinate * 16 - 0.5 is exactly + 3.75 + index / 2. All samples are interior, at quarter-texel weights. + Keep the same interpolation order; other scale ratios use sample_field. */ + for (axis = 0; axis < 3; axis++) + for (i = 0; i < OCC_SIZE; i++) + { + axes[axis][i].a = (i + 7) / 2; + axes[axis][i].b = axes[axis][i].a + 1; + axes[axis][i].t = i & 1 ? 0.25f : 0.75f; + axes[axis][i].inside = TRUE; + } +} + +/* Reuse the x/y interpolation shared by neighbouring output cells. The final + z interpolation remains in the update loop. This is the same x-then-y-then-z + arithmetic as sample_axes, with three interpolations per cell instead of + seven. Scratch lives only during this synchronous render update. */ +static void reproject_rows(const real *values, struct sample_axis const axes[3][OCC_SIZE], real *rows) +{ + real horizontal[OCC_COUNT]; + int x, y, z, low[3] = {0, OCC_SIZE - 1, OCC_SIZE - 1}, high[3] = {0, 0, 0}; + /* Only source rows reached by the requested coordinates are needed. + In the half-size volume, ten source rows feed sixteen output rows. */ + for (x = 0; x < OCC_SIZE; x++) + for (y = 1; y < 3; y++) + { + low[y] = MIN(low[y], MIN(axes[y][x].a, axes[y][x].b)); + high[y] = MAX(high[y], MAX(axes[y][x].a, axes[y][x].b)); + } + for (z = low[2]; z <= high[2]; z++) + for (y = low[1]; y <= high[1]; y++) + for (x = 0; x < OCC_SIZE; x++) + { + int row = (z * OCC_SIZE + y) * OCC_SIZE; + real a = values[row + axes[0][x].a]; + horizontal[row + x] = a + (values[row + axes[0][x].b] - a) * axes[0][x].t; + } + for (z = low[2]; z <= high[2]; z++) + for (y = 0; y < OCC_SIZE; y++) + for (x = 0; x < OCC_SIZE; x++) + { + int row0 = (z * OCC_SIZE + axes[1][y].a) * OCC_SIZE; + int row1 = (z * OCC_SIZE + axes[1][y].b) * OCC_SIZE; + real a = horizontal[row0 + x]; + rows[(z * OCC_SIZE + y) * OCC_SIZE + x] = a + (horizontal[row1 + x] - a) * axes[1][y].t; + } +} +static real sample_history_rows(const real *rows, int x, int y, struct sample_axis const *z) +{ + real a = rows[(z->a * OCC_SIZE + y) * OCC_SIZE + x]; + return a + (rows[(z->b * OCC_SIZE + y) * OCC_SIZE + x] - a) * z->t; +} + +/* One depth ray per cubemap texel serves every radial cell on that ray. + Interpolate visibility comparisons, never distances across a doorway. */ +static void trace_depths(real const extent, real_point3d const *from, long ignore, int vehicles, int resolution, real depths[6][OCC_SIZE * OCC_SIZE]) +{ + real_vector3d vectors[PLASMA_COLLISION_RAYS]; + real hits[PLASMA_COLLISION_RAYS]; + int face, x, y, axis, count = 0; + unsigned long flags = + FLAG(_collision_test_structure_bit) | FLAG(_collision_test_front_facing_surfaces_bit) | + FLAG(_collision_test_back_facing_surfaces_bit) | FLAG(_collision_test_objects_bit) | + FLAG(_collision_test_objects_scenery_bit) | FLAG(_collision_test_objects_machines_bit); + if (vehicles) flags |= FLAG(_collision_test_objects_vehicles_bit); + for (face = 0; face < 6; face++) + for (y = 0; y < resolution; y++) + for (x = 0; x < resolution; x++) + { + real component[3]; + real_vector3d ray; + axis = face / 2; + component[axis] = (face & 1) ? extent : -extent; + component[(axis + 1) % 3] = (2.0f * (x + 0.5f) / resolution - 1) * extent; + component[(axis + 2) % 3] = (2.0f * (y + 0.5f) / resolution - 1) * extent; + ray.i = component[0]; + ray.j = component[1]; + ray.k = component[2]; + vectors[count++] = ray; + } + plasma_collision_depths(flags, from, vectors, count, ignore, hits); + count = 0; + for (face = 0; face < 6; face++) + for (y = 0; y < resolution; y++) + for (x = 0; x < resolution; x++) + depths[face][y * OCC_SIZE + x] = hits[count++]; +} +static real depth_visibility(real depths[6][OCC_SIZE * OCC_SIZE], real_vector3d const *ray, real extent, int resolution) +{ + real p[3], magnitude, u, v, tx, ty, result = 0, length, fraction, hits[2][2]; + int axis = 0, face, x, y, i, j, clear = TRUE; + p[0] = ray->i; + p[1] = ray->j; + p[2] = ray->k; + if (fabsf(p[1]) > fabsf(p[axis])) + axis = 1; + if (fabsf(p[2]) > fabsf(p[axis])) + axis = 2; + magnitude = fabsf(p[axis]); + if (magnitude < 0.0001f) + return 1; + face = axis * 2 + (p[axis] > 0); + u = MAX(0.0f, MIN((real)(resolution - 1), (p[(axis + 1) % 3] / magnitude + 1) * 0.5f * resolution - 0.5f)); + v = MAX(0.0f, MIN((real)(resolution - 1), (p[(axis + 2) % 3] / magnitude + 1) * 0.5f * resolution - 0.5f)); + x = (int)u; + y = (int)v; + tx = u - x; + ty = v - y; + fraction = magnitude / extent; + for (j = 0; j < 2; j++) + for (i = 0; i < 2; i++) + { + hits[j][i] = depths[face][MIN(y + j, resolution - 1) * OCC_SIZE + MIN(x + i, resolution - 1)]; + if (!(hits[j][i] >= fraction)) clear = FALSE; + } + /* All four comparisons saturate to one before any distance feathering. + Retain the original sum/order of weights, even its rounding at seams, + but avoid the square root and four redundant visibility calculations. */ + if (clear) + return (1 - tx) * (1 - ty) + tx * (1 - ty) + (1 - tx) * ty + tx * ty; + length = sqrtf(p[0] * p[0] + p[1] * p[1] + p[2] * p[2]) * extent / magnitude; + for (j = 0; j < 2; j++) + for (i = 0; i < 2; i++) + { + real visible = MAX(0.0f, MIN(1.0f, 1.0f - (fraction - hits[j][i]) * length / 0.025f)); + result += visible * (i ? tx : 1 - tx) * (j ? ty : 1 - ty); + } + return result; +} +/* Four receiver cells share face selection and visibility arithmetic. Keep + exact divides, square roots and weight order: no approximate reciprocals or + reduced grids. Other CPU targets retain the scalar implementation. */ +#if defined(__SSE2__) +static __m128 visibility_choose(__m128 mask, __m128 a, __m128 b) +{ + return _mm_or_ps(_mm_and_ps(mask, a), _mm_andnot_ps(mask, b)); +} +static void depth_visibility_row(real depths[6][OCC_SIZE * OCC_SIZE], const real xs[OCC_SIZE], real y, real z, + real extent, int resolution, real *output) +{ + __m128 zero = _mm_setzero_ps(), one = _mm_set1_ps(1), half = _mm_set1_ps(.5f); + __m128 py = _mm_set1_ps(y), pz = _mm_set1_ps(z), ey = _mm_set1_ps(fabsf(y)), ez = _mm_set1_ps(fabsf(z)); + __m128 ex = _mm_set1_ps(extent), size = _mm_set1_ps((real)resolution), limit = _mm_set1_ps((real)(resolution - 1)); + __m128 facey = _mm_set1_ps((real)(2 + (y > 0))), facez = _mm_set1_ps((real)(4 + (z > 0))); + __m128 abs_mask = _mm_castsi128_ps(_mm_set1_epi32(0x7fffffff)); + int x, i, j, lane; + for (x = 0; x < OCC_SIZE; x += 4) + { + __m128 px = _mm_loadu_ps(xs + x), magnitude = _mm_and_ps(px, abs_mask); + __m128 mask = _mm_cmpgt_ps(ey, magnitude), u = visibility_choose(mask, pz, py), + v = visibility_choose(mask, px, pz); + __m128 face = visibility_choose(mask, facey, _mm_and_ps(_mm_cmpgt_ps(px, zero), one)); + __m128 near_origin, tx, ty, fraction, hits[4], length; + __m128 clear = _mm_castsi128_ps(_mm_set1_epi32(-1)), result = zero; + int faces[4], columns[4], rows[4]; + real gather[4]; + magnitude = visibility_choose(mask, ey, magnitude); + mask = _mm_cmpgt_ps(ez, magnitude); + magnitude = visibility_choose(mask, ez, magnitude); + face = visibility_choose(mask, facez, face); + u = visibility_choose(mask, px, u); + v = visibility_choose(mask, py, v); + near_origin = _mm_cmplt_ps(magnitude, _mm_set1_ps(.0001f)); + magnitude = visibility_choose(near_origin, one, magnitude); + u = _mm_sub_ps(_mm_mul_ps(_mm_mul_ps(_mm_add_ps(_mm_div_ps(u, magnitude), one), half), size), half); + v = _mm_sub_ps(_mm_mul_ps(_mm_mul_ps(_mm_add_ps(_mm_div_ps(v, magnitude), one), half), size), half); + u = _mm_max_ps(zero, _mm_min_ps(limit, u)); + v = _mm_max_ps(zero, _mm_min_ps(limit, v)); + _mm_storeu_si128((__m128i *)faces, _mm_cvttps_epi32(face)); + _mm_storeu_si128((__m128i *)columns, _mm_cvttps_epi32(u)); + _mm_storeu_si128((__m128i *)rows, _mm_cvttps_epi32(v)); + tx = _mm_sub_ps(u, _mm_cvtepi32_ps(_mm_cvttps_epi32(u))); + ty = _mm_sub_ps(v, _mm_cvtepi32_ps(_mm_cvttps_epi32(v))); + fraction = _mm_div_ps(magnitude, ex); + for (j = 0; j < 2; j++) + for (i = 0; i < 2; i++) + { + for (lane = 0; lane < 4; lane++) + gather[lane] = depths[faces[lane]][MIN(rows[lane] + j, resolution - 1) * OCC_SIZE + + MIN(columns[lane] + i, resolution - 1)]; + hits[j * 2 + i] = _mm_loadu_ps(gather); + clear = _mm_and_ps(clear, _mm_cmpge_ps(hits[j * 2 + i], fraction)); + } + if (_mm_movemask_ps(clear) == 15) + { + result = + _mm_add_ps(_mm_mul_ps(_mm_sub_ps(one, tx), _mm_sub_ps(one, ty)), _mm_mul_ps(tx, _mm_sub_ps(one, ty))); + result = _mm_add_ps(result, _mm_mul_ps(_mm_sub_ps(one, tx), ty)); + result = _mm_add_ps(result, _mm_mul_ps(tx, ty)); + } + else + { + length = _mm_div_ps(_mm_mul_ps(_mm_sqrt_ps(_mm_add_ps(_mm_add_ps(_mm_mul_ps(px, px), _mm_mul_ps(py, py)), + _mm_mul_ps(pz, pz))), + ex), + magnitude); + for (j = 0; j < 2; j++) + for (i = 0; i < 2; i++) + { + __m128 visible = _mm_sub_ps( + one, _mm_div_ps(_mm_mul_ps(_mm_sub_ps(fraction, hits[j * 2 + i]), length), _mm_set1_ps(.025f))); + visible = _mm_max_ps(zero, _mm_min_ps(one, visible)); + result = _mm_add_ps(result, _mm_mul_ps(_mm_mul_ps(visible, i ? tx : _mm_sub_ps(one, tx)), + j ? ty : _mm_sub_ps(one, ty))); + } + } + _mm_storeu_ps(output + x, visibility_choose(near_origin, one, result)); + } +} +#else +static void depth_visibility_row(real depths[6][OCC_SIZE * OCC_SIZE], const real xs[OCC_SIZE], real y, real z, + real extent, int resolution, real *output) +{ + int x; + for (x = 0; x < OCC_SIZE; x++) + { + real_vector3d ray; + ray.i = xs[x]; + ray.j = y; + ray.k = z; + output[x] = depth_visibility(depths, &ray, extent, resolution); + } +} +#endif + +static void reconstruct_visibility(real depths[6][OCC_SIZE * OCC_SIZE], real extent, int resolution, real dx, real dy, + real dz, real *output) +{ + real offsets[OCC_SIZE], xs[OCC_SIZE]; + int x, y, z; + for (x = 0; x < OCC_SIZE; x++) + { + offsets[x] = (2.0f * (x + 0.5f) / OCC_SIZE - 1) * extent; + xs[x] = offsets[x] + dx; + } + for (z = 0; z < OCC_SIZE; z++) + for (y = 0; y < OCC_SIZE; y++) + depth_visibility_row(depths, xs, offsets[y] + dy, offsets[z] + dz, extent, resolution, + output + (z * OCC_SIZE + y) * OCC_SIZE); +} + +static real filter_visibility(real history, real target, real clear_alpha, real block_alpha) +{ + real alpha = target < history ? block_alpha : clear_alpha; + real value = history + (target - history) * alpha; + /* Render-only fade history can otherwise stick at subnormal values. + This cutoff is far below one 8-bit texture step and leaves the + simulation's floating-point mode untouched. */ + if (value < 1.0e-20f) value = 0; + return value; +} +static int upload(IDirect3DVolumeTexture8 **texture, unsigned long const *pixels) +{ + D3DLOCKED_BOX box; + if (!*texture && D3DDevice_CreateVolumeTexture(OCC_SIZE, OCC_SIZE, OCC_SIZE, 1, 0, D3DFMT_A8R8G8B8, + D3DPOOL_MANAGED, texture) < 0) + return 0; + if (IDirect3DVolumeTexture8_LockBox(*texture, 0, &box, NULL, 0) < 0 || !box.pBits) + return 0; + rasterizer_xbox_bitmap_swizzle3d_long(box.pBits, (void *)pixels, OCC_SIZE, OCC_SIZE, OCC_SIZE); + return IDirect3DVolumeTexture8_UnlockBox(*texture, 0) >= 0; +} +/* Keep the large reconstruction scratch off the repeated per-draw lookup + path. Clang otherwise inlines this back into field_for, reserving/probing + its large stack frame even on a cache hit. All ports build with Clang. + This runs at most once per admitted field in a view. */ +static __attribute__((noinline)) struct occlusion_field *update_field(struct occlusion_field *field, long rasterizer_index, unsigned long now) +{ + struct rasterizer_light_submit_parameters *light; + int i, x, y, z, stationary, vehicles, resolution, retraced = FALSE; + unsigned long scene_revision; + real elapsed, extent, specular, clear_alpha, block_alpha, admission; + real previous[OCC_COUNT]; + real projected[OCC_COUNT]; + struct sample_axis history_axes[3][OCC_SIZE]; + real trace_dx, trace_dy, trace_dz; + real axis[3], origin[3], radius; + fields_dirty = 1; + field->used = now; + light = &rasterizer_lights.lights[rasterizer_index]; + specular = plasma_occlusion_specular_scale(rasterizer_index); + extent = light->radius * MAX(1.0f, specular); + if (!(extent > 0.001f && extent < 1000.0f)) + return NULL; + updates_this_window++; + elapsed = field->valid ? MIN((real)(now - field->updated) * 0.001f, 0.1f) : 0.1f; + trace_dx = light->position.x - field->trace_center[0]; + trace_dy = light->position.y - field->trace_center[1]; + trace_dz = light->position.z - field->trace_center[2]; + vehicles = muzzle_lighting_vehicle_occlusion(field->identity) || plasma_lighting_vehicle_occlusion(field->identity) || + covenant_emitter_lighting_vehicle_occlusion(field->identity); + scene_revision = plasma_collision_scene_revision(&field->scene, &light->position, extent, vehicles); + /* Only the deliberately short, soft prong glow uses a smaller ray grid. + Keep the established shield/projectile/vehicle grids and 16^3 filtered + output unchanged. A prong's 0.6-unit extent needs 96 rays, not 1536. */ + resolution = plasma_lighting_prong_cone(rasterizer_index, axis, origin, &radius) ? 4 : OCC_SIZE; + /* Cache collision depths briefly, but project and fade at every rendered pose. + Exact stationary poses can retain depths while all collision inputs are + unchanged. Geometry changes follow the existing 12 ms trace cadence; + they cannot be mistaken for a permanently unchanged stationary scene. */ + if (!field->valid || + (now - field->traced >= 12 && (field->scene_revision != scene_revision || + trace_dx != 0 || trace_dy != 0 || trace_dz != 0)) || field->trace_extent != extent || + trace_dx * trace_dx + trace_dy * trace_dy + trace_dz * trace_dz > extent * extent * 0.015625f) + { + trace_depths(extent, &light->position, covenant_emitter_lighting_occlusion_ignore(field->identity), + vehicles, resolution, field->depths); + retraced = TRUE; + field->scene_revision = scene_revision; + field->traced = now; + field->trace_extent = extent; + field->trace_center[0] = light->position.x; + field->trace_center[1] = light->position.y; + field->trace_center[2] = light->position.z; + trace_dx = trace_dy = trace_dz = 0; + } + memcpy(previous, field->visibility, sizeof(previous)); + stationary = field->valid && field->extent == extent && + field->center[0] == light->position.x && field->center[1] == light->position.y && + field->center[2] == light->position.z; + admission = field->fading ? MIN(1.0f, (real)(now - field->admitted) / 80.0f) : 1.0f; + admission = admission * admission * (3.0f - 2.0f * admission); + clear_alpha = 1.0f - powf(0.5f, elapsed / 0.025f); + block_alpha = 1.0f - powf(0.5f, elapsed / 0.008f); + /* Translation and uniform scale are separable: each axis has sixteen + coordinates, shared by all 4096 cells. Keep the original arithmetic + and interpolation order, including the outside-history fallback. */ + if (!stationary && field->valid && field->extent > 0) + { + for (i = 0; i < OCC_SIZE; i++) + { + real offset = (2.0f * (i + 0.5f) / OCC_SIZE - 1) * extent; + sample_axis_initialize(&history_axes[0][i], 0.5f + (light->position.x + offset - field->center[0]) / (2 * field->extent)); + sample_axis_initialize(&history_axes[1][i], 0.5f + (light->position.y + offset - field->center[1]) / (2 * field->extent)); + sample_axis_initialize(&history_axes[2][i], 0.5f + (light->position.z + offset - field->center[2]) / (2 * field->extent)); + } + reproject_rows(previous, history_axes, projected); + } + /* Unchanged poses only advance fades. This flat loop can vectorize without + ray construction or history-reprojection branches. */ + if (stationary && !retraced) + { + for (i = 0; i < OCC_COUNT; i++) + field->visibility[i] = filter_visibility(previous[i], field->targets[i], clear_alpha, block_alpha); + } + else + { + reconstruct_visibility(field->depths, extent, resolution, trace_dx, trace_dy, trace_dz, field->targets); + for (z = 0; z < OCC_SIZE; z++) + for (y = 0; y < OCC_SIZE; y++) + for (x = 0; x < OCC_SIZE; x++) + { + real target, history; + i = (z * OCC_SIZE + y) * OCC_SIZE + x; + target = field->targets[i]; + /* Reproject history at the receiver, not at a moving light-local cell. */ + history = target; + if (stationary) + history = previous[i]; + else if (field->valid && field->extent > 0) + { + if (history_axes[0][x].inside && history_axes[1][y].inside && history_axes[2][z].inside) + history = sample_history_rows(projected, x, y, &history_axes[2][z]); + } + field->visibility[i] = filter_visibility(history, target, clear_alpha, block_alpha); + } + } + + /* Texture coordinates are light-local. A changed world position alone + does not change texels if the projected visibility stayed identical. */ + if (!field->valid || field->radius != light->radius || field->specular != specular || + field->extent != extent || field->admission != admission || + memcmp(previous, field->visibility, sizeof(previous))) + field->texture_mask = 0; + else + field->texture_mask &= 7; /* failed uploads retry next view */ + field->center[0] = light->position.x; + field->center[1] = light->position.y; + field->center[2] = light->position.z; + field->radius = light->radius; + field->specular = specular; + field->extent = extent; + field->admission = admission; + field->updated = now; + field->window = current_window; + field->valid = 1; + return field; +} +static struct occlusion_field *field_for(long rasterizer_index) +{ + struct occlusion_field *field = NULL; + unsigned long now = GetTickCount(); + long identity = NONE; + int i; + if (!enabled() || rasterizer_index < 0 || rasterizer_index >= rasterizer_lights.light_count) + return NULL; + for (i = 0; i < submitted_count; i++) + if (submitted[i].rasterizer == rasterizer_index) + identity = submitted[i].identity; + if (identity == NONE) + return NULL; + for (i = 0; i < OCC_LIGHTS; i++) + if (fields[i].valid && fields[i].identity == identity) + field = &fields[i]; + if (field && field->window == current_window) + return field; + if (updates_this_window >= OCC_LIGHTS) + { + remember_overflow(identity, now); + return NULL; + } + if (!field) + { + for (i = 0; i < OCC_LIGHTS; i++) + if (!fields[i].valid || now - fields[i].used > 100) + { + field = &fields[i]; + break; + } + if (!field) + { + remember_overflow(identity, now); + return NULL; /* active lights are never evicted */ + } + field->valid = 0; + field->identity = identity; + field->admitted = now; + field->fading = 0; + for (i = 0; i < OCC_SUBMITTED; i++) + if (overflow[i].valid && overflow[i].identity == identity && now - overflow[i].seen < 200) + field->fading = 1; + for (i = 0; i < OCC_COUNT; i++) + field->visibility[i] = 1; + } + return update_field(field, rasterizer_index, now); +} +/* Convert four neighbouring receiver samples together. Keep the scalar order + of interpolation, admission, angular mask and radial falloff; no approximate + reciprocals or square roots. Other architectures retain the same formulas. */ +static void texture_row(unsigned long *pixels, real const *a, real const *b, real blend, + real admission, int radial, int directional, real const axis[3], real dy, real dz, real height_scale) +{ + int x; +#if defined(__SSE2__) + __m128 zero = _mm_setzero_ps(), one = _mm_set1_ps(1), two = _mm_set1_ps(2), three = _mm_set1_ps(3); + __m128 yy = _mm_set1_ps(dy * dy), zz = _mm_set1_ps(dz * dz); + __m128 weight = _mm_set1_ps(admission), base = _mm_set1_ps(1 - admission), mix = _mm_set1_ps(blend); + for (x = 0; x < OCC_SIZE; x += 4) + { + __m128 dx = _mm_setr_ps((x + 0.5f) * 0.125f - 1, (x + 1.5f) * 0.125f - 1, + (x + 2.5f) * 0.125f - 1, (x + 3.5f) * 0.125f - 1); + __m128 xx = _mm_mul_ps(dx, dx), first = _mm_loadu_ps(a + x); + __m128 value = _mm_add_ps(first, _mm_mul_ps(_mm_sub_ps(_mm_loadu_ps(b + x), first), mix)); + __m128 remaining, t, dot, length; + __m128i bytes; + value = _mm_add_ps(base, _mm_mul_ps(weight, value)); + if (directional == 2) + value = _mm_mul_ps(value, _mm_set1_ps(needler_falloff_factor(dz * height_scale))); + else if (directional) + { + length = _mm_sqrt_ps(_mm_add_ps(_mm_add_ps(xx, yy), zz)); + dot = _mm_add_ps(_mm_add_ps(_mm_mul_ps(_mm_set1_ps(axis[0]), dx), + _mm_set1_ps(axis[1] * dy)), _mm_set1_ps(axis[2] * dz)); + t = directional == 3 ? _mm_div_ps(_mm_add_ps(_mm_div_ps(dot, length), _mm_set1_ps(0.2f)), _mm_set1_ps(0.7f)) : + _mm_div_ps(dot, _mm_mul_ps(length, _mm_set1_ps(0.6f))); + t = _mm_min_ps(_mm_max_ps(t, zero), one); + value = _mm_mul_ps(value, _mm_mul_ps(_mm_mul_ps(t, t), _mm_sub_ps(three, _mm_mul_ps(two, t)))); + } + if (radial) + { + remaining = _mm_max_ps(zero, _mm_sub_ps(_mm_sub_ps(_mm_sub_ps(one, xx), yy), zz)); + value = _mm_mul_ps(value, _mm_mul_ps(remaining, remaining)); + } + /* Visibility is in [0,1], so signed conversion is exact for [0,255]. */ + bytes = _mm_cvttps_epi32(_mm_add_ps(_mm_mul_ps(_mm_set1_ps(255), value), _mm_set1_ps(0.5f))); + bytes = _mm_or_si128(bytes, _mm_slli_epi32(bytes, 8)); + bytes = _mm_or_si128(bytes, _mm_slli_epi32(bytes, 16)); + _mm_storeu_si128((__m128i *)(pixels + x), bytes); + } +#else + for (x = 0; x < OCC_SIZE; x++) + { + real dx = 2.0f * (x + 0.5f) / OCC_SIZE - 1; + real value = a[x] + (b[x] - a[x]) * blend; + real remaining = MAX(0.0f, 1 - dx * dx - dy * dy - dz * dz); + value = 1 - admission + admission * value; + if (directional) + value *= directional == 3 ? plasma_prong_falloff_factor(axis, dx, dy, dz) : directional == 2 ? + needler_falloff_factor(dz * height_scale) : ammo_counter_falloff_factor(axis, dx, dy, dz); + if (radial) value *= remaining * remaining; + pixels[x] = (unsigned long)(255 * value + 0.5f) * 0x01010101UL; + } +#endif +} + +/* Build only a texture actually consumed by this view. CPU visibility history + stays independent of pass order, and each pass uploads at most once. */ +/* Keep the pixel/row scratch out of cache hits, including under LTO. */ +static __attribute__((noinline)) void *prepare_field_texture(struct occlusion_field *field, int pass, int directional, real const axis[3]) +{ + unsigned long pixels[OCC_COUNT]; + real rows[OCC_COUNT]; + struct sample_axis half_axes[3][OCC_SIZE]; + int x, y, z, i; + real scale; + scale = (pass == 2 ? field->specular : 1.0f) * field->radius / field->extent; + if (pass && scale == 0.5f) + { + half_sample_axes(half_axes); + reproject_rows(field->visibility, half_axes, rows); + } + /* The ordinary model mask needs no radial/directional calculation or + resampling. A flat conversion keeps its common path vectorizable. */ + if (!pass && !directional) + { + for (i = 0; i < OCC_COUNT; i++) + pixels[i] = (unsigned long)(255 * (1 - field->admission + field->admission * field->visibility[i]) + 0.5f) * 0x01010101UL; + } + else if (!pass || scale == 0.5f || scale == 1.0f) + { + /* Resolve half/unit-size source slices once per output slice. The + contiguous rows share the packed conversion, including angular masks. */ + for (z = 0; z < OCC_SIZE; z++) + { + real const *a = !pass || scale == 1.0f ? field->visibility + z * OCC_SIZE * OCC_SIZE : rows + half_axes[2][z].a * OCC_SIZE * OCC_SIZE; + real const *b = !pass || scale == 1.0f ? a : rows + half_axes[2][z].b * OCC_SIZE * OCC_SIZE; + real blend = !pass || scale == 1.0f ? 0 : half_axes[2][z].t; + real dz = 2.0f * (z + 0.5f) / OCC_SIZE - 1; + for (y = 0; y < OCC_SIZE; y++) + { + real dy = 2.0f * (y + 0.5f) / OCC_SIZE - 1; + texture_row(pixels + (z * OCC_SIZE + y) * OCC_SIZE, a + y * OCC_SIZE, b + y * OCC_SIZE, + blend, field->admission, pass != 0, directional, axis, dy, dz, + pass == 0 ? field->extent / field->radius : pass == 2 ? field->specular : 1.0f); + } + } + } + else + { + for (z = 0; z < OCC_SIZE; z++) + for (y = 0; y < OCC_SIZE; y++) + for (x = 0; x < OCC_SIZE; x++) + { + real dx = 2.0f * (x + 0.5f) / OCC_SIZE - 1; + real dy = 2.0f * (y + 0.5f) / OCC_SIZE - 1; + real dz = 2.0f * (z + 0.5f) / OCC_SIZE - 1; + real remaining = MAX(0.0f, 1 - dx * dx - dy * dy - dz * dz); + real value; + i = (z * OCC_SIZE + y) * OCC_SIZE + x; + /* Unit-scale samples land exactly at texel centres. Outside the + attenuation sphere the result is zero regardless of visibility. */ + value = field->visibility[i]; + if (pass && remaining > 0 && scale != 1.0f) + value = scale == 0.5f ? sample_history_rows(rows, x, y, &half_axes[2][z]) : + sample_field(field->visibility, 0.5f + dx * scale * 0.5f, + 0.5f + dy * scale * 0.5f, 0.5f + dz * scale * 0.5f); + value = 1 - field->admission + field->admission * value; + if (directional) + value *= directional == 3 ? plasma_prong_falloff_factor(axis, dx, dy, dz) : directional == 2 ? needler_falloff_factor(dz * + (pass == 0 ? field->extent / field->radius : pass == 2 ? field->specular : 1.0f)) : + ammo_counter_falloff_factor(axis, dx, dy, dz); + if (pass) + value *= remaining * remaining; + pixels[i] = (unsigned long)(255 * value + 0.5f) * 0x01010101UL; + } + } + if (!(field->uploaded_mask & (1 << pass)) || memcmp(field->uploaded[pass], pixels, sizeof(pixels))) + { + if (!upload(&field->texture[pass], pixels)) + { + /* A failed unlock may have changed backing storage. */ + field->uploaded_mask &= ~(1 << pass); + field->texture_mask |= 8 << pass; + return NULL; + } + memcpy(field->uploaded[pass], pixels, sizeof(pixels)); + field->uploaded_mask |= 1 << pass; + } + field->texture_mask |= 1 << pass; + return field->texture[pass]; +} +static void *field_texture(struct occlusion_field *field, int pass, long rasterizer) +{ + real axis[3], origin[3], radius; + int directional = covenant_emitter_lighting_cone(rasterizer, axis, origin, &radius); + if (!directional) directional = plasma_lighting_prong_cone(rasterizer, axis, origin, &radius); + if (!field) + return NULL; + /* Directional profiles can rotate without changing collision visibility. + Needler's lower-height fade is independent of the weapon's aim. */ + if (directional != field->directional || + (directional && directional != 2 && memcmp(axis, field->direction, sizeof(field->direction)))) + { + field->texture_mask = 0; + field->directional = directional; + if (directional && directional != 2) memcpy(field->direction, axis, sizeof(field->direction)); + } + /* Equal radii produce identical diffuse/specular texels, including the + directional mask. Share that upload; different extents stay independent. */ + if (pass == 2 && field->specular == 1.0f) + pass = 1; + /* A failed pass falls back for the rest of this view, then retries next view. */ + if (field->texture_mask & (8 << pass)) + return NULL; + if (field->texture_mask & (1 << pass)) + return field->texture[pass]; + return prepare_field_texture(field, pass, directional, axis); +} +void plasma_occlusion_reset(void) +{ + int i, j; + ammo_counter_falloff_dispose(); + /* The disabled frame-end path may request reset repeatedly. Clear the + bounded upload/visibility storage only after it has actually been used. */ + if (fields_dirty) + { + for (i = 0; i < OCC_LIGHTS; i++) + for (j = 0; j < 3; j++) + if (fields[i].texture[j]) + D3DResource_Release((D3DResource *)fields[i].texture[j]); + memset(fields, 0, sizeof(fields)); + fields_dirty = 0; + } + memset(overflow, 0, sizeof(overflow)); + plasma_occlusion_window(); +} + + +void plasma_occlusion_window(void) +{ + ammo_counter_falloff_window(); + current_window++; + submitted_count = 0; + updates_this_window = 0; + model_slots[0] = model_slots[1] = NONE; +} +unsigned long plasma_occlusion_view_serial(void) +{ + return current_window; +} +void plasma_occlusion_submit(long light, long rasterizer_index) +{ + if ((((lighting_config_boolean("display.plasma_lighting") || authored_emitter_lighting_enabled()) && lighting_config_boolean("display.plasma_occlusion")) || + plasma_lighting_vehicle_occlusion(light) || covenant_emitter_lighting_vehicle_occlusion(light) || + muzzle_lighting_selected(rasterizer_index) || + ((covenant_emitter_lighting_selected(rasterizer_index) || shield_glow_selected(rasterizer_index)) && lighting_config_boolean("display.plasma_occlusion"))) && + submitted_count < OCC_SUBMITTED) + { + submitted[submitted_count].identity = light; + submitted[submitted_count++].rasterizer = rasterizer_index; + } +} +void plasma_occlusion_model_slot(long rasterizer_index, short slot) +{ + if (slot >= 0 && slot < 2) + model_slots[slot] = rasterizer_index; +} +void *plasma_occlusion_texture(long rasterizer_index, int specular) +{ + struct occlusion_field *field = field_for(rasterizer_index); + void *texture = field_texture(field, specular ? 2 : 1, rasterizer_index); + return texture ? texture : ammo_counter_falloff_texture(rasterizer_index, specular ? 2 : 1, NULL); +} +void *plasma_occlusion_model_texture(int slot, float transform[4]) +{ + struct occlusion_field *field; + if (slot < 0 || slot >= 2) + return NULL; + field = field_for(model_slots[slot]); + if (!field) + return ammo_counter_falloff_texture(model_slots[slot], 0, transform); + transform[0] = field->center[0]; + transform[1] = field->center[1]; + transform[2] = field->center[2]; + transform[3] = 0.5f / field->extent; + { + void *texture = field_texture(field, 0, model_slots[slot]); + return texture ? texture : ammo_counter_falloff_texture(model_slots[slot], 0, transform); + } +} diff --git a/port/linux/game/render_interpolation.c b/port/linux/game/render_interpolation.c index 1f9f795b94..32e1376f68 100644 --- a/port/linux/game/render_interpolation.c +++ b/port/linux/game/render_interpolation.c @@ -16,13 +16,10 @@ also need the tick after the pair it spans: two ticks behind.) Rotations are blended as quaternions (normalised lerp, taking the shorter way round), positions and scales linearly. Anything that moves further than a tick of motion plausibly allows (teleports, respawns, camera cuts) snaps -instead of sweeping across the world, and so does a pose whose nodes moved -too far for one tick: two snapshots of different poses (a model swapped, -another weapon's skeleton, a pose left from seconds before) blended node by -node stretch vertices across the screen. The first-person weapon's two poses -are told apart by the weapon and its animation graph instead, since its own -animations (a rocket launcher's melee) move further in a tick than any -distance that would tell them from another weapon's. +instead of sweeping across the world, and so does an object's pose whose +nodes moved too far for one tick. First-person poses use weapon and animation +graph identity instead: fast melee motion is continuous, but blending another +weapon's skeleton node by node stretches vertices across the screen. Particles, contrails and other effects already move every frame (game_frame), so they need nothing here. @@ -47,6 +44,7 @@ tick, such as a nav marker, is moved as far as the object is drawn from there #include "game/players.h" #include "render/render_cameras.h" #include "units/units.h" +#include "third_person.h" #include "vehicle_riding.h" /* port/linux/src/port_config.c */ @@ -56,6 +54,7 @@ unsigned long config_changes(void); #include #include #include +#include "plasma_lighting.h" /* ---------- constants */ @@ -75,11 +74,9 @@ that the whole object turning moves nothing: measured in the world, a fast turn swung the head and weapon far enough to snap, and characters moved like robots.) */ #define NODE_SNAP_DISTANCE 0.4f -/* a first-person node's two rotations within about two degrees of half a -turn apart (the quaternions' dot product): which way it turned cannot be -told, and blending either way spins it through poses it never had, as the -rocket launcher's barrels set back by half a turn after a shot */ -#define FIRST_PERSON_HALF_TURN_COSINE 0.02f +/* Quaternion dot product for a rotation within about a degree of a half-turn. +The two equally short directions cannot identify an authored pose reset. */ +#define FIRST_PERSON_HALF_TURN_COSINE 0.01f /* a correction's difference left drawn after each tick (of 1) */ #define CORRECTION_DECAY 0.6f /* ... and small enough to be none */ @@ -143,7 +140,6 @@ struct interpolated_camera struct interpolated_first_person { long tick; - /* the weapon and animation graph the latest pose was of */ long weapon_index; long animation_graph_index; short node_count; @@ -521,6 +517,7 @@ void render_interpolation_frame_begin(void) void render_interpolation_frame_end(void) { interpolation_rendering = FALSE; + plasma_lighting_frame_end(); } real render_interpolation_fraction(void) @@ -732,7 +729,8 @@ static struct observer_result const *render_interpolation_direct_camera( enabled = config_boolean("display.direct_camera"); } if (!enabled || !observer || - director_get_perspective(local_player_index) != _director_perspective_first_person || + (director_get_perspective(local_player_index) != _director_perspective_first_person && + !third_person_director_active(local_player_index)) || director_inhibited_facing(local_player_index) || cinematic_in_progress()) { @@ -930,26 +928,28 @@ void render_interpolation_first_person( struct interpolation_rotation latest_rotations[MAXIMUM_INTERPOLATED_NODES]; short node_index; - if (!interpolation_rendering || - local_player_index < 0 || local_player_index >= MAXIMUM_LOCAL_PLAYERS || - node_count <= 0 || node_count > MAXIMUM_INTERPOLATED_NODES) + if (local_player_index < 0 || local_player_index >= MAXIMUM_LOCAL_PLAYERS) { return; } first_person = &interpolated_first_person[local_player_index]; + if (!interpolation_rendering || weapon_index == NONE || animation_graph_index == NONE || + node_count <= 0 || node_count > MAXIMUM_INTERPOLATED_NODES) + { + first_person->node_count = 0; + first_person->has_previous = FALSE; + return; + } matrix4x3_from_point_and_vectors(&camera_matrix, &camera->position, &camera->forward, &camera->up); matrix4x3_inverse(&camera_matrix, &inverse_camera); - if (first_person->tick != interpolation_tick || - first_person->weapon_index != weapon_index || - first_person->animation_graph_index != animation_graph_index) + if (first_person->tick != interpolation_tick || first_person->weapon_index != weapon_index || + first_person->animation_graph_index != animation_graph_index || first_person->node_count != node_count) { /* the pose drawn last, if that was at the end of the tick just before: not one left from before the view was last away from first - person (zoomed, in a vehicle, dead, in a cinematic), seconds old, and - not another weapon's or skeleton's (of as many nodes) */ + person (zoomed, in a vehicle, dead, in a cinematic), seconds old */ first_person->has_previous = first_person->tick == interpolation_tick - 1 && - first_person->node_count == node_count && - first_person->weapon_index == weapon_index && + first_person->node_count == node_count && first_person->weapon_index == weapon_index && first_person->animation_graph_index == animation_graph_index; memcpy(first_person->previous, first_person->latest, sizeof(first_person->previous)); first_person->tick = interpolation_tick; @@ -961,32 +961,37 @@ void render_interpolation_first_person( first_person->node_count = node_count; if (!first_person->has_previous) return; - /* a node's move is not limited: one weapon's own animations, a melee - or a reload, move as far in a tick as they were made to. Only a position - not a number (so written) snaps the pose. */ + /* Weapon and graph identity above distinguish different skeletons, even + with equal node counts. A distance limit mistook fast melee and reload + poses for weapon changes and held the whole pose at 30 Hz. Still refuse + non-finite displacements before writing any blended nodes. */ for (node_index = 0; node_index < node_count; node_index++) { real_matrix4x3 const *previous = &first_person->previous[node_index]; real_matrix4x3 const *latest = &first_person->latest[node_index]; - if (!(distance_squared(&previous->position, &latest->position) <= REAL_MAX)) + if (!(distance_squared(&previous->position, &latest->position) <= + REAL_MAX)) + { return; + } rotation_from_matrix(previous, &previous_rotations[node_index]); rotation_from_matrix(latest, &latest_rotations[node_index]); } for (node_index = 0; node_index < node_count; node_index++) { - struct interpolation_rotation const *previous_rotation = &previous_rotations[node_index]; - struct interpolation_rotation const *latest_rotation = &latest_rotations[node_index]; real_matrix4x3 blended; - - if (previous_rotation->is_rotation && latest_rotation->is_rotation && - fabs(previous_rotation->quaternion.i * latest_rotation->quaternion.i + - previous_rotation->quaternion.j * latest_rotation->quaternion.j + - previous_rotation->quaternion.k * latest_rotation->quaternion.k + - previous_rotation->quaternion.w * latest_rotation->quaternion.w) < FIRST_PERSON_HALF_TURN_COSINE) + struct interpolation_rotation const *previous = &previous_rotations[node_index]; + struct interpolation_rotation const *latest = &latest_rotations[node_index]; + struct interpolation_quaternion const *a = &previous->quaternion; + struct interpolation_quaternion const *b = &latest->quaternion; + + /* The stock rocket tubes reset by a half-turn after chambering. + Blending that reset invents an extra spin between otherwise equivalent + poses. Snap only that node; the hands and ordinary rotation still blend. */ + if (previous->is_rotation && latest->is_rotation && + fabs(a->i*b->i + a->j*b->j + a->k*b->k + a->w*b->w) < FIRST_PERSON_HALF_TURN_COSINE) { - /* half a turn: this node snaps, the others still blend */ blended = first_person->latest[node_index]; } else @@ -994,8 +999,8 @@ void render_interpolation_first_person( matrix_blend_rotations( &first_person->previous[node_index], &first_person->latest[node_index], - previous_rotation, - latest_rotation, + previous, + latest, interpolation_fraction, &blended); } diff --git a/port/linux/game/rocket_lighting.c b/port/linux/game/rocket_lighting.c new file mode 100644 index 0000000000..16c59778b9 --- /dev/null +++ b/port/linux/game/rocket_lighting.c @@ -0,0 +1,187 @@ +/* Stock rockets have no flight light. These bounded, render-owned glows + reuse the engine's glow interface without editing projectile/effect tags. */ +#include "cseries.h" +#include "objects/objects.h" +#include "objects/object_definitions.h" +#include "objects/object_lights.h" +#include "tag_files/tag_files.h" +#include "camera/observer.h" +#include "game/players.h" +#include "rocket_lighting.h" +#include "plasma_occlusion.h" +#include + +#include "lighting_config.h" +long light_port_glow_definition_get(void); +boolean light_port_glow_set(long light_index, long object_index, real_rgb_color const *color, real radius); + +enum { ROCKET_LIGHTS = 8 }; +static struct rocket_light +{ + int active, connected; + long object_index, light_index, rasterizer_index; +} rocket_lights[ROCKET_LIGHTS]; +static const real_rgb_color rocket_color = {1.0f, 0.45f, 0.12f}; +static const real_rgb_color rocket_black = {0.0f, 0.0f, 0.0f}; + +static int rocket_visible(long object_index) +{ + struct object_datum *object = object_try_and_get(object_index); + struct object_definition *definition; + const char *name; + short player; + int i; + if (!object || object->object.type != _object_type_projectile || + TEST_FLAG(object->object.flags, _object_invisible_bit) || + object->object.node_matrices.size < sizeof(real_matrix4x3)) + return FALSE; + name = tag_get_name(object->definition_index); + if (!name || strcmp(name, "weapons\\rocket launcher\\rocket")) + return FALSE; + definition = object_definition_get(object->definition_index); + /* A custom map's authored attachment takes precedence over a new glow. */ + for (i = 0; i < definition->object.attachments.count && i < MAXIMUM_NUMBER_OF_ATTACHMENTS_PER_OBJECT; i++) + { + struct object_attachment_definition *attachment = + TAG_BLOCK_GET_ELEMENT(&definition->object.attachments, i, struct object_attachment_definition); + if (attachment->type.group_tag == 'ligh' && attachment->type.index != NONE) + return FALSE; + } + for (player = local_player_get_next(NONE); player != NONE; player = local_player_get_next(player)) + { + const struct observer_result *camera = observer_get_camera(player); + if (camera && distance3d(&object->object.bounding_sphere_center, &camera->position) <= 25.0f) + return TRUE; + } + return FALSE; +} + +static void rocket_release(struct rocket_light *light) +{ + /* The salted handle, owner and glow definition must still match. */ + if (light->active && light_port_glow_set(light->light_index, light->object_index, &rocket_black, 0.0f)) + light_delete(light->light_index); + memset(light, 0, sizeof(*light)); +} + +void rocket_lighting_update(void) +{ + struct object_iterator iterator; + int i, slot; + int enabled = lighting_config_boolean("display.plasma_lighting"); + for (i = 0; i < ROCKET_LIGHTS; i++) + if (rocket_lights[i].active && (!enabled || !rocket_visible(rocket_lights[i].object_index))) + rocket_release(&rocket_lights[i]); + if (!enabled) + return; + object_iterator_new(&iterator, _object_mask_projectile, 0); + while (object_iterator_next(&iterator)) + { + struct rocket_light *light; + long definition; + if (!rocket_visible(iterator.index)) + continue; + slot = NONE; + for (i = 0; i < ROCKET_LIGHTS; i++) + { + if (rocket_lights[i].active && rocket_lights[i].object_index == iterator.index) + { + slot = i; + break; + } + if (!rocket_lights[i].active && slot == NONE) + slot = i; + } + if (slot == NONE) + continue; + light = &rocket_lights[slot]; + if (light->active && light_port_glow_set(light->light_index, iterator.index, &rocket_color, 1.75f)) + { + if (!light->connected) + light_reconnect_to_map(light->light_index); + light->connected = TRUE; + continue; + } + memset(light, 0, sizeof(*light)); + definition = light_port_glow_definition_get(); + if (definition == NONE) + continue; + light->light_index = light_new_unattached(definition, iterator.index, 0, + (real_point3d const *)global_zero_vector3d, global_forward3d, 0.0f); + if (light->light_index == NONE) + continue; + light->object_index = iterator.index; + light->rasterizer_index = NONE; + light->active = light->connected = TRUE; + light_port_glow_set(light->light_index, iterator.index, &rocket_color, 1.75f); + } +} + +void rocket_lighting_frame_end(void) +{ + int i; + for (i = 0; i < ROCKET_LIGHTS; i++) + { + struct rocket_light *light = &rocket_lights[i]; + if (!light->active) + continue; + if (!lighting_config_boolean("display.plasma_lighting")) + rocket_release(light); + else if (light_port_glow_set(light->light_index, light->object_index, &rocket_black, 0.0f) && light->connected) + { + light_disconnect_from_map(light->light_index); + light->connected = FALSE; + } + light->rasterizer_index = NONE; + } +} + +void rocket_lighting_forget(void) +{ + /* Called only as the engine discards its entire light array/partition. */ + memset(rocket_lights, 0, sizeof(rocket_lights)); +} + +void rocket_lighting_window_begin(void) +{ + int i; + for (i = 0; i < ROCKET_LIGHTS; i++) + rocket_lights[i].rasterizer_index = NONE; +} + +void rocket_lighting_submitted(long light_index, long rasterizer_index) +{ + int i; + for (i = 0; i < ROCKET_LIGHTS; i++) + if (rocket_lights[i].active && rocket_lights[i].light_index == light_index) + { + rocket_lights[i].rasterizer_index = rasterizer_index; + plasma_occlusion_submit(light_index, rasterizer_index); + return; + } +} + +int rocket_lighting_selected(long rasterizer_index) +{ + int i; + if (rasterizer_index == NONE || !lighting_config_boolean("display.plasma_lighting")) + return FALSE; + for (i = 0; i < ROCKET_LIGHTS; i++) + if (rocket_lights[i].active && rocket_lights[i].rasterizer_index == rasterizer_index) + return TRUE; + return FALSE; +} + +/* Visibility bounds must cover the owned flight glow, even when the map's + borrowed template describes a smaller muzzle flash. */ +float rocket_lighting_radius(long light_index, long object_index, float radius) +{ + int i; + if (!lighting_config_boolean("display.plasma_lighting")) + return radius; + for (i = 0; i < ROCKET_LIGHTS; i++) + if (rocket_lights[i].active && rocket_lights[i].light_index == light_index && + rocket_lights[i].object_index == object_index) + return MAX(radius, 1.75f); + return radius; +} diff --git a/port/linux/game/rocket_lighting.h b/port/linux/game/rocket_lighting.h new file mode 100644 index 0000000000..535adefb43 --- /dev/null +++ b/port/linux/game/rocket_lighting.h @@ -0,0 +1,13 @@ +#ifndef ROCKET_LIGHTING_H +#define ROCKET_LIGHTING_H + +void rocket_lighting_update(void); +void rocket_lighting_forget(void); +void rocket_lighting_frame_end(void); +void rocket_lighting_window_begin(void); +void rocket_lighting_submitted(long light_index, long rasterizer_index); +int rocket_lighting_selected(long rasterizer_index); + +float rocket_lighting_radius(long light_index, long object_index, float radius); + +#endif diff --git a/port/linux/game/server_director.c b/port/linux/game/server_director.c index 61112b6dc0..6e861d9562 100644 --- a/port/linux/game/server_director.c +++ b/port/linux/game/server_director.c @@ -40,6 +40,7 @@ Called from the main loop every frame (main.c). #include "network_map_vote.h" #include "server_director.h" #include "server_gametypes.h" +#include "bots.h" #include "../src/p2p.h" /* port: port/linux/src/p2p.c, p2p_lobby.c */ #include "../src/server_console.h" /* port: port/linux/src/server_console.c */ @@ -2155,7 +2156,7 @@ static void server_publish_state( server_json_object_begin(&json, NULL); server_json_string(&json, "variant", variant); server_json_string(&json, "state", server_status_state_name(server.state)); - server_json_integer(&json, "players", server_player_count()); + server_json_integer(&json, "players", bots_human_count(game)); server_json_string(&json, "map", server.current_set ? server.current.map_name : ""); server_json_string(&json, "gametype", server.current_set ? server.current.gametype : ""); server_json_object_end(&json); diff --git a/port/linux/game/shield_arcs.inl b/port/linux/game/shield_arcs.inl new file mode 100644 index 0000000000..623837d72e --- /dev/null +++ b/port/linux/game/shield_arcs.inl @@ -0,0 +1,217 @@ +/* SHIELD_ARCS.INL: Bigass sprite animation on depleted enhanced shields. +Included by shield_look.c; no simulation particles or map tags are modified. */ +#include "render/render_sprite.h" +#include "render/render.h" +#include "rasterizer/rasterizer.h" +#include "rasterizer/xbox/rasterizer_xbox_hardware_bitmaps.h" +#include "viewmodel_shield.h" +#include + +int config_boolean(const char *name); +void platform_log(const char *format, ...); +void *cache_files_tag_instances(long *count); +void cache_files_set_tag_instances(void *instances, long count); + +struct shield_arcs_tag +{ + long group, parents[2], index; + char *name; + void *address; + unsigned long unused[2]; +}; + +enum { SHIELD_ARCS_FRAMES = 31, SHIELD_ARCS_PIXELS = 172032, SHIELD_ARCS_BYTES = 345064 }; +static struct shield_arcs_tag *shield_arcs_table, *shield_arcs_original; +static long shield_arcs_original_count, shield_arcs_index = NONE; +static boolean shield_arcs_attempted; +static byte *shield_arcs_asset; +static struct bitmap_group shield_arcs_bitmap_group; +static struct bitmap_group_sequence shield_arcs_sequence; +static struct bitmap_group_sprite shield_arcs_sprites[SHIELD_ARCS_FRAMES]; +static struct bitmap_data shield_arcs_bitmaps[2]; + +/* Runs after texture-cache shutdown, before other appended tables unwind. */ +void shield_arcs_unload(void) +{ + short i; + if (shield_arcs_original) + cache_files_set_tag_instances(shield_arcs_original, shield_arcs_original_count); + for (i = 0; i < 2; i++) + if (shield_arcs_bitmaps[i].hardware_format) + rasterizer_bitmap_delete(&shield_arcs_bitmaps[i]); + if (shield_arcs_table) + free(shield_arcs_table); + if (shield_arcs_asset) + free(shield_arcs_asset); + shield_arcs_table = shield_arcs_original = NULL; + shield_arcs_asset = NULL; + shield_arcs_index = NONE; + shield_arcs_attempted = FALSE; + memset(shield_arcs_bitmaps, 0, sizeof(shield_arcs_bitmaps)); +} + +static boolean shield_arcs_load(void) +{ + FILE *file; + long count, i; + struct shield_arcs_tag *original; + struct bitmap_data *bitmap; + struct bitmap_group_sprite *sprite; + short j; + if (shield_arcs_attempted) + return shield_arcs_index != NONE; + shield_arcs_attempted = TRUE; + file = fopen("d:\\shield_assets\\bigass_arcs.bin", "rb"); + if (!file) + { + platform_log("shield arcs: install shield_assets/bigass_arcs.bin with tools/extract_shield_arcs.py"); + return FALSE; + } + shield_arcs_asset = malloc(SHIELD_ARCS_BYTES); + if (!shield_arcs_asset || fread(shield_arcs_asset, 1, SHIELD_ARCS_BYTES, file) != SHIELD_ARCS_BYTES || + fgetc(file) != EOF || memcmp(shield_arcs_asset, "GCARCS1", 8)) + { + fclose(file); + goto failed; + } + fclose(file); + memcpy(shield_arcs_sprites, shield_arcs_asset + 8, sizeof(shield_arcs_sprites)); + for (i = 0; i < SHIELD_ARCS_FRAMES; i++) + { + sprite = &shield_arcs_sprites[i]; + if (sprite->bitmap_index < 0 || sprite->bitmap_index > 1) + goto failed; + for (j = 0; j < 4; j++) + if (!(sprite->bounds.n[j] >= 0.f && sprite->bounds.n[j] <= 1.f)) + goto failed; + if (!(sprite->bounds.x0 < sprite->bounds.x1 && sprite->bounds.y0 < sprite->bounds.y1 && + sprite->registration_point.x >= 0.f && sprite->registration_point.x <= 1.f && + sprite->registration_point.y >= 0.f && sprite->registration_point.y <= 1.f)) + goto failed; + } + original = cache_files_tag_instances(&count); + if (!original || count < 0 || count >= 32767) + goto failed; + shield_arcs_table = malloc((count + 1) * sizeof(*shield_arcs_table)); + if (!shield_arcs_table) + goto failed; + memcpy(shield_arcs_table, original, count * sizeof(*original)); + memset(&shield_arcs_table[count], 0, sizeof(*original)); + /* The new absolute slot cannot collide with an existing handle. */ + shield_arcs_index = (0x6000L << 16) | count; + shield_arcs_table[count].group = 'bitm'; + shield_arcs_table[count].parents[0] = shield_arcs_table[count].parents[1] = NONE; + shield_arcs_table[count].index = shield_arcs_index; + shield_arcs_table[count].name = "gulch\\shield_arcs"; + shield_arcs_table[count].address = &shield_arcs_bitmap_group; + memset(&shield_arcs_bitmap_group, 0, sizeof(shield_arcs_bitmap_group)); + memset(&shield_arcs_sequence, 0, sizeof(shield_arcs_sequence)); + shield_arcs_bitmap_group.type = 4; + shield_arcs_bitmap_group.sequences.count = 1; + shield_arcs_bitmap_group.sequences.address = &shield_arcs_sequence; + shield_arcs_bitmap_group.bitmaps.count = 2; + shield_arcs_bitmap_group.bitmaps.address = shield_arcs_bitmaps; + shield_arcs_sequence.sprites.count = SHIELD_ARCS_FRAMES; + shield_arcs_sequence.sprites.address = shield_arcs_sprites; + for (i = 0; i < 2; i++) + { + bitmap = &shield_arcs_bitmaps[i]; + bitmap->signature = 'bitm'; + bitmap->width = bitmap->height = 512; + bitmap->depth = 1; + bitmap->format = 14; + bitmap->flags = 3; /* power-of-two, compressed; privately owned, not cached */ + bitmap->mipmap_count = 2; + bitmap->pixels_size = SHIELD_ARCS_PIXELS; + bitmap->tag_index = shield_arcs_index; + bitmap->cache_block_index = NONE; + bitmap->base_address = shield_arcs_asset + 8 + sizeof(shield_arcs_sprites) + i * SHIELD_ARCS_PIXELS; + if (!rasterizer_bitmap_new(bitmap)) + goto failed; + rasterizer_bitmap_changed(bitmap); + } + shield_arcs_original = original; + shield_arcs_original_count = count; + cache_files_set_tag_instances(shield_arcs_table, count + 1); + return TRUE; +failed: + shield_arcs_unload(); + shield_arcs_attempted = TRUE; + platform_log("shield arcs: invalid asset or unavailable texture; normal shields retained"); + return FALSE; +} + +static boolean shield_arcs_active(struct object_datum const *object, boolean arms) +{ + return shield_look_enabled() && (!arms || config_boolean("display.viewmodel_shield")) && + shield_look_player(object) && + !TEST_FLAG(object->object.damage_flags, _object_dead_bit) && + TEST_FLAG(object->object.damage_flags, _object_shield_depleted_bit) && + object->object.shield_vitality <= 0.f && object->object.shield_stun_ticks > 0; +} + +/* Integer hashing supplies visual variation without consuming game RNG. */ +static uint32_t shield_arcs_random(uint32_t value) +{ + value ^= value >> 16; + value *= UINT32_C(0x7FEB352D); + value ^= value >> 15; + value *= UINT32_C(0x846CA68B); + return value ^ (value >> 16); +} + +void shield_arcs_draw(long object_index, long model_index, real_matrix4x3 const *nodes, + struct render_model_effect const *effect, boolean arms) +{ + struct object_datum *object = object_try_and_get(object_index); + struct model *model; + struct build_sprite_data sprites; + real time, phase, life, age, fade, radius, offset; + real_point3d position; + real_vector3d direction; + real_rgb_color parallel; + real_argb_color color; + uint32_t seed, cycle; + short slot, node, count; + if (!shield_arcs_active(object, arms) || !nodes || !effect || (arms && !effect->modifier_shader)) + return; + model = model_definition_get(model_index); + if (!cache_file_tag_cache_contains(model, sizeof(*model)) || model->nodes.count < 2 || + model->nodes.count > MAXIMUM_NODES_PER_MODEL || !shield_arcs_load()) + return; + time = global_frame_parameters.game_time_sec; + if (!(time >= 0.f && time < 10000000.f)) + return; + color.alpha = 1.f; + color.red = color.green = color.blue = 1.f; + parallel = color.rgb; + if (effect->modifier_shader) + shield_look_colors(effect->modifier_shader, object->object.outgoing_change_colors, &color.rgb, ¶llel); + count = arms ? 2 : 6; + build_sprites_begin(&sprites, count, shield_arcs_index, &global_shader_effect_additive, + arms ? FLAG(_build_sprites_first_person_bit) : 0); + for (slot = 0; slot < count; slot++) + { + phase = time + slot * 0.173f; + cycle = (uint32_t)phase; + age = phase - (real)cycle; + seed = shield_arcs_random((uint32_t)object_index ^ (cycle * 31 + slot * 997)); + life = 0.5f + (seed & 255) * (0.5f / 255.f); + if (age >= life) + continue; + node = 1 + ((seed >> 8) % (model->nodes.count - 1)); + position = nodes[node].position; + vector_from_points3d(&position, &render.camera.position, &direction); + normalize3d(&direction); + offset = arms ? viewmodel_shield_offset_amount(effect->modifier_animation.values, 0.03f) : 0.025f; + point_from_line3d(&position, &direction, offset, &position); + radius = (arms ? 0.025f : 0.05f) * (1.f + ((seed >> 16) & 255) / 255.f); + fade = age < 0.05f ? age / 0.05f : 1.f; + if (life - age < 0.15f) + fade *= (life - age) / 0.15f; + /* Bigass's 31-frame sequence runs at 30 fps with radius 0.05-0.1. */ + build_sprite(&sprites, _build_sprite_normal, 0, ((short)(age * 30.f)) % SHIELD_ARCS_FRAMES, + &position, &direction, 0.f, radius * 0.016f, &color, fade, 0); + } + build_sprites_end(&sprites); +} diff --git a/port/linux/game/shield_color.c b/port/linux/game/shield_color.c deleted file mode 100644 index 80e659de2d..0000000000 --- a/port/linux/game/shield_color.c +++ /dev/null @@ -1,122 +0,0 @@ -/* -SHIELD_COLOR.C - -Your energy shield's color, as this machine draws it (Video Setup > FOV and -Viewmodels > Shield Color): the flare in one of the multiplayer armor colors -instead of the shield's own, whatever color the armor is. The shield's own -shader is drawn, only its two colors are replaced, keeping their brightness: -no new assets. Others see your shield as their own settings draw it. - -Only the drawing is changed; the shield itself is the game's. -*/ - -#include "cseries.h" -#include "real_math.h" -#include "objects/objects.h" -#include "units/units.h" -#include "game/players.h" -#include "saved games/player_profile.h" - -#include - -/* port/linux/src/port_config.c */ -const char *config_string(const char *name); -unsigned long config_changes(void); - -/* the multiplayer armor colors, in the profile's order (player_profile.c) */ -static char const *const shield_color_names[] = -{ - "white", "black", "red", "blue", "gray", "yellow", "green", "pink", "purple", - "cyan", "cobalt", "orange", "teal", "sage", "brown", "tan", "maroon", "salmon", -}; - -static unsigned long shield_color_changes = (unsigned long)-1; -static short shield_color_index = NONE; - -static void shield_color_update( - void) -{ - char const *value; - short index; - - if (shield_color_changes == config_changes()) - return; - shield_color_changes = config_changes(); - shield_color_index = NONE; - value = config_string("display.shield_color"); - for (index = 0; value && index < (short)NUMBEROF(shield_color_names); index++) - { - if (!strcmp(value, shield_color_names[index])) - shield_color_index = index; - } -} - -/* the colors a unit's shield is drawn with, given the unit's own: when the -unit is a local player's and a color is chosen, a copy of them that -shield_color_override knows again; otherwise the unit's own */ -static real_rgb_color shield_color_marker[MAXIMUM_NUMBER_OF_LOCAL_PLAYERS][4]; - -real_rgb_color const *shield_color_colors( - long unit_index, - real_rgb_color const *colors) -{ - short local_player_index; - - shield_color_update(); - if (shield_color_index == NONE || !colors) - return colors; - for (local_player_index = 0; local_player_index < MAXIMUM_NUMBER_OF_LOCAL_PLAYERS; local_player_index++) - { - long player_index = local_player_get_player_index(local_player_index); - - if (player_index != NONE && player_get(player_index)->unit_index == unit_index) - { - csmemcpy(shield_color_marker[local_player_index], colors, sizeof(shield_color_marker[local_player_index])); - return shield_color_marker[local_player_index]; - } - } - return colors; -} - -/* the chosen color, when a plasma shader is drawn with colors from -shield_color_colors (FALSE: drawn as it is) */ -boolean shield_color_override( - real_rgb_color const *colors, - real_rgb_color *chosen) -{ - short local_player_index; - - if (!colors || shield_color_index == NONE) - return FALSE; - for (local_player_index = 0; local_player_index < MAXIMUM_NUMBER_OF_LOCAL_PLAYERS; local_player_index++) - { - if (colors == shield_color_marker[local_player_index]) - { - *chosen = player_profile_get_rgb_color(shield_color_index); - return TRUE; - } - } - return FALSE; -} - -/* a shield color in place of one of the shader's own: the chosen hue at the -original's brightness (its brightest channel) */ -void shield_color_apply( - real_rgb_color const *chosen, - real_rgb_color const *original, - real_rgb_color *result) -{ - real brightness = MAX(original->red, MAX(original->green, original->blue)); - real peak = MAX(chosen->red, MAX(chosen->green, chosen->blue)); - - if (peak <= 0.f) - { - /* (black: the flare is added to what is behind it, so black would - not show at all; a dark smoke-grey instead) */ - result->red = result->green = result->blue = brightness * 0.12f; - return; - } - result->red = chosen->red / peak * brightness; - result->green = chosen->green / peak * brightness; - result->blue = chosen->blue / peak * brightness; -} diff --git a/port/linux/game/shield_glow.c b/port/linux/game/shield_glow.c index 59e622bc50..1024563885 100644 --- a/port/linux/game/shield_glow.c +++ b/port/linux/game/shield_glow.c @@ -1,101 +1,77 @@ -/* -SHIELD_GLOW.C - -The energy shield's glow (Video Setup > Graphics > Shield Glow, -display.shield_glow): as a unit's shield flares (hit, charging, falling), -it lights what is around it, as a plasma bolt does, in the shield's own -color: a Spartan's gold, an Elite's blue. display.shield_glow_intensity -"light_show" makes it reach three times as far, and at full strength from a -third of the flare (a light is no brighter than full: the game's lights' -colors go to 1). - -The flare's strength is the shield shader's own: the intensity its plasma is -drawn with (its intensity source, an object function of the unit, to its -exponent), so the glow rises and falls with the flare seen on the body. Its -color is the shader's edge color at full brightness. The light is an -ordinary dynamic light of the game's (light_new_unattached, which -object_lights.c's light_port_glow_set colors and sizes), drawn with a light -definition the map already has: no new assets. The units that glow are those -near any local player's camera, the same for each of a split screen's views -(lights_preprocess_scene runs for each), so each keeps its one light. - -Only the drawing changes: nothing the game simulates, nothing sent between -machines. -*/ - +/* Optional shield illumination. Surface appearance and host policy remain + owned by their existing modules; these lights exist only during rendering. */ #include "cseries.h" #include "real_math.h" #include "objects/objects.h" #include "objects/object_definitions.h" -#include "render/render.h" +#include "objects/object_lights.h" #include "rasterizer/rasterizer.h" +#include "rasterizer/rasterizer_model_types.h" #include "shaders/shader_definitions.h" #include "shaders/shaders.h" #include "units/units.h" #include "camera/observer.h" #include "game/players.h" -#include "objects/object_lights.h" #include "network_shield_effects.h" - +#include "shield_glow.h" +#include "shield_look.h" +#include "overshield_effect.h" +#include "plasma_occlusion.h" #include #include -/* port/linux/src/port_config.c */ int config_boolean(const char *name); const char *config_string(const char *name); unsigned long config_changes(void); - -/* object_lights.c (port) */ +real render_interpolation_game_time_sec(long ticks); long light_port_glow_definition_get(void); -boolean light_port_glow_set(long light_index, long object_index, real_rgb_color const *color, real radius); -/* port/linux/game/overshield_effect.c */ -real overshield_effect_flare(long unit_index); -real_rgb_color const *overshield_effect_glow_color(void); +boolean light_port_glow_set(long light, long owner, real_rgb_color const *color, real radius); +boolean light_port_glow_move(long light, real_point3d const *position); -enum -{ - SHIELD_GLOW_MAXIMUM = 8, - _shader_type_transparent_plasma_glow = 10, /* (shader_get_and_verify_type's plasma) */ -}; - -/* units this far from the camera and nearer glow (world units) */ +enum { SHIELD_GLOW_MAXIMUM = 8 }; #define SHIELD_GLOW_RANGE 25.f -/* how far the glow reaches, world units: at the flare's least and its most */ -#define SHIELD_GLOW_RADIUS_MINIMUM 0.5f -#define SHIELD_GLOW_RADIUS_MAXIMUM 1.4f -/* a flare fainter than this lights nothing */ -#define SHIELD_GLOW_THRESHOLD 0.03f -/* the plasma shader's fields after its header (rasterizer_xbox_plasma_energy.c's) */ +/* The validated plasma layout after struct shader, as used by its renderer. */ struct shield_glow_plasma { byte reserved00[4]; - short intensity_exponent_source; - short pad06; + short intensity_exponent_source, pad06; real intensity_exponent; byte reserved0C[0x2C]; real perpendicular_alpha; real_rgb_color perpendicular_color; real parallel_alpha; real_rgb_color parallel_color; + short color_source; }; - struct shield_glow { - long unit_index; /* NONE: free */ - long light_index; - unsigned long frame; + long unit_index, light_index, rasterizer; + real strength, last_time, radius; + boolean connected; +}; +struct shield_glow_sample +{ + long unit_index; + real strength, radius, score; + real_rgb_color color; + real_point3d position; }; - static struct shield_glow shield_glows[SHIELD_GLOW_MAXIMUM]; -static unsigned long shield_glow_frame = 0; - static real shield_glow_scale = 1.f; +static real shield_glow_time; + +void shield_glow_reset(void) +{ + short i; + memset(shield_glows, 0, sizeof(shield_glows)); + for (i = 0; i < SHIELD_GLOW_MAXIMUM; i++) + shield_glows[i].unit_index = shield_glows[i].light_index = shield_glows[i].rasterizer = NONE; + shield_glow_time = 0.f; + overshield_effect_reset(); +} -/* display.shield_glow, and its intensity (display.shield_glow_intensity): -"default", or "light_show", three times as bright and as far; in a network -game, the host's (network_shield_effects.c) */ -static boolean shield_glow_enabled( +boolean shield_glow_enabled( void) { static unsigned long changes = (unsigned long)-1; @@ -120,179 +96,255 @@ static boolean shield_glow_enabled( return enabled; } -/* a glow's light, on the unit's root node (NONE: none, or the map has no -light definition to draw it with) */ -static long shield_glow_light_new( - long unit_index) + + +static void shield_glow_release(struct shield_glow *glow) { - long definition_index = light_port_glow_definition_get(); + if (glow->light_index != NONE && + light_port_glow_set(glow->light_index, NONE, global_real_rgb_black, 0.f)) + light_delete(glow->light_index); + memset(glow, 0, sizeof(*glow)); + glow->unit_index = glow->light_index = glow->rasterizer = NONE; +} - if (definition_index == NONE) - return NONE; - return light_new_unattached(definition_index, unit_index, 0, (real_point3d const *)global_zero_vector3d, - global_forward3d, 0.0f); +static struct shield_glow *shield_glow_find(long unit_index) +{ + short i; + for (i = 0; i < SHIELD_GLOW_MAXIMUM; i++) + if (shield_glows[i].unit_index == unit_index) + return &shield_glows[i]; + return NULL; } -/* how far a point is from the nearest local player's camera */ -static real shield_glow_camera_distance( - real_point3d const *point) +static real shield_glow_camera_distance(real_point3d const *point) { real nearest = SHIELD_GLOW_RANGE * 2.f; - short local_player_index; - - for (local_player_index = local_player_get_next(NONE); local_player_index != NONE; - local_player_index = local_player_get_next(local_player_index)) + short player; + for (player = local_player_get_next(NONE); player != NONE; player = local_player_get_next(player)) { - struct observer_result const *camera = observer_get_camera(local_player_index); - real distance = camera ? distance3d(point, &camera->position) : nearest; - - if (distance < nearest) - nearest = distance; + struct observer_result const *camera = observer_get_camera(player); + if (camera) + nearest = MIN(nearest, distance3d(point, &camera->position)); } return nearest; } -/* a unit's flare now: its strength (0: none) and color */ -static real shield_glow_flare( - long unit_index, - real_rgb_color *color) +static boolean shield_glow_sample(long index, struct shield_glow_sample *sample) { - struct object_datum *object = object_try_and_get(unit_index); + struct object_datum *object = object_try_and_get(index); struct object_definition *definition; - struct shader *shader; struct shield_glow_plasma const *plasma; - short source; - real value; - real peak; - - if (!object || TEST_FLAG(object->object.flags, _object_invisible_bit)) - return 0.f; + struct shader *shader; + struct render_model_effect effect; + real_rgb_color parallel, tint = *global_real_rgb_white; + real_matrix4x3 *nodes; + real coverage = 1.f, intensity = 1.f, offset = 0.f, peak, distance, bottom, top; + short source, i, count; + boolean overshield; + if (!object || TEST_FLAG(object->object.flags, _object_invisible_bit) || + TEST_FLAG(object->object.damage_flags, _object_dead_bit)) + return FALSE; + distance = shield_glow_camera_distance(&object->object.bounding_sphere_center); + if (distance >= SHIELD_GLOW_RANGE) + return FALSE; definition = object_definition_get(object->definition_index); if (!definition || definition->object.modifier_shader.index == NONE) - return 0.f; - shader = shader_definition_get(definition->object.modifier_shader.index); - if (!shader || shader->base.type != _shader_type_transparent_plasma_glow) - return 0.f; + return FALSE; + shader = shield_look_body(index, shader_definition_get(definition->object.modifier_shader.index)); + if (!shader || shader->base.type != 10) + return FALSE; plasma = (struct shield_glow_plasma const *)((byte const *)shader + sizeof(struct shader)); - source = plasma->intensity_exponent_source; - if (source < 1 || source > 4) - return 0.f; - value = object->object.outgoing_function_values[source - 1]; - /* (an overshield: lit as it rises, then whole while it lasts) */ + sample->color = plasma->perpendicular_color; + parallel = plasma->parallel_color; + shield_look_colors(shader, object->object.outgoing_change_colors, &sample->color, ¶llel); + overshield = overshield_effect_light_sample(index, &tint, &coverage); + if (overshield) { - real overshield = overshield_effect_flare(unit_index); - - if (overshield >= 0.f) - value = overshield; + /* Match the surface's layer hue while retaining the selected brightness. */ + peak = MAX(sample->color.red, MAX(sample->color.green, sample->color.blue)) / + MAX(tint.red, MAX(tint.green, tint.blue)); + sample->color.red = tint.red * peak; + sample->color.green = tint.green * peak; + sample->color.blue = tint.blue * peak; + intensity = coverage; } - if (!(value > 0.f)) - return 0.f; - value = (real)pow((double)value, (double)plasma->intensity_exponent); - - *color = plasma->perpendicular_color; - /* (an overshield: its own color) */ - if (overshield_effect_flare(unit_index) >= 0.f) - *color = *overshield_effect_glow_color(); - peak = MAX(color->red, MAX(color->green, color->blue)); - if (!(peak > 0.f)) - return 0.f; - color->red /= peak; - color->green /= peak; - color->blue /= peak; - if (unit_get(unit_index)->unit.active_camouflage > 0.f) - value *= 1.f - unit_get(unit_index)->unit.active_camouflage; - return PIN(value, 0.f, 1.f); -} - -static struct shield_glow *shield_glow_find( - long unit_index, - boolean make) -{ - struct shield_glow *free_glow = NULL; - short index; - - for (index = 0; index < SHIELD_GLOW_MAXIMUM; index++) + else { - if (shield_glows[index].unit_index == unit_index) - return &shield_glows[index]; - if (shield_glows[index].unit_index == NONE && !free_glow) - free_glow = &shield_glows[index]; + source = plasma->color_source; + if (source >= 1 && source <= 4) + { + tint = object->object.outgoing_change_colors[source - 1]; + sample->color.red *= tint.red; + sample->color.green *= tint.green; + sample->color.blue *= tint.blue; + } + source = plasma->intensity_exponent_source; + if (source >= 1 && source <= 4) + intensity = (real)pow(MAX(0.f, object->object.outgoing_function_values[source - 1]), plasma->intensity_exponent); + memset(&effect, 0, sizeof(effect)); + effect.modifier_shader = shader; + effect.modifier_animation.values = object->object.outgoing_function_values; + effect.modifier_animation.colors = object->object.outgoing_change_colors; + shield_recharge_prepare(index, &effect, FALSE); + shield_recharge_draw(shader, effect.modifier_animation.values, &intensity, &offset); } - if (!make || !free_glow) - return NULL; - free_glow->unit_index = unit_index; - free_glow->light_index = NONE; - return free_glow; + peak = MAX(sample->color.red, MAX(sample->color.green, sample->color.blue)); + if (!(peak > 0.f) || !valid_real(peak) || !valid_real(intensity)) + return FALSE; + /* Normalize only overbright shaders; a deliberately dark shader stays dark. */ + peak = MAX(peak, 1.f); + sample->color.red /= peak; sample->color.green /= peak; sample->color.blue /= peak; + sample->strength = PIN(intensity * shield_glow_scale, 0.f, 1.f) * + (1.f - PIN(unit_get(index)->unit.active_camouflage, 0.f, 1.f)); + /* Fade admission over the last three world units, not at a hard distance. */ + sample->strength *= PIN((SHIELD_GLOW_RANGE - distance) / 3.f, 0.f, 1.f); + count = object->object.node_matrices.size / sizeof(real_matrix4x3); + if (count <= 0) + return FALSE; + nodes = object_get_node_matrices(index); + bottom = top = nodes[0].position.z; + for (i = 1; i < count; i++) + { + bottom = MIN(bottom, nodes[i].position.z); + top = MAX(top, nodes[i].position.z); + } + /* A radial approximation of the currently luminous body, not an AR cone. + Crouching naturally lowers its centre and reduces its reach. */ + sample->position = nodes[0].position; + sample->position.z = bottom + (top - bottom) * (overshield ? 0.5f * coverage : 0.5f); + sample->radius = 1.4f * PIN((top - bottom) / 0.9f, 0.65f, 2.f) * shield_glow_scale; + sample->unit_index = index; + sample->score = sample->strength * sample->radius * sample->radius / (1.f + distance * distance); + return TRUE; } -/* each frame, before the lights are gathered (lights_preprocess_scene) */ -void shield_glow_update( - void) +/* Sorted, bounded selection with an incumbent bonus prevents equal lights + trading places every view. All local cameras contribute to distance. */ +void shield_glow_update(void) { - static boolean initialized = FALSE; + struct shield_glow_sample candidates[SHIELD_GLOW_MAXIMUM], sample; struct object_iterator iterator; - short index; - - if (!initialized) - { - for (index = 0; index < SHIELD_GLOW_MAXIMUM; index++) - shield_glows[index].unit_index = NONE; - initialized = TRUE; - } - shield_glow_frame++; - if (shield_glow_enabled()) + real now = render_interpolation_game_time_sec(game_time_get()); + short count = 0, i, j; + boolean enabled = shield_glow_enabled(); + if (!enabled || now < shield_glow_time) + for (i = 0; i < SHIELD_GLOW_MAXIMUM; i++) + shield_glow_release(&shield_glows[i]); + shield_glow_time = now; + if (!enabled) + return; + object_iterator_new(&iterator, _object_mask_unit, 0); + while (object_iterator_next(&iterator)) { - object_iterator_new(&iterator, _object_mask_unit, 0); - while (object_iterator_next(&iterator)) + struct shield_glow *glow; + if (!shield_glow_sample(iterator.index, &sample)) + continue; + glow = shield_glow_find(iterator.index); + if (glow) { - struct object_datum *object = object_get(iterator.index); - real_rgb_color color; - real flare; - struct shield_glow *glow; - - if (shield_glow_camera_distance(&object->object.bounding_sphere_center) > SHIELD_GLOW_RANGE) + /* Retain a fading light until its release is visually negligible. */ + sample.score = MAX(sample.score, glow->strength * 0.001f) * 1.2f; + if (sample.strength < 0.002f && glow->strength < 0.002f) continue; - flare = shield_glow_flare(iterator.index, &color); - glow = shield_glow_find(iterator.index, flare > SHIELD_GLOW_THRESHOLD); - if (!glow) - continue; - if (flare <= SHIELD_GLOW_THRESHOLD) - continue; /* (let go below) */ - if (glow->light_index == NONE) - glow->light_index = shield_glow_light_new(iterator.index); - /* (brighter, to full, every channel alike: the shield's color - kept) */ - { - real strength = MIN(flare * shield_glow_scale, 1.f); - - color.red *= strength; - color.green *= strength; - color.blue *= strength; - } - if (glow->light_index != NONE && - light_port_glow_set(glow->light_index, iterator.index, &color, - (SHIELD_GLOW_RADIUS_MINIMUM + (SHIELD_GLOW_RADIUS_MAXIMUM - SHIELD_GLOW_RADIUS_MINIMUM) * flare) * - shield_glow_scale)) - { - glow->frame = shield_glow_frame; - } - else - { - glow->light_index = NONE; - } } + else if (sample.strength < 0.006f) + continue; + for (i = 0; i < count && candidates[i].score >= sample.score; i++) {} + if (i == SHIELD_GLOW_MAXIMUM) + continue; + if (count < SHIELD_GLOW_MAXIMUM) count++; + for (j = count - 1; j > i; j--) candidates[j] = candidates[j - 1]; + candidates[i] = sample; } - /* (a glow not kept this frame: dark, and let go; its light goes a moment - after, as the game's own passing lights do) */ - for (index = 0; index < SHIELD_GLOW_MAXIMUM; index++) + for (i = 0; i < SHIELD_GLOW_MAXIMUM; i++) { - struct shield_glow *glow = &shield_glows[index]; + for (j = 0; j < count && candidates[j].unit_index != shield_glows[i].unit_index; j++) {} + if (j == count) shield_glow_release(&shield_glows[i]); + } + for (i = 0; i < count; i++) + { + struct shield_glow *glow = shield_glow_find(candidates[i].unit_index); + real_rgb_color color; + real blend; + long definition; + sample = candidates[i]; + if (!glow) + { + for (j = 0; j < SHIELD_GLOW_MAXIMUM && shield_glows[j].unit_index != NONE; j++) {} + if (j == SHIELD_GLOW_MAXIMUM) continue; + glow = &shield_glows[j]; + glow->unit_index = sample.unit_index; + glow->last_time = now; + glow->strength = sample.strength; /* do not lose a short hit on admission */ + } + blend = 1.f - (real)exp(-PIN(now - glow->last_time, 0.f, 0.25f) / + (sample.strength > glow->strength ? 0.015 : 0.08)); + glow->strength += (sample.strength - glow->strength) * blend; + glow->last_time = now; + glow->radius = sample.radius; + color.red = sample.color.red * glow->strength; + color.green = sample.color.green * glow->strength; + color.blue = sample.color.blue * glow->strength; + if (glow->light_index == NONE) + { + definition = light_port_glow_definition_get(); + if (definition != NONE) + glow->light_index = light_new_unattached(definition, NONE, 0, &sample.position, global_forward3d, 0.f); + } + if (!light_port_glow_set(glow->light_index, NONE, &color, sample.radius) || + !light_port_glow_move(glow->light_index, &sample.position)) + shield_glow_release(glow); + else + glow->connected = TRUE; + } +} - if (glow->unit_index == NONE || glow->frame == shield_glow_frame) - continue; - if (glow->light_index != NONE) - light_port_glow_set(glow->light_index, glow->unit_index, global_real_rgb_black, 0.f); - glow->unit_index = NONE; - glow->light_index = NONE; +void shield_glow_frame_end(void) +{ + short i; + boolean enabled = shield_glow_enabled(); + for (i = 0; i < SHIELD_GLOW_MAXIMUM; i++) + { + struct shield_glow *glow = &shield_glows[i]; + if (!enabled) shield_glow_release(glow); + else if (glow->connected && light_port_glow_set(glow->light_index, NONE, global_real_rgb_black, 0.f)) + light_disconnect_from_map(glow->light_index); + glow->connected = FALSE; + glow->rasterizer = NONE; } } + +void shield_glow_window_begin(void) +{ + short i; + for (i = 0; i < SHIELD_GLOW_MAXIMUM; i++) shield_glows[i].rasterizer = NONE; +} + +void shield_glow_submitted(long light, long rasterizer) +{ + short i; + for (i = 0; i < SHIELD_GLOW_MAXIMUM; i++) + if (shield_glows[i].unit_index != NONE && shield_glows[i].light_index == light) + { + shield_glows[i].rasterizer = rasterizer; + plasma_occlusion_submit(light, rasterizer); + } +} + +boolean shield_glow_selected(long rasterizer) +{ + short i; + if (rasterizer == NONE || !shield_glow_enabled()) return FALSE; + for (i = 0; i < SHIELD_GLOW_MAXIMUM; i++) + if (shield_glows[i].unit_index != NONE && shield_glows[i].rasterizer == rasterizer) return TRUE; + return FALSE; +} + +float shield_glow_radius(long light, float radius) +{ + short i; + for (i = 0; i < SHIELD_GLOW_MAXIMUM; i++) + if (shield_glows[i].unit_index != NONE && shield_glows[i].light_index == light && light != NONE) + return MAX(radius, shield_glows[i].radius); + return radius; +} diff --git a/port/linux/game/shield_glow.h b/port/linux/game/shield_glow.h new file mode 100644 index 0000000000..472be83bae --- /dev/null +++ b/port/linux/game/shield_glow.h @@ -0,0 +1,11 @@ +#ifndef SHIELD_GLOW_H +#define SHIELD_GLOW_H +boolean shield_glow_enabled(void); +void shield_glow_reset(void); +void shield_glow_update(void); +void shield_glow_frame_end(void); +void shield_glow_window_begin(void); +void shield_glow_submitted(long light, long rasterizer); +boolean shield_glow_selected(long rasterizer); +float shield_glow_radius(long light, float radius); +#endif diff --git a/port/linux/game/shield_look.c b/port/linux/game/shield_look.c new file mode 100644 index 0000000000..178359e938 --- /dev/null +++ b/port/linux/game/shield_look.c @@ -0,0 +1,518 @@ +/* +SHIELD_LOOK.C + +Optional plasma profiles overriding player biped shield materials. The map owns its tags and pixels; this module owns only +the draw-time shader copies. See docs/shield_look.md for the inspected +data, appearance precedence and shared-engine hooks. +*/ + +#include "cseries.h" +#include "cseries/cseries_windows.h" +#include "real_math.h" +#include "bitmaps/bitmap_group.h" +#include "cache/cache_files.h" +#include "game/game_globals.h" +#include "game/players.h" +#include "models/model_definitions.h" +#include "objects/objects.h" +#include "objects/object_definitions.h" +#include "rasterizer/rasterizer_model_types.h" +#include "scenario/scenario.h" +#include "shaders/shader_definitions.h" +#include "shaders/shaders.h" +#include "units/units.h" +#include "shield_look.h" + +#include +#include +#include +#include + +const char *config_string(const char *name); + +/* Plasma tag layout, shared by the validated Xbox, CE and MCC runtime +tags. Keep the references intact: each map's own texture cache serves them. */ +struct shield_look_plasma +{ + struct shader shader; + byte reserved28[4]; + short intensity_source; + short pad2E; + real intensity_exponent; + short offset_source; + short pad36; + real offset_amount; + real offset_exponent; + byte reserved40[0x20]; + real perpendicular_alpha; + real_rgb_color perpendicular_color; + real parallel_alpha; + real_rgb_color parallel_color; + short color_source; + byte reserved82[0x3E]; + real primary_period; + real_vector3d primary_direction; + real primary_scale; + struct tag_reference primary_map; + byte reservedE4[0x24]; + real secondary_period; + real_vector3d secondary_direction; + real secondary_scale; + struct tag_reference secondary_map; + byte reserved12C[0x20]; +}; + +typedef char shield_look_plasma_size_check[sizeof(struct shield_look_plasma) == 0x14C ? 1 : -1]; +typedef char shield_look_primary_map_check[offsetof(struct shield_look_plasma, primary_map) == 0xD4 ? 1 : -1]; +typedef char shield_look_secondary_map_check[offsetof(struct shield_look_plasma, secondary_map) == 0x11C ? 1 : -1]; + +struct shield_look_model_shader +{ + struct tag_reference shader; + short permutation; + short pad; + long unused[3]; +}; + +enum { SHIELD_LOOK_MAXIMUM = 64 }; +struct shield_look_entry +{ + long definition_index; + long hands_index; + long model_index; + struct shader const *authored_modifier; + boolean eligible; + boolean sprinkles; + boolean honeycomb; + struct shield_look_plasma body; + struct shield_look_plasma arms; +}; + +/* Never recycled during a map: transparent draw packets retain pointers +until they are submitted, including each split-screen view. */ +static struct shield_look_entry shield_looks[SHIELD_LOOK_MAXIMUM]; +static short shield_look_count; +static boolean shield_look_noise_searched; +static long shield_look_noise_index = NONE; + +static boolean shield_look_enabled(void) +{ + char const *value = config_string("display.shield_look"); + return value && (!strcmp(value, "enhanced") || !strcmp(value, "enhanced2") || + !strcmp(value, "classic_with_sprinkles") || !strcmp(value, "classic_honeycomb2")); +} + +/* Ownership is per instance, never per model or definition: AI can share +player assets. The unit player index also covers remote and co-op players. */ +static boolean shield_look_player(struct object_datum const *object) +{ + return object && object->object.type == _object_type_biped && + ((struct unit_datum const *)object)->unit.player_index != NONE; +} + +static uint32_t shield_look_hash(uint32_t hash, void const *data, size_t size) +{ + byte const *bytes = data; + size_t index; + + for (index = 0; index < size; index++) + hash = (hash ^ bytes[index]) * UINT32_C(16777619); + return hash; +} + +static boolean shield_look_stock_noise(long tag_index) +{ + struct bitmap_group *group; + struct bitmap_data *bitmap; + byte *pixels; + long size; + uint32_t hash; + boolean complete = FALSE; + + if (tag_index == NONE || tag_get_group_tag(tag_index) != 'bitm') + return FALSE; + group = bitmap_group_get(tag_index); + if (!cache_file_tag_cache_contains(group, sizeof(*group)) || group->bitmaps.count != 1 || + !cache_file_tag_cache_contains(group->bitmaps.address, sizeof(struct bitmap_data))) + return FALSE; + bitmap = group->bitmaps.address; + if (bitmap->width != 32 || bitmap->height != 32 || bitmap->depth != 32 || + bitmap->type != 1 || bitmap->mipmap_count != 5 || (bitmap->format != 3 && bitmap->format != 11)) + return FALSE; + /* Compression, palettes and linear addressing would interpret the + stored bytes differently. Only the inspected volume layouts qualify. */ + if ((bitmap->flags & 0x1E) != 0 && (bitmap->flags & 0x1E) != 8) + return FALSE; + /* Full mip chain, excluding hardware padding. The cache rounds Xbox + reads up to a sector; the allocation includes that tail. */ + size = bitmap->format == 3 ? 74898 : 149796; + if (bitmap->pixels_size < size || bitmap->pixels_offset < 0) + return FALSE; + pixels = malloc((size + 4095) & ~4095); + if (!pixels) + return FALSE; + memset(pixels, 0, (size + 4095) & ~4095); + cache_file_read(tag_index, bitmap->pixels_offset, size, pixels, &complete, TRUE); + while (!complete) + SwitchToThread(); + hash = shield_look_hash(UINT32_C(2166136261), pixels, size); + free(pixels); + /* Xbox A8Y8, CE ARGB, and the same CE pixels packed by MCC's existing + bitmap adapter. No foreign resource path or adapter is used here. */ + return complete == TRUE && (bitmap->format == 3 ? + (bitmap->flags & 8) && hash == UINT32_C(0xF2F70788) : + (bitmap->flags & 8) ? hash == UINT32_C(0x18AC1E94) : hash == UINT32_C(0xE7F72DA4)); +} + +/* Resolve the exact CMT noise through this map's existing resource loader. +A custom modifier may reference different pixels; never use those for ENHANCED. */ +static long shield_look_noise(void) +{ + struct tag_iterator iterator; + long index; + + if (!shield_look_noise_searched) + { + shield_look_noise_searched = TRUE; + tag_iterator_new(&iterator, 'bitm'); + while ((index = tag_iterator_next(&iterator)) != NONE) + { + if (shield_look_stock_noise(index)) + { + shield_look_noise_index = index; + break; + } + } + } + return shield_look_noise_index; +} + +static void shield_look_profile(struct shield_look_plasma *plasma, boolean arms) +{ + /* CMT Snow Grove's body tag 1935 and hands tag 2163. These are shader + parameters, not extracted textures, geometry or executable code. */ + plasma->intensity_source = 2; + plasma->intensity_exponent = 1.f; + plasma->offset_source = 3; + plasma->offset_amount = arms ? 0.009f : 0.035f; + plasma->offset_exponent = 2.f; + plasma->perpendicular_alpha = plasma->parallel_alpha = 1.f; + plasma->perpendicular_color.red = 0.909804f; + plasma->perpendicular_color.green = 0.772549f; + plasma->perpendicular_color.blue = 0.f; + plasma->parallel_color.red = 0.937255f; + plasma->parallel_color.green = 0.694118f; + plasma->parallel_color.blue = 0.0627451f; + plasma->color_source = 0; + plasma->primary_period = 2.1f; + plasma->primary_direction.i = 2.f; + plasma->primary_direction.j = 0.f; + plasma->primary_direction.k = -0.5f; + plasma->primary_scale = arms ? 45.f : 18.f; + plasma->secondary_period = 3.2f; + plasma->secondary_direction.i = 0.f; + plasma->secondary_direction.j = 2.f; + plasma->secondary_direction.k = 0.5f; + plasma->secondary_scale = arms ? 62.f : 14.f; +} + +/* Stock Xbox cyborg shield surface, inspected in Beaver Creek. Both presets +use the same verified noise volume. The separate layer envelope is shared. */ +static void shield_look_classic_profile(struct shield_look_plasma *plasma) +{ + plasma->perpendicular_color.red = 1.f; + plasma->perpendicular_color.green = 0.545098f; + plasma->perpendicular_color.blue = 0.243137f; + plasma->parallel_color.red = 0.0666667f; + plasma->parallel_color.green = 0.0666667f; + plasma->parallel_color.blue = 1.f; + plasma->primary_period = 2.2f; + plasma->primary_direction.k = -0.3f; + plasma->primary_scale = 10.f; + plasma->secondary_period = 3.f; + plasma->secondary_scale = 6.f; +} + +static struct shield_look_entry *shield_look_for_unit(long object_index, long hands_index) +{ + struct object_datum *object; + struct object_definition *definition; + struct shield_look_plasma const *plasma; + struct shader const *shader; + short intensity_source; + struct shield_look_entry *entry; + short index; + long shader_index; + long noise_index; + boolean sprinkles; + boolean honeycomb; + + if (!shield_look_enabled()) + return NULL; + sprinkles = !strcmp(config_string("display.shield_look"), "classic_with_sprinkles") || + !strcmp(config_string("display.shield_look"), "classic_honeycomb2"); + honeycomb = !strcmp(config_string("display.shield_look"), "classic_honeycomb2"); + object = object_try_and_get(object_index); + if (!shield_look_player(object)) + return NULL; + for (index = 0; index < shield_look_count; index++) + { + entry = &shield_looks[index]; + if (entry->definition_index == object->definition_index && entry->hands_index == hands_index && + entry->sprinkles == sprinkles && entry->honeycomb == honeycomb) + return entry->eligible ? entry : NULL; + } + /* Refuse overflow rather than recycling memory still used by a draw. */ + if (shield_look_count == SHIELD_LOOK_MAXIMUM) + return NULL; + entry = &shield_looks[shield_look_count++]; + entry->definition_index = object->definition_index; + entry->hands_index = hands_index; + entry->sprinkles = sprinkles; + entry->honeycomb = honeycomb; + definition = object_definition_get(object->definition_index); + if (!cache_file_tag_cache_contains(definition, sizeof(*definition))) + return NULL; + entry->model_index = definition->object.model.index; + shader_index = definition->object.modifier_shader.index; + if (shader_index == NONE || entry->model_index == NONE || hands_index == NONE) + return NULL; + shader = shader_definition_get(shader_index); + if (!cache_file_tag_cache_contains(shader, sizeof(*shader)) || + !shader_type_is_valid_for_modifier(shader->base.type)) + return NULL; + plasma = shader->base.type == 10 ? (struct shield_look_plasma const *)shader : NULL; + if (plasma && !cache_file_tag_cache_contains(plasma, sizeof(*plasma))) + return NULL; + noise_index = shield_look_noise(); + if (noise_index == NONE) + return NULL; + if (plasma) + entry->body = entry->arms = *plasma; + else + { + entry->body.shader = entry->arms.shader = *shader; + entry->body.shader.base.type = entry->arms.shader.base.type = 10; + } + entry->authored_modifier = shader; + intensity_source = plasma ? plasma->intensity_source : 2; + entry->body.primary_map.index = entry->body.secondary_map.index = noise_index; + entry->arms.primary_map.index = entry->arms.secondary_map.index = noise_index; + shield_look_profile(&entry->body, FALSE); + shield_look_profile(&entry->arms, TRUE); + if (sprinkles) + { + shield_look_classic_profile(&entry->body); + shield_look_classic_profile(&entry->arms); + } + /* The map still owns hit timing and the outgoing function channel. + Overshield animation writes that same channel; only appearance changes. */ + entry->body.intensity_source = entry->arms.intensity_source = intensity_source; + /* Use the established Arm Shields stand-off, capped by its existing + distance/FOV calculation. An authored zero-offset shell must not remove it. */ + entry->arms.offset_source = intensity_source; + entry->arms.offset_amount = 0.03f; + entry->arms.offset_exponent = 2.f; + /* A small normal displacement follows the visible hit intensity (B), + not the unused stock C function. At full intensity this is 3.8 cm; + the square root keeps a gentle outer layer while the hit fades. */ + entry->body.offset_source = intensity_source; + entry->body.offset_amount = 0.0125f; + entry->body.offset_exponent = 0.5f; + entry->eligible = TRUE; + return entry; +} + +/* Compare colour data, not tag paths: protected maps can rename tags. */ +static boolean shield_look_color_near(real_rgb_color const *color, real red, real green, real blue) +{ + return color->red > red - 0.00001f && color->red < red + 0.00001f && + color->green > green - 0.00001f && color->green < green + 0.00001f && + color->blue > blue - 0.00001f && color->blue < blue + 0.00001f; +} + +static boolean shield_look_default_colors(struct shield_look_plasma const *p) +{ + if (p->color_source != 0) + return FALSE; + return (shield_look_color_near(&p->perpendicular_color, 1.f, 0.545098f, 0.243137f) && + shield_look_color_near(&p->parallel_color, 0.0666667f, 0.0666667f, 1.f)) || + (shield_look_color_near(&p->perpendicular_color, 0.65098f, 1.f, 1.f) && + shield_look_color_near(&p->parallel_color, 0.627451f, 0.215686f, 1.f)) || + (shield_look_color_near(&p->perpendicular_color, 0.909804f, 0.772549f, 0.f) && + shield_look_color_near(&p->parallel_color, 0.937255f, 0.694118f, 0.0627451f)); +} + +static real shield_look_color_peak(real_rgb_color const *color) +{ + real peak; + /* Reject negative, nonfinite and out-of-range authored RGB values. */ + if (!(color->red >= 0.f && color->red <= 1.f && color->green >= 0.f && + color->green <= 1.f && color->blue >= 0.f && color->blue <= 1.f)) + return 0.f; + peak = color->red > color->green ? color->red : color->green; + return peak > color->blue ? peak : color->blue; +} + +static void shield_look_color_apply(real_rgb_color const *color, real_rgb_color *out) +{ + real brightness = shield_look_color_peak(out); + real peak = shield_look_color_peak(color); + out->red = (color->red / peak) * brightness; + out->green = (color->green / peak) * brightness; + out->blue = (color->blue / peak) * brightness; +} + +/* Draw-local colours preserve per-object channels without mutating cached +profiles or map tags. Only the two RGB constants change; a black authored +endpoint borrows the other hue rather than removing the preset's layer. */ +boolean shield_look_colors(struct shader const *shader, real_rgb_color const *colors, + real_rgb_color *perpendicular, real_rgb_color *parallel) +{ + struct shield_look_plasma const *authored; + struct shield_look_entry const *entry; + real_rgb_color a, b; + real_rgb_color const *tint; + short index; + if (!shield_look_enabled()) + return FALSE; + for (index = 0; index < shield_look_count; index++) + { + entry = &shield_looks[index]; + if (!entry->eligible || (shader != &entry->body.shader && shader != &entry->arms.shader) || + entry->authored_modifier->base.type != 10) + continue; + authored = (struct shield_look_plasma const *)entry->authored_modifier; + if (shield_look_default_colors(authored)) + return FALSE; + a = authored->perpendicular_color; + b = authored->parallel_color; + if (authored->color_source != 0) + { + if (!colors || authored->color_source < 1 || authored->color_source > 4) + return FALSE; + tint = &colors[authored->color_source - 1]; + if (shield_look_color_peak(tint) == 0.f) + return FALSE; + a.red *= tint->red; a.green *= tint->green; a.blue *= tint->blue; + b.red *= tint->red; b.green *= tint->green; b.blue *= tint->blue; + } + if (shield_look_color_peak(&a) == 0.f) + a = b; + if (shield_look_color_peak(&b) == 0.f) + b = a; + if (shield_look_color_peak(&a) == 0.f) + return FALSE; + shield_look_color_apply(&a, perpendicular); + shield_look_color_apply(&b, parallel); + return TRUE; + } + return FALSE; +} + +/* Identity comes from the retained draw profile, never a global menu value: +queued draws may outlive a setting change. */ +real shield_look_honeycomb_scale(struct shader const *shader) +{ + short index; + for (index = 0; index < shield_look_count; index++) + { + struct shield_look_entry const *entry = &shield_looks[index]; + if (entry->eligible && entry->honeycomb && + (shader == &entry->body.shader || shader == &entry->arms.shader)) + return shader == &entry->arms.shader ? 225.f : 87.5f; + } + return 0.f; +} + +/* Draw-local composition: 0 is disabled, 1 is arms, 2 is the body, 3 follows body plasma. */ +short shield_look_honeycomb_classic_mode(struct shader const *shader) +{ + short index; + for (index = 0; index < shield_look_count; index++) + { + struct shield_look_entry const *entry = &shield_looks[index]; + if (entry->eligible && entry->honeycomb && entry->sprinkles && + (shader == &entry->body.shader || shader == &entry->arms.shader)) + return shader == &entry->arms.shader ? 1 : 3; + } + return 0; +} + +void shield_look_reset(void) +{ + shield_recharge_reset(); + memset(shield_looks, 0, sizeof(shield_looks)); + shield_look_count = 0; + shield_look_noise_searched = FALSE; + shield_look_noise_index = NONE; +} + +struct shader *shield_look_body(long object_index, struct shader *original) +{ + struct game_globals *globals; + struct game_globals_first_person_interface *first_person; + struct shield_look_entry *entry; + + if (!shield_look_enabled()) + return original; + globals = scenario_get_game_globals(); + if (!cache_file_tag_cache_contains(globals, sizeof(*globals)) || globals->first_person_interface.count != 1 || + !cache_file_tag_cache_contains(globals->first_person_interface.address, sizeof(*first_person))) + return original; + first_person = TAG_BLOCK_GET_ELEMENT(&globals->first_person_interface, 0, struct game_globals_first_person_interface); + entry = shield_look_for_unit(object_index, first_person->hands.index); + return entry ? &entry->body.shader : original; +} + +boolean shield_look_arms(short local_player_index, long unit_index, long hands_model_index, + struct render_model_effect *effect) +{ + struct shield_look_entry *entry; + + /* The caller first applies Arm Shields. OFF leaves no pass to restyle; + ON retains its values pointer, including its offset cap and overshield. + Register the model even when OFF so authored hand shells are suppressed. */ + if (local_player_index < 0 || local_player_index >= MAXIMUM_LOCAL_PLAYERS) + return FALSE; + entry = shield_look_for_unit(unit_index, hands_model_index); + if (!entry || !effect->modifier_shader) + return FALSE; + effect->modifier_shader = &entry->arms.shader; + return TRUE; +} + +/* A map can duplicate its body/arm geometry for a plasma shell. When the +selected modifier already supplies that layer, omit the authored plasma +part before submitting either the base material or another modifier copy. +Other transparent materials (visors, lamps and decals) are not shields. */ +boolean shield_look_skip_shell(long object_index, struct model const *model, struct shader const *surface, + boolean first_person) +{ + struct object_datum *object; + short index; + + if (!surface || !model || !shield_look_enabled()) + return FALSE; + /* The engine identifies a first-person hands draw by its weapon. Keep + that identity intact and resolve its owning unit only for this gate. */ + object = object_try_and_get(object_index); + if (first_person && object && object->object.type == _object_type_weapon) + object = object_try_and_get(object->object.parent_object_index); + if (!shield_look_player(object)) + return FALSE; + for (index = 0; index < shield_look_count; index++) + { + if (shield_looks[index].eligible && + (surface->base.type == 10 || + (surface->base.type > 4 && surface == shield_looks[index].authored_modifier)) && + (model == model_definition_get(shield_looks[index].model_index) || + model == model_definition_get(shield_looks[index].hands_index))) + return TRUE; + } + return FALSE; +} + +#include "shield_arcs.inl" + +#include "shield_recharge.inl" diff --git a/port/linux/game/shield_look.h b/port/linux/game/shield_look.h new file mode 100644 index 0000000000..82d0af956d --- /dev/null +++ b/port/linux/game/shield_look.h @@ -0,0 +1,29 @@ +/* SHIELD LOOK: optional player-only profiles; DEFAULT preserves map-authored shields. */ +#ifndef SHIELD_LOOK_H +#define SHIELD_LOOK_H + +struct shader; +struct model; +struct render_model_effect; +union real_rgb_color; +struct real_matrix4x3; + +boolean shield_look_colors(struct shader const *shader, union real_rgb_color const *colors, + union real_rgb_color *perpendicular, union real_rgb_color *parallel); +void shield_arcs_unload(void); +void shield_arcs_draw(long object_index, long model_index, struct real_matrix4x3 const *nodes, + struct render_model_effect const *effect, boolean arms); +void shield_recharge_reset(void); +void shield_recharge_prepare(long object_index, struct render_model_effect const *effect, boolean arms); +boolean shield_recharge_visible(struct shader const *shader, real const *values); +void shield_recharge_draw(struct shader const *shader, real const *values, real *intensity, real *offset); +real shield_look_honeycomb_scale(struct shader const *shader); +short shield_look_honeycomb_classic_mode(struct shader const *shader); +void shield_look_reset(void); +boolean shield_look_skip_shell(long object_index, struct model const *model, struct shader const *surface, + boolean first_person); +struct shader *shield_look_body(long object_index, struct shader *original); +boolean shield_look_arms(short local_player_index, long unit_index, long hands_model_index, + struct render_model_effect *effect); + +#endif diff --git a/port/linux/game/shield_recharge.inl b/port/linux/game/shield_recharge.inl new file mode 100644 index 0000000000..fcca23593c --- /dev/null +++ b/port/linux/game/shield_recharge.inl @@ -0,0 +1,181 @@ +/* SHIELD_RECHARGE.INL: a draw-only envelope on the approved ENHANCED profile. */ +#include "rasterizer/rasterizer.h" +#include "viewmodel_shield.h" + +unsigned long config_changes(void); +int config_boolean(char const *name); + +enum { SHIELD_RECHARGE_MAXIMUM = 128 }; +struct shield_recharge +{ + boolean used, charging; + boolean classic_surface[2]; + long object_index; + real seen, retreat, progress, fade; + struct shader const *shaders[2]; + real const *values[2]; +}; +static struct shield_recharge shield_recharges[SHIELD_RECHARGE_MAXIMUM]; +static unsigned long shield_recharge_changes; + +void shield_recharge_reset(void) +{ + memset(shield_recharges, 0, sizeof(shield_recharges)); + shield_recharge_changes = config_changes(); +} + +static real shield_recharge_ease(real value) +{ + value = PIN(value, 0.f, 1.f); + return value * value * (3.f - 2.f * value); +} + +/* The charging flag distinguishes regeneration from a shield held below full. +Stun/depletion and overcharge always win, even if a charging flag is stale. */ +static boolean shield_recharge_allowed(struct object_datum const *object) +{ + return shield_look_player(object) && + !TEST_FLAG(object->object.damage_flags, _object_dead_bit) && + !TEST_FLAG(object->object.damage_flags, _object_shield_depleted_bit) && + !TEST_FLAG(object->object.damage_flags, _object_shield_over_charging_bit) && + object->object.shield_stun_ticks == 0 && + object->object.shield_vitality > 0.f && object->object.shield_vitality <= 1.f; +} + +static void shield_recharge_update(struct shield_recharge *state, + struct object_datum const *object, real now) +{ + real shield = object->object.shield_vitality; + if (!shield_recharge_allowed(object)) + { + state->used = FALSE; + return; + } + if (shield < 1.f && TEST_FLAG(object->object.damage_flags, _object_shield_charging_bit)) + { + state->charging = TRUE; + state->progress = shield_recharge_ease(shield); + state->fade = shield_recharge_ease(shield / 0.06f); + } + else if (shield >= 1.f && (state->charging || state->fade > 0.f)) + { + if (state->charging) + { + state->retreat = now; + state->charging = FALSE; + } + state->progress = 1.f; + state->fade = 1.f - shield_recharge_ease((now - state->retreat) / 0.5f); + if (state->fade <= 0.f) + state->used = FALSE; + } + else + state->used = FALSE; + state->seen = now; +} + +/* Register existing values pointers, preserving Arm Shields and Overshield +ownership. Transparent packets outlive this call, so no stack copies are used. */ +void shield_recharge_prepare(long object_index, struct render_model_effect const *effect, boolean arms) +{ + struct object_datum *object; + struct shield_recharge *state = NULL, *available = NULL; + real now = global_frame_parameters.game_time_sec; + short i, side = arms ? 1 : 0; + boolean owned = FALSE, classic_surface = FALSE; + if (shield_recharge_changes != config_changes()) + shield_recharge_reset(); + if (!shield_look_enabled() || !effect || !effect->modifier_animation.values || + (arms && !config_boolean("display.viewmodel_shield"))) + return; + for (i = 0; i < shield_look_count; i++) + if (effect->modifier_shader == (arms ? &shield_looks[i].arms.shader : &shield_looks[i].body.shader)) + { + owned = TRUE; + classic_surface = shield_looks[i].sprinkles; + } + if (!owned || !(now >= 0.f && now < 10000000.f)) + return; + object = object_try_and_get(object_index); + for (i = 0; i < SHIELD_RECHARGE_MAXIMUM; i++) + { + struct shield_recharge *each = &shield_recharges[i]; + if (each->used && (now < each->seen || now - each->seen > 1.f)) + each->used = FALSE; + if (each->used && each->object_index == object_index) + state = each; + else if (each->used && each->values[side] == effect->modifier_animation.values) + each->values[side] = NULL; /* respawn or reassigned split-screen arms */ + if (!each->used && !available) + available = each; + } + if (!shield_recharge_allowed(object)) + { + if (state) state->used = FALSE; + return; + } + if (!state) + { + if (!available || object->object.shield_vitality >= 1.f || + !TEST_FLAG(object->object.damage_flags, _object_shield_charging_bit)) + return; + state = available; + memset(state, 0, sizeof(*state)); + state->used = TRUE; + state->object_index = object_index; + } + shield_recharge_update(state, object, now); + state->classic_surface[side] = classic_surface; + state->shaders[side] = effect->modifier_shader; + state->values[side] = effect->modifier_animation.values; +} + +static struct shield_recharge const *shield_recharge_find(struct shader const *shader, + real const *values, short *side) +{ + short i, j; + if (!shader || !values || !shield_look_enabled() || shield_recharge_changes != config_changes()) + return NULL; + for (i = 0; i < SHIELD_RECHARGE_MAXIMUM; i++) + { + struct shield_recharge const *state = &shield_recharges[i]; + if (!state->used || state->fade <= 0.f || + state->seen != global_frame_parameters.game_time_sec) + continue; + for (j = 0; j < 2; j++) + if (state->shaders[j] == shader && state->values[j] == values && + (!j || config_boolean("display.viewmodel_shield"))) + { + *side = j; + return state; + } + } + return NULL; +} + +boolean shield_recharge_visible(struct shader const *shader, real const *values) +{ + short side; + return shield_recharge_find(shader, values, &side) != NULL; +} + +void shield_recharge_draw(struct shader const *shader, real const *values, real *intensity, real *offset) +{ + short side; + struct shield_recharge const *state = shield_recharge_find(shader, values, &side); + struct shield_look_plasma const *profile = (struct shield_look_plasma const *)shader; + real maximum, visibility; + if (!state) + return; + /* Arms grow within their existing cap. Body peak is only 15% above the + approved offset; no profile, colour, texture or animation speed changes. */ + maximum = viewmodel_shield_offset_amount(values, profile->offset_amount * (side ? 1.f : 1.15f)); + *offset = maximum * (0.3f + 0.7f * state->progress) * state->fade; + visibility = state->fade; + /* The classic surface loses broad bands sooner as intensity falls. + Keep them readable through the shared retreat without changing its + duration, displacement, shader profile or the approved ENHANCED curve. */ + if (state->classic_surface[side]) + visibility *= 1.f + 0.75f * (1.f - visibility); + *intensity = MAX(*intensity, (0.22f + 0.25f * state->progress) * visibility); +} diff --git a/port/linux/game/tag_schema.h b/port/linux/game/tag_schema.h index aaae65240b..c4ec9b345f 100644 --- a/port/linux/game/tag_schema.h +++ b/port/linux/game/tag_schema.h @@ -312,7 +312,7 @@ boolean tag_validate_custom_edition_tags( struct tag_validate_file_range const *file_ranges, short file_range_count, char const *map_name); - + /* A protected map's tags have their groups scrambled in the tag table (extractors show them as INVALID), while the references to them keep the real ones, which is all Halo PC read. Gives each tag of no known group the diff --git a/port/linux/game/tag_validate.c b/port/linux/game/tag_validate.c index b79e902ac6..1a82d97034 100644 --- a/port/linux/game/tag_validate.c +++ b/port/linux/game/tag_validate.c @@ -1854,6 +1854,8 @@ boolean tag_validate_file_contains( long offset, long size) { + if (mcc_validation_callbacks && mcc_validation_callbacks->owns(validation)) + return mcc_validation_callbacks->file_contains(validation, offset, size); short range_index; if (mcc_validation_callbacks && mcc_validation_callbacks->owns(validation)) diff --git a/port/linux/game/texture_prepare.c b/port/linux/game/texture_prepare.c new file mode 100644 index 0000000000..37beb91e3c --- /dev/null +++ b/port/linux/game/texture_prepare.c @@ -0,0 +1,89 @@ +/* Optional Xbox/CE preparation through the existing validated texture cache. + * MCC has its own allocation enumeration, budget and ownership. */ +#include "cseries.h" +#include "cseries/errors.h" +#include "bitmaps/bitmap_group.h" +#include "cache/cache_files.h" +#include "cache/texture_cache.h" +#include "mcc_cache.h" +#include "../src/port_config.h" +#include + +#ifndef HALO_GLES +#define TEXTURE_PREPARE_LIMIT 8192 +struct texture_candidate { + struct bitmap_data *bitmap; + unsigned long charge; +}; + +/* Bound both guest cache residency and worst-case RGBA GPU storage, including + * mip levels and cube faces. The native loader still validates the resource. */ +static unsigned long texture_prepare_charge(struct bitmap_data const *bitmap) +{ + unsigned long long bytes=0; + unsigned long width,height,depth,level; + if (!(bitmap->flags&(1U<<7)) || bitmap->type<0 || bitmap->type>2 || + bitmap->format<0 || bitmap->format>=17 || bitmap->pixels_size<=0 || + bitmap->width<=0 || bitmap->width>4096 || bitmap->height<=0 || bitmap->height>4096 || + bitmap->depth<=0 || bitmap->depth>512 || bitmap->mipmap_count<0 || bitmap->mipmap_count>12) return 0; + width=bitmap->width;height=bitmap->height;depth=bitmap->depth; + for (level=0;level<=(unsigned)bitmap->mipmap_count;level++) { + /* Native linear rows are rounded to the Xbox 64-byte pitch. */ + bytes+=(unsigned long long)((width*4+63)&~63UL)*height*depth; + if (width>1) width>>=1; + if (height>1) height>>=1; + if (depth>1) depth>>=1; + } + if (bitmap->type==2) bytes*=6; + if (bytes<(unsigned long)bitmap->pixels_size) bytes=bitmap->pixels_size; + /* A cache allocation is page-rounded even for tiny textures. */ + bytes=(bytes+16383)&~16383ULL; + return bytes>128ULL*1024*1024 ? 0 : (unsigned long)bytes; +} + +static int texture_prepare_order(void const *left,void const *right) +{ + struct texture_candidate const *a=left,*b=right; + return a->charge>b->charge ? -1 : a->chargecharge ? 1 : 0; +} +#endif + +void texture_prepare_map(void) +{ +#ifndef HALO_GLES + struct texture_candidate *candidates; + struct tag_iterator iterator; + long index,megabytes=config_integer("display.texture_prepare_mb"); + unsigned count=0,item,prepared=0; + unsigned long budget,spent=0; + if (megabytes<=0 || mcc_cache_tags_loaded() || config_server_mode_enabled() || + config_boolean("debug.null_renderer")) return; + /* At most half the established 256 MiB guest texture cache. */ + if (megabytes>128) megabytes=128; + budget=(unsigned long)megabytes*1024*1024; + candidates=malloc(TEXTURE_PREPARE_LIMIT*sizeof(*candidates)); + if (!candidates) return; + tag_iterator_new(&iterator,BITMAP_GROUP_TAG); + while ((index=tag_iterator_next(&iterator))!=NONE && countbitmaps.count && countbitmaps.address+bitmap_index; + unsigned long charge=texture_prepare_charge(bitmap); + if (charge && charge<=budget) { + candidates[count].bitmap=bitmap;candidates[count++].charge=charge; + } + } + } + qsort(candidates,count,sizeof(*candidates),texture_prepare_order); + for (item=0;itembudget-spent) continue; + spent+=candidates[item].charge; + header=_texture_cache_bitmap_get_hardware_format(candidates[item].bitmap,TRUE,TRUE); + if (header && render_prepare_texture(header)) prepared++; + } + free(candidates); + error(_error_silent,"texture preparation: uploaded %u textures (%lu KiB bounded storage)",prepared,spent/1024); +#endif +} diff --git a/port/linux/game/third_person.c b/port/linux/game/third_person.c new file mode 100644 index 0000000000..6100ab355e --- /dev/null +++ b/port/linux/game/third_person.c @@ -0,0 +1,356 @@ +/* Optional shoulder view, applied to the director's eye after interpolation. + The simulation's aim stays fixed; shoulder shots use world muzzles. */ +#include "cseries.h" +#include "third_person.h" +#include "camera/director.h" +#include "cutscene/cinematics.h" +#include "game/players.h" +#include "units/units.h" +#include "physics/collisions.h" +#include "render/render.h" +#include "render/render_cameras_internal.h" +#include "main/main.h" +#include "camera/observer.h" +#include "halo_keyboard.h" +#include + +int config_boolean(char const *name); +unsigned long config_changes(void); +double config_real(char const *name); + +struct shoulder_camera_state +{ + boolean initialized; + long unit_index; + real distance, height, side, boom; + real_point3d eye; + boolean looking; + real look_yaw, look_pitch; + boolean look_requires_release, collision_blocked; + real clear_time, recovery_delay, vertical_lag; + real return_time, return_yaw, return_pitch; +}; +static struct shoulder_camera_state cameras[MAXIMUM_LOCAL_PLAYERS]; +static boolean active[MAXIMUM_LOCAL_PLAYERS]; +static boolean smooth_camera = TRUE; +static real requested_distance = 0.85f, requested_height = 0.12f, requested_side = 0.24f; + +/* Exponential response gives the same settling time at different frame rates. */ +static real camera_blend(real dt, real seconds) +{ + return smooth_camera ? (real)(1.0 - exp(-dt / seconds)) : 1.0f; +} + +static void release_look(struct shoulder_camera_state *state) +{ + if (state->looking) + { + state->return_time = 0.25f; + state->return_yaw = state->look_yaw; + state->return_pitch = state->look_pitch; + state->looking = FALSE; + } +} + +/* Reject non-finite values as well as out-of-range settings. */ +static real camera_setting(char const *name, double low, double high, real fallback) +{ + double value = config_real(name); + return value >= low && value <= high ? (real)value : fallback; +} + +void third_person_reset(void) +{ + short index; + for (index = 0; index < MAXIMUM_LOCAL_PLAYERS; index++) + { + cameras[index].initialized = FALSE; + cameras[index].looking = FALSE; + cameras[index].look_requires_release = (halo_keyboard_actions(index) & (1UL << HALO_KEYBOARD_FREE_LOOK)) != 0; + cameras[index].return_time = 0.0f; + cameras[index].look_yaw = cameras[index].look_pitch = 0.0f; + active[index] = FALSE; + } +} + +static real_point3d targets[MAXIMUM_LOCAL_PLAYERS]; + +boolean third_person_active(short local_player_index) +{ + return local_player_index >= 0 && local_player_index < MAXIMUM_LOCAL_PLAYERS && + active[local_player_index]; +} + +boolean third_person_available(short local_player_index) +{ + static unsigned long read_at = (unsigned long)-1; + long unit_index; + struct unit_datum *unit; + + if (read_at != config_changes()) + { + read_at = config_changes(); + smooth_camera = config_boolean("display.third_person_smooth") != 0; + requested_distance = camera_setting("display.third_person_distance", 0.3, 2.0, 0.85f); + requested_height = camera_setting("display.third_person_height", -0.2, 0.6, 0.12f); + requested_side = camera_setting("display.third_person_offset", 0.0, 0.6, 0.24f); + if (config_boolean("display.third_person_left_shoulder")) + requested_side = -requested_side; + } + if (local_player_index < 0 || local_player_index >= MAXIMUM_LOCAL_PLAYERS || + !third_person_enabled() || cinematic_in_progress() || *director_camera_scripted || + director_inhibited_facing(local_player_index)) + return FALSE; + unit_index = player_control_get_unit_index(local_player_index); + unit = unit_index != NONE ? unit_try_and_get(unit_index) : NULL; + if (player_control_get_zoom_level(local_player_index) != NONE || + (unit && (unit->unit.current_zoom_level != NONE || unit->unit.desired_zoom_level != NONE))) + { + return FALSE; + } + return unit && unit->object.parent_object_index == NONE && + !TEST_FLAG(unit->object.damage_flags, _object_dead_bit); +} + +static boolean third_person_wanted(short local_player_index) +{ + return third_person_available(local_player_index) && + third_person_director_active(local_player_index); +} + +boolean third_person_free_look_input(short local_player_index, real yaw, real pitch) +{ + struct shoulder_camera_state *state; + boolean held; + if (local_player_index < 0 || local_player_index >= MAXIMUM_LOCAL_PLAYERS) + return FALSE; + state = &cameras[local_player_index]; + held = (halo_keyboard_actions(local_player_index) & (1UL << HALO_KEYBOARD_FREE_LOOK)) != 0; + if (!held) + state->look_requires_release = FALSE; + if (!third_person_wanted(local_player_index) || !state->initialized || + state->unit_index != player_control_get_unit_index(local_player_index)) + { + state->looking = FALSE; + state->look_requires_release = held; + state->return_time = 0.0f; + state->look_yaw = state->look_pitch = 0.0f; + return FALSE; + } + if (!held) + release_look(state); + else if (!state->look_requires_release && third_person_active(local_player_index)) + state->looking = TRUE; + if (!state->looking) + return FALSE; + state->return_time = 0.0f; + state->look_yaw += yaw; + while (state->look_yaw > _pi) state->look_yaw -= 2.0f * _pi; + while (state->look_yaw < -_pi) state->look_yaw += 2.0f * _pi; + state->look_pitch = PIN(state->look_pitch + pitch, -_pi, _pi); + return TRUE; +} + +void third_person_camera(short local_player_index, struct render_camera *camera) +{ + long unit_index; + struct unit_datum *unit; + real_vector3d right, offset, ray, saved_forward, saved_up; + real_euler_angles2d look_angles; + real_point3d origin; + struct collision_result collision; + real fraction, length; + real hard_fraction, blend, dt, wanted_boom, vertical_step, remaining; + boolean was_active; + struct shoulder_camera_state *state; + unsigned long flags; + + if (local_player_index < 0 || local_player_index >= MAXIMUM_LOCAL_PLAYERS) + return; + was_active = active[local_player_index]; + active[local_player_index] = FALSE; + state = &cameras[local_player_index]; + if (!camera || !third_person_wanted(local_player_index)) + { + state->initialized = FALSE; + state->look_requires_release = (halo_keyboard_actions(local_player_index) & (1UL << HALO_KEYBOARD_FREE_LOOK)) != 0; + state->return_time = 0.0f; + state->looking = FALSE; + state->look_yaw = state->look_pitch = 0.0f; + return; + } + unit_index = player_control_get_unit_index(local_player_index); + unit = unit_get(unit_index); + dt = PIN(main_get_seconds_elapsed(), 0.0f, 0.1f); + + vector_from_points3d(&state->eye, &camera->position, &offset); + if (!state->initialized || state->unit_index != unit_index || magnitude3d(&offset) > 2.0f) + { + state->looking = FALSE; + /* A respawn or teleport must not restart a held orbit key. */ + state->look_requires_release = (halo_keyboard_actions(local_player_index) & (1UL << HALO_KEYBOARD_FREE_LOOK)) != 0; + state->look_yaw = state->look_pitch = 0.0f; + state->distance = requested_distance; + state->height = requested_height; + state->side = requested_side; + state->boom = 0.0f; + state->vertical_lag = 0.0f; + state->eye = camera->position; + state->collision_blocked = FALSE; + state->clear_time = state->recovery_delay = state->return_time = 0.0f; + state->unit_index = unit_index; + state->initialized = TRUE; + was_active = FALSE; + } + vertical_step = camera->position.z - state->eye.z; + /* Dampen small stair/slope changes only. Keep the real eye as the + collision pivot; the bounded lag is part of the swept camera offset. */ + if (smooth_camera && vertical_step > -0.2f && vertical_step < 0.2f) + state->vertical_lag = PIN((state->vertical_lag - vertical_step) * + (1.0f - camera_blend(dt, 0.08f)), -0.06f, 0.06f); + else + state->vertical_lag = 0.0f; + state->eye = camera->position; + /* Input releases immediately even if gameplay is paused by a menu. */ + if (!(halo_keyboard_actions(local_player_index) & (1UL << HALO_KEYBOARD_FREE_LOOK))) + { + state->look_requires_release = FALSE; + release_look(state); + } + if (!state->looking) + { + state->return_time = smooth_camera ? MAX(0.0f, state->return_time - dt) : 0.0f; + if (state->return_time < 0.000001f) + state->return_time = 0.0f; + remaining = state->return_time / 0.25f; + blend = remaining * remaining * (3.0f - 2.0f * remaining); + state->look_yaw = state->return_yaw * blend; + state->look_pitch = state->return_pitch * blend; + } + + saved_forward = camera->forward; + saved_up = camera->up; + if (state->looking || state->look_yaw != 0.0f || state->look_pitch != 0.0f) + { + euler_angles2d_from_vector3d(&look_angles, &camera->forward); + /* Retain steep gameplay aim on release; an 80-degree orbit limit + must not leave a permanent pitch offset when aiming higher. */ + if (state->looking) + state->look_pitch = PIN(state->look_pitch, + MIN(-DEGREES_TO_RADIANS(80.0f), look_angles.pitch) - look_angles.pitch, + MAX(DEGREES_TO_RADIANS(80.0f), look_angles.pitch) - look_angles.pitch); + look_angles.yaw += state->look_yaw; + look_angles.pitch = PIN(look_angles.pitch + state->look_pitch, + MIN(-DEGREES_TO_RADIANS(80.0f), look_angles.pitch), + MAX(DEGREES_TO_RADIANS(80.0f), look_angles.pitch)); + vector3d_from_euler_angles2d(&camera->forward, &look_angles); + observer_up_from_forward(&camera->forward, &camera->up); + } + blend = camera_blend(dt, 0.12f); + state->distance += (requested_distance - state->distance) * blend; + state->height += (requested_height - state->height) * blend; + state->side += (requested_side - state->side) * blend; + /* Halo world units are about three metres. Sweep the whole diagonal + from the eye so the shoulder cannot pass through a corner. */ + cross_product3d(&camera->forward, &camera->up, &right); + normalize3d(&right); + offset.i = -state->distance * camera->forward.i + state->side * right.i + state->height * camera->up.i; + offset.j = -state->distance * camera->forward.j + state->side * right.j + state->height * camera->up.j; + offset.k = -state->distance * camera->forward.k + state->side * right.k + state->height * camera->up.k + state->vertical_lag; + length = magnitude3d(&offset); + fraction = 1.0f; + flags = FLAG(_collision_test_front_facing_surfaces_bit) | + FLAG(_collision_test_back_facing_surfaces_bit) | + FLAG(_collision_test_structure_bit) | FLAG(_collision_test_objects_bit) | + _collision_test_objects_sight_blocking_flags; + /* The sphere sweep covers the BSP; the ray also tests scenery, + doors and vehicles, which the engine's pill test does not visit. */ + if (collision_test_pill_new(flags, &camera->position, &offset, 0.06f, unit_index, &collision)) + fraction = PIN(collision.t - 0.02f / length, 0.0f, 1.0f); + if (collision_test_vector(flags, &camera->position, &offset, unit_index, &collision)) + fraction = MIN(fraction, MAX(0.0f, collision.t - 0.06f / length)); + hard_fraction = fraction; + /* Start drawing inward before the hard collision limit. Safety always + wins over smoothing; recovery is slower than pull-in. */ + if (collision_test_pill_new(flags, &camera->position, &offset, 0.10f, unit_index, &collision)) + fraction = MIN(fraction, MAX(0.0f, collision.t - 0.02f / length)); + /* A soft sweep can start inside a narrow doorway even when the hard + sweep fits. It must not itself force a change to first person. */ + if (hard_fraction * length >= 0.16f) + fraction = MAX(fraction, 0.16f / length); + wanted_boom = fraction * length; + /* Briefly hold after an inward correction so door edges and steps + cannot pump the camera outward on every other frame. */ + if (wanted_boom < state->boom - 0.01f) + state->recovery_delay = 0.08f; + else + state->recovery_delay = MAX(0.0f, state->recovery_delay - dt); + blend = camera_blend(dt, wanted_boom < state->boom ? 0.06f : 0.25f); + if (smooth_camera && wanted_boom > state->boom && state->recovery_delay > 0.0f) + blend = 0.0f; + state->boom += (wanted_boom - state->boom) * blend; + state->boom = MIN(state->boom, hard_fraction * length); + /* Separate entry and exit thresholds prevent rapid perspective changes + when a wall leaves just enough room for the player's body. */ + if (hard_fraction * length < (was_active ? 0.10f : 0.14f)) + { + state->collision_blocked = TRUE; + state->clear_time = 0.0f; + } + if (state->collision_blocked) + { + if (hard_fraction * length >= 0.14f) + state->clear_time += dt; + if (state->clear_time >= 0.10f) + state->collision_blocked = FALSE; + } + if (state->collision_blocked) + { + state->boom = 0.0f; + /* Collision fallback must retain the player's first-person aim. */ + camera->forward = saved_forward; + camera->up = saved_up; + return; + } + state->boom = MAX(state->boom, MIN(0.14f, hard_fraction * length)); + point_from_line3d(&camera->position, &offset, state->boom / length, &camera->position); + active[local_player_index] = TRUE; + /* Use the current unscoped target FOV, not the observer's remaining + zoom interpolation. Collision fallback retains the stock camera. */ + camera->vertical_field_of_view = 2.0f * arctangent( + 0.75f * render_camera_get_adjusted_field_of_view_tangent( + player_control_get_field_of_view(local_player_index)), 1.0f); + + /* Project the stock firing line, not a ray from the displaced camera. + This indicates the nominal aim point; spread and projectile gravity + remain the weapon's own, just as in first person. */ + unit_get_camera_position(unit_index, &origin); + scale_vector3d(&unit->unit.aiming_vector, 1000.0f, &ray); + point_from_line3d(&origin, &ray, 1.0f, &targets[local_player_index]); + if (collision_test_vector(_collision_test_for_projectiles_flags, &origin, &ray, + unit_index, &collision)) + targets[local_player_index] = collision.point; + third_person_muzzle_target(local_player_index, &targets[local_player_index]); +} + +boolean third_person_reticle(point2d *point, real reticle_scale) +{ + real_point2d screen; + real center_x, center_y; + + if (!third_person_active(render.local_player_index)) + return TRUE; + if (cameras[render.local_player_index].looking || + cameras[render.local_player_index].look_yaw != 0.0f || + cameras[render.local_player_index].look_pitch != 0.0f) + return FALSE; + if (!render_camera_world_to_screen(&render.camera, &render.frustum, + &targets[render.local_player_index], &screen)) + return FALSE; + center_x = (render.camera.window_bounds.x0 + render.camera.window_bounds.x1) * 0.5f; + center_y = (render.camera.window_bounds.y0 + render.camera.window_bounds.y1) * 0.5f; + /* hud_draw_bitmap_internal scales about the original screen centre. */ + point->x += (short)((screen.x - center_x) / reticle_scale); + point->y += (short)((screen.y - center_y) / reticle_scale); + return TRUE; +} diff --git a/port/linux/game/third_person.h b/port/linux/game/third_person.h new file mode 100644 index 0000000000..a3aa1dffde --- /dev/null +++ b/port/linux/game/third_person.h @@ -0,0 +1,39 @@ +#ifndef THIRD_PERSON_H +#define THIRD_PERSON_H + +enum third_person_match_policy +{ + _third_person_player_choice, + _third_person_forced_on, + _third_person_forced_off +}; +/* Bits in network_game.cooperative_flags, shared by all match types. */ +#define THIRD_PERSON_POLICY_SHIFT 4 +#define THIRD_PERSON_POLICY_MASK 48 +/* Replicated with each input tick, not latched like a button press. */ +#define THIRD_PERSON_INPUT_BIT 16 +short third_person_host_policy(void); +short third_person_policy(void); +boolean third_person_enabled(void); +boolean third_person_match_flags_valid(unsigned long flags); +void third_person_input_update(void); + +struct render_camera; +union point2d; +union real_point3d; +union real_vector3d; +boolean third_person_muzzle_shot(long weapon_index, long unit_index, short trigger_index, + union real_point3d *origin, union real_vector3d *forward); +boolean third_person_muzzle_history(long unit_index, union real_point3d *position); +void third_person_muzzle_target(short local_player_index, union real_point3d *target); +boolean third_person_free_look_input(short local_player_index, real yaw, real pitch); +void third_person_reset(void); +boolean third_person_active(short local_player_index); +boolean third_person_available(short local_player_index); +boolean third_person_director_active(short local_player_index); +void third_person_camera_update(void *camera, void *controls, void *result); +int third_person_camera_scroll(float notches, unsigned long actions); +void third_person_camera(short local_player_index, struct render_camera *camera); +boolean third_person_reticle(union point2d *point, real reticle_scale); + +#endif diff --git a/port/linux/game/third_person_director.c b/port/linux/game/third_person_director.c new file mode 100644 index 0000000000..8a2521e6ba --- /dev/null +++ b/port/linux/game/third_person_director.c @@ -0,0 +1,20 @@ +/* The director owns the camera mode; the shoulder solver still runs after + interpolation and camera effects, keeping its collision and aiming pivot. */ +#include "cseries.h" +#include "third_person.h" +#include "camera/director.h" +#include "camera/first_person_camera.h" + +boolean third_person_director_active(short player) +{ + return director_camera_is(player, third_person_camera_update); +} + +void third_person_camera_update(void *camera, void *controls, void *result) +{ + /* Preserve the stock eye, aim assistance pivot and scope interpolation. + The wrapper has the director's exact callback type on wasm too. */ + first_person_camera_update((struct first_person_camera *)camera, + (struct first_person_camera_action const *)controls, + (struct first_person_camera_result *)result); +} diff --git a/port/linux/game/third_person_input.c b/port/linux/game/third_person_input.c new file mode 100644 index 0000000000..fd8e07fbb2 --- /dev/null +++ b/port/linux/game/third_person_input.c @@ -0,0 +1,78 @@ +/* Live camera adjustments use the same bounded settings as the menu. */ +#include "cseries.h" +#include "third_person.h" +#include "halo_keyboard.h" + +double config_real(char const *name); +int config_boolean(char const *name); +int config_write(char const *name, char const *value); + +int third_person_camera_scroll(float notches, unsigned long actions) +{ + char const *setting; + double position, minimum, maximum, fallback, step; + int lateral = FALSE; + int left = FALSE; + char value[32]; + + /* One axis per scroll; preserve distance when modifiers overlap. */ + if (actions & (1UL << HALO_KEYBOARD_CAMERA_DISTANCE)) + { + setting = "display.third_person_distance"; + minimum = 0.3; + maximum = 2.0; + fallback = 0.85; + step = -0.08; + } + else if (actions & (1UL << HALO_KEYBOARD_CAMERA_HEIGHT)) + { + setting = "display.third_person_height"; + minimum = -0.2; + maximum = 0.6; + fallback = 0.12; + step = 0.04; + } + else if (actions & (1UL << HALO_KEYBOARD_CAMERA_OFFSET)) + { + setting = "display.third_person_offset"; + minimum = 0.0; + maximum = 0.6; + fallback = 0.24; + step = 0.04; + lateral = TRUE; + } + else + return 0; + + if (!third_person_active(0) || !third_person_available(0) || + !(notches >= -100.0f && notches <= 100.0f) || notches == 0.0f) + return 0; + position = config_real(setting); + if (!(position >= minimum && position <= maximum)) + position = fallback; + if (lateral) + { + /* The menu stores magnitude and shoulder separately; scrolling can + cross the centre without changing that contract or the B binding. */ + left = config_boolean("display.third_person_left_shoulder"); + if (left) + position = -position; + minimum = -maximum; + } + position = PIN(position + (double)notches * step, minimum, maximum); + if (lateral) + { + /* Keep the shoulder when the saved four-decimal offset rounds to zero. */ + if (position > -0.00005 && position < 0.00005) + position = 0.0; + if (position < 0.0 && !left) + config_write("display.third_person_left_shoulder", "true"); + else if (position > 0.0 && left) + config_write("display.third_person_left_shoulder", "false"); + if (position < 0.0) + position = -position; + } + snprintf(value, sizeof(value), "%.4f", position); + config_write(setting, value); + return 1; +} diff --git a/port/linux/game/third_person_policy.c b/port/linux/game/third_person_policy.c new file mode 100644 index 0000000000..a205372ca1 --- /dev/null +++ b/port/linux/game/third_person_policy.c @@ -0,0 +1,66 @@ +/* Match camera rules never overwrite a player's saved camera preference. */ +#include "cseries.h" +#include "third_person.h" +#include "third_person_protocol.h" +#include "halo_keyboard.h" +#include "controller_remap.h" +#include "networking/network_game_globals.h" +#include "networking/network_game_manager.h" + +char const *config_string(char const *name); +int config_boolean(char const *name); +int config_write(char const *name, char const *value); + +boolean third_person_match_flags_valid(unsigned long flags) +{ + /* Bits zero through three are upstream co-op and vehicle riding flags; policy value three is reserved. */ + return !(flags & ~(15UL | (third_person_session_active() ? THIRD_PERSON_POLICY_MASK : 0))) && + ((flags & THIRD_PERSON_POLICY_MASK) >> THIRD_PERSON_POLICY_SHIFT) <= _third_person_forced_off; +} + +short third_person_host_policy(void) +{ + char const *setting = config_string("network.camera_policy"); + if (setting && !strcmp(setting, "forced_on")) return _third_person_forced_on; + if (setting && !strcmp(setting, "forced_off")) return _third_person_forced_off; + return _third_person_player_choice; +} + +short third_person_policy(void) +{ + struct network_game const *game = network_game_get_game(); + short policy = game ? (game->cooperative_flags & THIRD_PERSON_POLICY_MASK) >> THIRD_PERSON_POLICY_SHIFT : 0; + /* Local split screen has no remote peers and retains the offline preference. */ + if (network_game_is_splitscreen_local() && !third_person_session_active()) return _third_person_player_choice; + if (network_game_is_active() && !third_person_session_active()) return _third_person_forced_off; + /* The receiver rejects invalid records; fail closed if called earlier. */ + return policy <= _third_person_forced_off ? policy : _third_person_forced_off; +} + +boolean third_person_enabled(void) +{ + short policy = third_person_policy(); + return policy == _third_person_forced_on || + (policy == _third_person_player_choice && config_boolean("display.third_person")); +} + +void third_person_input_update(void) +{ + static unsigned long previous; + unsigned long held = halo_keyboard_actions(0); + unsigned long pressed = held & ~previous; + unsigned int pad_pressed = 0; + short port; + previous = held; + /* The remapper owns controller context, capture and release guards. */ + for (port = 0; port < 4; port++) + pad_pressed |= controller_remap_pressed(port, (1u << PAD_TOGGLE_PERSPECTIVE) | (1u << PAD_SWAP_SHOULDER)); + if (pad_pressed & (1u << PAD_TOGGLE_PERSPECTIVE)) pressed |= 1UL << HALO_KEYBOARD_TOGGLE_PERSPECTIVE; + if (pad_pressed & (1u << PAD_SWAP_SHOULDER)) pressed |= 1UL << HALO_KEYBOARD_SWAP_SHOULDER; + /* Keyboard and controller share one camera preference and host policy. */ + if ((pressed & (1UL << HALO_KEYBOARD_TOGGLE_PERSPECTIVE)) && + third_person_policy() == _third_person_player_choice) + config_write("display.third_person", config_boolean("display.third_person") ? "false" : "true"); + if ((pressed & (1UL << HALO_KEYBOARD_SWAP_SHOULDER)) && third_person_enabled()) + config_write("display.third_person_left_shoulder", config_boolean("display.third_person_left_shoulder") ? "false" : "true"); +} diff --git a/port/linux/game/third_person_protocol.c b/port/linux/game/third_person_protocol.c new file mode 100644 index 0000000000..d95729da3a --- /dev/null +++ b/port/linux/game/third_person_protocol.c @@ -0,0 +1,122 @@ +#include "cseries.h" +#include "third_person_protocol.h" +#include "networking/network_messages.h" +#include "bungie_net/common/message_header.h" +#include "third_person.h" +#include "networking/network_game_globals.h" +#include "networking/network_game_manager.h" + +char const *config_string(char const *name); +int config_write(char const *name, char const *value); +struct network_game *network_game_server_get_game(struct network_game_server *server); +boolean network_game_server_send_game_data_pregame(struct network_game_server *server); + +/* The server owns the mode for its whole lifetime. Client capability belongs + * only to the selected connection; settings and local preferences cannot grant it. */ +static int camera_host, camera_host_enabled, camera_locked, camera_client; + +void third_person_session_host_begin(void) +{ + char const *mode = config_string("network.session_compatibility"); + camera_host = 1; + camera_host_enabled = mode && !strcmp(mode, "gulchce_third_person"); + camera_locked = 0; + camera_client = 0; + third_person_reset(); +} + +void third_person_session_host_end(void) +{ + camera_host = camera_host_enabled = camera_locked = camera_client = 0; + third_person_reset(); +} + +void third_person_session_lock(void) { if (camera_host) camera_locked = 1; } +int third_person_session_locked(void) { return camera_locked; } +int third_person_session_active(void) { return camera_host ? camera_host_enabled : camera_client; } + +int third_person_session_set(int enabled) +{ + struct network_game_server *server = global_network_game_server_get(); + struct network_game *game; + if (!server || !camera_host || camera_locked || (enabled != 0 && enabled != 1)) return 0; + game = network_game_server_get_game(server); + if (!game || game->machine_count > 1) return 0; + camera_host_enabled = enabled; + game->cooperative_flags &= ~THIRD_PERSON_POLICY_MASK; + if (enabled) game->cooperative_flags |= third_person_host_policy() << THIRD_PERSON_POLICY_SHIFT; + config_write("network.session_compatibility", enabled ? "gulchce_third_person" : "opence_crossplay"); + third_person_reset(); + network_game_server_send_game_data_pregame(server); + return 1; +} + +void third_person_session_client_begin(unsigned int version) +{ + camera_client = version == THIRD_PERSON_PROTOCOL_VERSION; + third_person_reset(); +} + +void third_person_session_client_clear(void) +{ + camera_client = 0; + third_person_reset(); +} + +unsigned int third_person_session_version(char const *map) +{ + (void)map; + return third_person_session_active() ? THIRD_PERSON_PROTOCOL_VERSION : HALO_PORT_NETWORK_VERSION; +} + +int third_person_session_compatible(char const *map, unsigned int version, unsigned int flags) +{ + (void)map; + if (!(flags & HALO_PORT_ADVERTISED_DISTRIBUTED_FLAG)) return 0; + return version == HALO_PORT_NETWORK_VERSION || version == THIRD_PERSON_PROTOCOL_VERSION; +} + +/* The camera envelope carries only the ordinary OpenCE join. */ +static int third_person_protocol_inner_valid(byte const *message, unsigned short bytes) +{ + word header; + if (bytes <= sizeof(header) || bytes > THIRD_PERSON_PROTOCOL_JOIN_MAX - 8) return 0; + memcpy(&header, message, sizeof(header)); + if (GET_MESSAGE_FLAGS(header) || GET_MESSAGE_SIZE(header) != bytes) return 0; + if (GET_MESSAGE_TYPE(header) == _message_type_packet) + return message[bytes - 1] == _message_client_join_game_request; + return 0; +} + +void const *third_person_protocol_join(void const *message, unsigned short bytes, void *buffer) +{ + byte *out = buffer; + if (!third_person_protocol_inner_valid(message, bytes)) return NULL; + build_message_header((word *)out, bytes + 8, 2, 0); + out[2] = THIRD_PERSON_PROTOCOL_JOIN_KIND; + out[3] = THIRD_PERSON_PROTOCOL_JOIN_REVISION; + out[4] = THIRD_PERSON_PROTOCOL_VERSION & 255; + out[5] = THIRD_PERSON_PROTOCOL_VERSION >> 8; + out[6] = out[7] = 0; + memcpy(out + 8, message, bytes); + return out; +} + +/* Camera sessions require this proof before admission, even Forced Off. + * OpenCE Crossplay does not send or accept a camera envelope. */ +int third_person_protocol_unwrap(void const *message, unsigned short bytes, + void *inner, unsigned short *inner_bytes) +{ + byte const *in = message; + word header; + if (bytes <= 10 || bytes > THIRD_PERSON_PROTOCOL_JOIN_MAX || + in[2] != THIRD_PERSON_PROTOCOL_JOIN_KIND || in[3] != THIRD_PERSON_PROTOCOL_JOIN_REVISION || + in[4] != (THIRD_PERSON_PROTOCOL_VERSION & 255) || + in[5] != (THIRD_PERSON_PROTOCOL_VERSION >> 8) || in[6] || in[7]) return 0; + memcpy(&header, in, sizeof(header)); + if (GET_MESSAGE_FLAGS(header) || GET_MESSAGE_TYPE(header) != 2 || + GET_MESSAGE_SIZE(header) != bytes || !third_person_protocol_inner_valid(in + 8, bytes - 8)) return 0; + *inner_bytes = bytes - 8; + memcpy(inner, in + 8, *inner_bytes); + return 1; +} diff --git a/port/linux/game/third_person_protocol.h b/port/linux/game/third_person_protocol.h new file mode 100644 index 0000000000..e735cf4ad1 --- /dev/null +++ b/port/linux/game/third_person_protocol.h @@ -0,0 +1,30 @@ +/* Admission for the experimental camera wire format, independent of MCC. */ +#ifndef THIRD_PERSON_PROTOCOL_H +#define THIRD_PERSON_PROTOCOL_H + +/* OpenCE 43 plus shoulder-camera input and policy in cooperative flag bits 4-5. + * All map families share this agreement; older camera sessions are incompatible. */ +#define THIRD_PERSON_PROTOCOL_VERSION 32744 + +struct network_game; +void third_person_session_host_begin(void); +void third_person_session_host_end(void); +void third_person_session_lock(void); +int third_person_session_locked(void); +int third_person_session_set(int enabled); +int third_person_session_active(void); +void third_person_session_client_begin(unsigned int version); +void third_person_session_client_clear(void); +unsigned int third_person_session_version(char const *map); +int third_person_session_compatible(char const *map, unsigned int version, unsigned int flags); + +#define THIRD_PERSON_PROTOCOL_JOIN_KIND 102 +#define THIRD_PERSON_PROTOCOL_JOIN_REVISION 1 +#define THIRD_PERSON_PROTOCOL_JOIN_MAX 520 + +/* Buffers must hold JOIN_MAX bytes and be word-aligned, like engine messages. */ +void const *third_person_protocol_join(void const *message, unsigned short bytes, void *buffer); +int third_person_protocol_unwrap(void const *message, unsigned short bytes, + void *inner, unsigned short *inner_bytes); + +#endif diff --git a/port/linux/game/third_person_weapon.c b/port/linux/game/third_person_weapon.c new file mode 100644 index 0000000000..3a07b57337 --- /dev/null +++ b/port/linux/game/third_person_weapon.c @@ -0,0 +1,264 @@ +/* The host and predicting clients solve shots from the same world markers. */ +#include "cseries.h" +#include "third_person.h" +#include "mcc_projectiles.h" +#include "camera/director.h" +#include "game/game.h" +#include "game/players.h" +#include "units/units.h" +#include "physics/collisions.h" +#include "items/weapons.h" +#include "items/weapon_definitions.h" +#include "units/unit_definitions.h" +#include "effects/effect_definitions.h" + +char const *config_string(char const *name); +void platform_log(char const *format, ...); + +static boolean muzzle_player(short player, long unit_index) +{ + struct unit_datum *unit; + director_perspective perspective; + if (!third_person_active(player) || + unit_index == NONE || player_control_get_unit_index(player) != unit_index || + player_control_get_zoom_level(player) != NONE) + return FALSE; + unit = unit_try_and_get(unit_index); + return unit && unit->object.parent_object_index == NONE && + !TEST_FLAG(unit->object.damage_flags, _object_dead_bit) && + !director_desired_perspective(unit_index, &perspective); +} + +static boolean muzzle_network_player(long unit_index) +{ + struct unit_datum *unit = unit_index != NONE ? unit_try_and_get(unit_index) : NULL; + director_perspective perspective; + return unit && unit->unit.player_index != NONE && + unit->object.parent_object_index == NONE && + !TEST_FLAG(unit->object.damage_flags, _object_dead_bit) && + unit->unit.current_zoom_level == NONE && + third_person_policy() != _third_person_forced_off && + TEST_FLAG(unit->unit.control_flags, THIRD_PERSON_INPUT_BIT) && + /* A stale or forged input bit cannot override an authored camera. */ + !director_desired_perspective(unit_index, &perspective); +} + +static short muzzle_preview_trigger(struct weapon_datum *weapon, struct weapon_definition *definition) +{ + /* A charged secondary shot leaves a different muzzle on the pistol. */ + return definition->weapon.triggers.count > 1 && + ((weapon->weapon.triggers[0].state == _trigger_charged && + TAG_BLOCK_GET_ELEMENT(&definition->weapon.triggers, 0, struct weapon_trigger_definition)->spew_time <= 0.0f) || + weapon->weapon.triggers[1].state == _trigger_charging || + weapon->weapon.triggers[1].state == _trigger_charged || + weapon->weapon.triggers[1].state == _trigger_spewing) ? 1 : 0; +} + +/* Authored alternating firing effects can name a different barrel, as + the Plasma Rifle does. Only accept trigger markers, never smoke/ejection + locations; missing or custom names retain the ordinary trigger marker. */ +static char const *muzzle_marker(long weapon_index, short trigger_index) +{ + struct weapon_datum *weapon = weapon_get(weapon_index); + struct weapon_definition *definition = weapon_definition_get(weapon->definition_index); + struct weapon_trigger_definition *trigger; + struct weapon_firing_effect_definition *firing; + struct effect_definition *effect; + char const *name; + char const *fallback = trigger_index ? "secondary trigger" : "primary trigger"; + short index = weapon->weapon.triggers[trigger_index].firing_effect_index; + if (definition->weapon.triggers.count <= trigger_index) + return fallback; + trigger = TAG_BLOCK_GET_ELEMENT(&definition->weapon.triggers, trigger_index, struct weapon_trigger_definition); + if (index < 0 || index >= trigger->firing_effects.count) + return fallback; + firing = TAG_BLOCK_GET_ELEMENT(&trigger->firing_effects, index, struct weapon_firing_effect_definition); + if (firing->effects[0].index == NONE) + return fallback; + effect = (struct effect_definition *)tag_get(EFFECT_DEFINITION_TAG, firing->effects[0].index); + if (!effect->locations.count) + return fallback; + /* Effect locations are 32-byte marker names. The tag loader validates + this block, and object_get_marker_by_name still verifies the marker. */ + name = (char const *)effect->locations.address; + if (!strncmp(name, fallback, strlen(fallback)) && + (name[strlen(fallback)] == '\0' || + (name[strlen(fallback)] >= '0' && name[strlen(fallback)] <= '9'))) + return name; + return fallback; +} + +static boolean muzzle_position(long weapon_index, long unit_index, short trigger_index, + real_point3d *position, real_point3d *obstruction, boolean *blocked) +{ + struct object_marker marker; + real_point3d eye; + real_vector3d delta; + real length; + struct collision_result collision; + *blocked = FALSE; + if (weapon_index == NONE || trigger_index < 0 || trigger_index > 1) + return FALSE; + if (!object_get_marker_by_name(weapon_index, muzzle_marker(weapon_index, trigger_index), &marker, 1) && + !object_get_marker_by_name(weapon_index, + trigger_index ? "secondary trigger" : "primary trigger", &marker, 1)) + return FALSE; + unit_get_camera_position(unit_index, &eye); + *position = marker.matrix.position; + vector_from_points3d(&eye, position, &delta); + length = magnitude3d(&delta); + /* Do not let a barrel through a wall spawn a shot beyond that wall. */ + if (length > 0.001f && collision_test_vector(_collision_test_for_projectiles_flags, + &eye, &delta, unit_index, &collision)) + { + point_from_line3d(&eye, &delta, MAX(0.0f, collision.t - 0.01f / length), position); + *obstruction = collision.point; + *blocked = TRUE; + } + return TRUE; +} + +/* Both the preview and actual shot use this solver. The input ray is the + stock weapon ray (aim assistance has already run for a real shot). */ +static boolean muzzle_aim(long weapon_index, long unit_index, short trigger_index, + real_point3d *origin, real_vector3d *forward, real_point3d *target) +{ + real_point3d muzzle, eye, obstruction; + real_vector3d ray; + boolean blocked; + struct collision_result collision; + if (!muzzle_position(weapon_index, unit_index, trigger_index, &muzzle, &obstruction, &blocked)) + return FALSE; + scale_vector3d(forward, 1000.0f, &ray); + point_from_line3d(origin, &ray, 1.0f, target); + if (collision_test_vector(_collision_test_for_projectiles_flags, origin, &ray, unit_index, &collision)) + *target = collision.point; + /* The stock offset can start beyond nearby cover. Check the segment + leading to that origin as well, rather than aiming through the wall. */ + unit_get_camera_position(unit_index, &eye); + vector_from_points3d(&eye, origin, &ray); + if (magnitude3d(&ray) > 0.001f && collision_test_vector(_collision_test_for_projectiles_flags, + &eye, &ray, unit_index, &collision)) + *target = collision.point; + if (blocked) + *target = obstruction; + vector_from_points3d(&muzzle, target, &ray); + /* A target behind the barrel must not turn the shot backwards. Keep + its original direction; the preview traces that same forward path. */ + if ((blocked || dot_product3d(&ray, forward) > 0.001f) && normalize3d(&ray) > 0.001f) + *forward = ray; + *origin = muzzle; + scale_vector3d(forward, 1000.0f, &ray); + point_from_line3d(origin, &ray, 1.0f, target); + if (collision_test_vector(_collision_test_for_projectiles_flags, origin, &ray, unit_index, &collision)) + *target = collision.point; + return TRUE; +} + +boolean third_person_muzzle_shot(long weapon_index, long unit_index, short trigger_index, + real_point3d *origin, real_vector3d *forward) +{ + short player; + real_point3d target; + if (game_connection() != _game_connection_local) + { + if (!muzzle_network_player(unit_index)) + return FALSE; + if (!muzzle_aim(weapon_index, unit_index, trigger_index, origin, forward, &target)) + return FALSE; + if (config_string("debug.network_test")[0]) + platform_log("network muzzle: player %ld trigger %d origin %.4f %.4f %.4f", + (long)DATUM_INDEX_TO_ABSOLUTE_INDEX(unit_get(unit_index)->unit.player_index), (int)trigger_index, + origin->x, origin->y, origin->z); + return TRUE; + } + for (player = 0; player < MAXIMUM_LOCAL_PLAYERS; player++) + if (muzzle_player(player, unit_index)) + return muzzle_aim(weapon_index, unit_index, trigger_index, origin, forward, &target); + return FALSE; +} + +/* The host's visibility history needs the same cover-clamped muzzle as + shoulder shots. No client position is accepted or retained here. */ +boolean third_person_muzzle_history(long unit_index, real_point3d *position) +{ + struct unit_datum *unit; + struct weapon_datum *weapon; + struct weapon_definition *definition; + struct weapon_trigger_definition *trigger; + long weapon_index; + short trigger_index; + real_point3d obstruction; + boolean blocked; + if (game_connection() != _game_connection_network_server || !muzzle_network_player(unit_index)) + return FALSE; + unit = unit_get(unit_index); + weapon_index = unit_inventory_get_weapon(unit_index, unit->unit.current_weapon_index); + if (weapon_index == NONE) + return FALSE; + weapon = weapon_get(weapon_index); + definition = weapon_definition_get(weapon->definition_index); + trigger_index = muzzle_preview_trigger(weapon, definition); + if (definition->weapon.triggers.count <= trigger_index) + return FALSE; + trigger = TAG_BLOCK_GET_ELEMENT(&definition->weapon.triggers, trigger_index, struct weapon_trigger_definition); + if (TEST_FLAG(trigger->flags, _weapon_trigger_uses_weapon_origin_bit) || + TEST_FLAG(trigger->flags, _weapon_trigger_projectiles_cannot_be_aimed_bit)) + return FALSE; + return muzzle_position(weapon_index, unit_index, trigger_index, position, &obstruction, &blocked); +} + +void third_person_muzzle_target(short player, real_point3d *target) +{ + long unit_index, weapon_index; + long aim_target; + short trigger_index = 0; + struct unit_datum *unit; + struct weapon_datum *weapon; + struct weapon_definition *definition; + struct weapon_trigger_definition *trigger; + struct object_marker marker; + real_point3d origin; + real_vector3d forward, right, up; + real velocity; + unit_index = player_control_get_unit_index(player); + if (!muzzle_player(player, unit_index)) + return; + unit = unit_get(unit_index); + weapon_index = unit_inventory_get_weapon(unit_index, unit->unit.current_weapon_index); + if (weapon_index == NONE) + return; + weapon = weapon_get(weapon_index); + definition = weapon_definition_get(weapon->definition_index); + trigger_index = muzzle_preview_trigger(weapon, definition); + if (definition->weapon.triggers.count <= trigger_index) + return; + trigger = TAG_BLOCK_GET_ELEMENT(&definition->weapon.triggers, trigger_index, struct weapon_trigger_definition); + /* Preserve explicit custom firing rules, as the actual shot does. */ + if (TEST_FLAG(trigger->flags, _weapon_trigger_uses_weapon_origin_bit) || + TEST_FLAG(trigger->flags, _weapon_trigger_projectiles_cannot_be_aimed_bit)) + return; + /* MCC's reticle must preview the same nominal ray as the actual shot. */ + if (mcc_projectile_ray(weapon_index, unit_index, trigger_index, FALSE, + &origin, &forward, &velocity, &aim_target)) + { + muzzle_aim(weapon_index, unit_index, trigger_index, &origin, &forward, target); + return; + } + if (!object_get_marker_by_name(weapon_index, + trigger_index ? "secondary trigger" : "primary trigger", &marker, 1)) + return; + origin = marker.matrix.position; + forward = unit->unit.aiming_vector; + unit_adjust_projectile_ray(unit_index, &origin, &forward, &velocity, + TEST_FLAG(unit_definition_get(unit->definition_index)->unit.flags, _unit_fires_from_camera_bit), TRUE); + cross_product3d(global_up3d, &forward, &right); + if (normalize3d(&right) == 0.0f) + right = *global_left3d; + cross_product3d(&forward, &right, &up); + normalize3d(&up); + point_from_line3d(&origin, &forward, trigger->first_person_weapon_offset.x, &origin); + point_from_line3d(&origin, &right, trigger->first_person_weapon_offset.y, &origin); + point_from_line3d(&origin, &up, trigger->first_person_weapon_offset.z, &origin); + muzzle_aim(weapon_index, unit_index, trigger_index, &origin, &forward, target); +} diff --git a/port/linux/game/view_fov.c b/port/linux/game/view_fov.c index 2c0241de5b..ac54e13e08 100644 --- a/port/linux/game/view_fov.c +++ b/port/linux/game/view_fov.c @@ -13,6 +13,7 @@ that draw the first-person weapon (rasterizer and render sources). #include "cseries.h" #include "view_fov.h" +#include "third_person.h" #include "camera/director.h" #include "cutscene/cinematics.h" #include "game/players.h" @@ -260,24 +261,7 @@ boolean viewmodel_is_visible(void) initialized = TRUE; read_at = changes; } - return visible; -} - -/* ---------- whether the energy shield's flare is drawn on the arms */ - -boolean viewmodel_shield_is_visible(void) -{ - static boolean initialized, visible; - static unsigned long read_at; - unsigned long changes = config_changes(); - - if (!initialized || read_at != changes) - { - visible = config_boolean("display.viewmodel_shield") != 0; - initialized = TRUE; - read_at = changes; - } - return visible; + return visible && !third_person_active(render.local_player_index); } boolean viewmodel_draws_geometry(boolean first_person) diff --git a/port/linux/game/view_fov.h b/port/linux/game/view_fov.h index de4dcec5c1..6f410e0a2f 100644 --- a/port/linux/game/view_fov.h +++ b/port/linux/game/view_fov.h @@ -25,9 +25,6 @@ void viewmodel_projection_end(void); /* whether the first-person weapon, hands and attached visuals are drawn (display.viewmodel_visible); its firing, sounds and lights go on either way */ boolean viewmodel_is_visible(void); -/* display.viewmodel_shield: the unit's energy shield flare drawn on the -first-person arms too, as on its body */ -boolean viewmodel_shield_is_visible(void); /* whether a pass draws: not one of the first-person weapon's that is hidden */ boolean viewmodel_draws_geometry(boolean first_person); diff --git a/port/linux/game/viewmodel_shield.c b/port/linux/game/viewmodel_shield.c new file mode 100644 index 0000000000..343abbd75a --- /dev/null +++ b/port/linux/game/viewmodel_shield.c @@ -0,0 +1,175 @@ +/* +VIEWMODEL_SHIELD.C + +The unit's energy shield on its first-person arms (Video Setup > FOV and +Viewmodels > Arm Shields, display.viewmodel_shield; off, the stock game's: +on the body only). The hands are drawn with the unit's own modifier shader, +its colors and values, as render_objects.c draws the body; the weapon is +not. With display.overshield_effect, the overshield comes up on the arms as +its rise passes them (overshield_effect.c). + +The modifier is queued as transparent geometry and drawn later, in the +first-person pass, so the flare is known again by its values: each local +player's hands are given a copy of them here, which the plasma draw +(rasterizer_xbox_plasma_energy.c) passes back to +viewmodel_shield_offset_amount. + +A plasma shield stands off its model by a distance in world units, made +for a body seen across a room; the arms are a few centimetres from the eye, +where that distance fills the view. On the arms it is kept to a share of +the view: at the arms' distance d, drawn at the vertical angle v (the +viewmodel's, display.viewmodel_fov, inside the first-person pass), half the +view's height is d tan(v/2) world units, and the flare stands off no more +than VIEWMODEL_SHIELD_STAND_OFF of that, whatever the field of view or the +resolution. +*/ + +#include "cseries.h" +#include "real_math.h" +#include "game/players.h" +#include "models/model_animation_definitions.h" +#include "models/model_definitions.h" +#include "objects/objects.h" +#include "objects/object_definitions.h" +#include "rasterizer/rasterizer.h" +#include "rasterizer/rasterizer_model_types.h" +#include "render/render.h" +#include "shaders/shader_definitions.h" +#include "shaders/shaders.h" +#include "units/units.h" + +#include "viewmodel_shield.h" + +#include + +/* the largest share of half the view's height the flare stands off the +arms by (tuned by eye) */ +#define VIEWMODEL_SHIELD_STAND_OFF 0.01f + +/* port/linux/src/port_config.c */ +int config_boolean(const char *name); +unsigned long config_changes(void); + +/* port/linux/game/overshield_effect.c */ +boolean overshield_effect_arms_values(long unit_index, real const *values, real *arms); + +/* ---------- globals */ + +/* each local player's arms, rewritten each frame before they are drawn */ +static struct +{ + /* the values the arms' modifier is drawn with */ + real values[NUMBER_OF_OUTGOING_OBJECT_FUNCTIONS]; + /* how far from the eye the arms are, world units */ + real distance; +} viewmodel_shields[MAXIMUM_LOCAL_PLAYERS]; + +/* ---------- private code */ + +static boolean viewmodel_shield_enabled( + void) +{ + static unsigned long changes = (unsigned long)-1; + static boolean enabled = FALSE; + + if (changes != config_changes()) + { + changes = config_changes(); + enabled = config_boolean("display.viewmodel_shield") != 0; + } + return enabled; +} + +/* how far the arms are from the eye: their nodes' mean distance, past the +root (the camera's own frame, at the eye), and no nearer than the closest +the first-person pass draws */ +static real viewmodel_shield_arms_distance( + struct model const *model, + real_matrix4x3 const *node_matrices, + real_point3d const *eye, + real nearest) +{ + real sum = 0.f; + short count = 0; + short index; + + for (index = 0; index < model->nodes.count && index < MAXIMUM_NODES_PER_ANIMATION; index++) + { + struct model_node const *node = TAG_BLOCK_GET_ELEMENT(&model->nodes, index, struct model_node); + + if (node->parent_node_index == NONE) + continue; + sum += distance3d(eye, &node_matrices[index].position); + count++; + } + if (count == 0 || !(sum / count > nearest)) + return nearest; + return sum / count; +} + +/* the farthest a flare stands off the arms at that distance and vertical +angle */ +static real viewmodel_shield_maximum_offset( + real distance, + real vertical_field_of_view) +{ + return VIEWMODEL_SHIELD_STAND_OFF * distance * (real)tan(0.5 * (double)vertical_field_of_view); +} + +/* ---------- public code */ + +void viewmodel_shield_apply( + short local_player_index, + long unit_index, + long hands_model_index, + real_matrix4x3 const *hands_node_matrices, + real const *shown_functions, + struct render_model_effect *effect) +{ + struct unit_datum *unit; + struct object_definition *definition; + struct shader *shader; + + if (!viewmodel_shield_enabled() || local_player_index < 0 || local_player_index >= MAXIMUM_LOCAL_PLAYERS) + return; + unit = unit_get(unit_index); + definition = object_definition_get(unit->definition_index); + if (definition->object.modifier_shader.index == NONE) + return; + /* (one that isn't is reported as the body is drawn) */ + shader = shader_definition_get(definition->object.modifier_shader.index); + if (!shader_type_is_valid_for_modifier(shader->base.type)) + return; + + if (!overshield_effect_arms_values(unit_index, shown_functions, + viewmodel_shields[local_player_index].values)) + { + csmemcpy(viewmodel_shields[local_player_index].values, shown_functions, + sizeof(viewmodel_shields[local_player_index].values)); + } + viewmodel_shields[local_player_index].distance = viewmodel_shield_arms_distance( + model_definition_get(hands_model_index), hands_node_matrices, &render.camera.position, + rasterizer_globals.first_person_weapon_near_clip_distance); + effect->modifier_shader = shader; + effect->modifier_animation.colors = unit->object.outgoing_change_colors; + effect->modifier_animation.values = viewmodel_shields[local_player_index].values; +} + +real viewmodel_shield_offset_amount( + real const *values, + real offset_amount) +{ + short index; + + for (index = 0; values && index < MAXIMUM_LOCAL_PLAYERS; index++) + { + if (values == viewmodel_shields[index].values) + { + real maximum = viewmodel_shield_maximum_offset(viewmodel_shields[index].distance, + global_window_parameters.camera.vertical_field_of_view); + + return offset_amount > maximum ? maximum : offset_amount; + } + } + return offset_amount; +} diff --git a/port/linux/game/viewmodel_shield.h b/port/linux/game/viewmodel_shield.h new file mode 100644 index 0000000000..881db98f69 --- /dev/null +++ b/port/linux/game/viewmodel_shield.h @@ -0,0 +1,23 @@ +/* +VIEWMODEL_SHIELD.H + +The unit's energy shield on its first-person arms (viewmodel_shield.c). +*/ + +#ifndef VIEWMODEL_SHIELD_H +#define VIEWMODEL_SHIELD_H + +struct render_model_effect; + +/* the hands' effect, before they are drawn (not the weapon's): with +display.viewmodel_shield, the unit's own modifier shader, with its colors +and a copy of its interpolated picture values that viewmodel_shield_offset_amount knows again */ +void viewmodel_shield_apply(short local_player_index, long unit_index, long hands_model_index, + real_matrix4x3 const *hands_node_matrices, real const *shown_functions, + struct render_model_effect *effect); +/* the plasma shader's final displacement for a flare drawn with these values: on +the arms, at most what stands off them by a small share of the view; +anything else's, its own */ +real viewmodel_shield_offset_amount(real const *values, real offset_amount); + +#endif diff --git a/port/linux/include/controller_remap.h b/port/linux/include/controller_remap.h index 2c9a0de0e3..9cb3667af3 100644 --- a/port/linux/include/controller_remap.h +++ b/port/linux/include/controller_remap.h @@ -13,6 +13,7 @@ enum controller_remap_action PAD_CHAT, PAD_TEAM_CHAT, PAD_VEHICLE_CHAT, PAD_TALK, PAD_CAMERA_FASTER, PAD_CAMERA_SLOWER, PAD_CAMERA_SWITCH, PAD_CAMERA_UP, PAD_CAMERA_DOWN, PAD_CAMERA_CYCLE, + PAD_TOGGLE_PERSPECTIVE, PAD_SWAP_SHOULDER, CONTROLLER_REMAP_ACTIONS }; diff --git a/port/linux/include/frontend_input.h b/port/linux/include/frontend_input.h new file mode 100644 index 0000000000..fbab82aea8 --- /dev/null +++ b/port/linux/include/frontend_input.h @@ -0,0 +1,12 @@ +#ifndef FRONTEND_INPUT_H +#define FRONTEND_INPUT_H + +/* Presentation state only. Never remaps controls or writes glyph preferences. + * -1 is keyboard/mouse, -2 touch, 0..3 the physical controller port. */ +void frontend_input_enable(int enabled); +int frontend_input_device(void); +void frontend_input_pad(short port, unsigned long buttons, int connected); +void frontend_input_keys(unsigned char const *keys, unsigned int count); +void frontend_input_pointer(int touch, int activity); + +#endif diff --git a/port/linux/include/halo_keyboard.h b/port/linux/include/halo_keyboard.h index ed657d6b0e..2c96c9b0a2 100644 --- a/port/linux/include/halo_keyboard.h +++ b/port/linux/include/halo_keyboard.h @@ -38,14 +38,20 @@ enum halo_keyboard_action /* (voice chat's, which the game itself does not read: halo_push_to_talk_held) */ HALO_KEYBOARD_PUSH_TO_TALK, + HALO_KEYBOARD_SWAP_SHOULDER, + HALO_KEYBOARD_FREE_LOOK, + HALO_KEYBOARD_TOGGLE_PERSPECTIVE, /* (the text chat's, which the game itself does not read: a line to everyone, or to the team: port/linux/game/network_chat.c) */ HALO_KEYBOARD_CHAT, HALO_KEYBOARD_TEAM_CHAT, + HALO_KEYBOARD_CAMERA_DISTANCE, /* (the players' votes', yes and no in the vote running: port/linux/game/ network_votekick.c, read with the chat's keys) */ HALO_KEYBOARD_VOTE_YES, HALO_KEYBOARD_VOTE_NO, + HALO_KEYBOARD_CAMERA_HEIGHT, + HALO_KEYBOARD_CAMERA_OFFSET, NUMBER_OF_HALO_KEYBOARD_ACTIONS }; diff --git a/port/linux/include/halo_linux_source_fixups.h b/port/linux/include/halo_linux_source_fixups.h index bf651e02b5..5e9b4a457c 100644 --- a/port/linux/include/halo_linux_source_fixups.h +++ b/port/linux/include/halo_linux_source_fixups.h @@ -33,7 +33,8 @@ void render_interpolation_object_point(long object_index, union real_point3d *po struct observer_result const *render_interpolation_camera(short local_player_index, struct observer_result const *observer); void render_interpolation_first_person(short local_player_index, long weapon_index, long animation_graph_index, - struct real_matrix4x3 *node_matrices, short node_count, struct render_camera const *camera); + struct real_matrix4x3 *node_matrices, + short node_count, struct render_camera const *camera); float render_interpolation_game_time_sec(long ticks); /* whether the map being loaded, by the name it was loaded by, is a @@ -141,4 +142,16 @@ middle button, R and F are held, and the wheel's notches since the last call (port/linux/src/xinput_sdl.c) */ int halo_linux_debug_camera_input(int *middle, int *up, int *down, float *wheel); +/* port/linux/src/touch_gyro.c: consume zoom-only gyro input outside zoom. */ +void halo_linux_gyro_filter(int zoomed, float *yaw, float *pitch); + +/* port/linux/src/shader_prepare.c, through the active GL backend. */ +void render_prepare_map(char const *name); +void render_prepare_end(void); +/* port/linux/game/texture_prepare.c: bounded Xbox/CE preparation, default off. */ +void texture_prepare_map(void); +int render_prepare_texture(void const *header); +/* port/linux/game/material_prepare.c: optional loading-only shader selection. */ +#include "../game/material_prepare.h" + #endif diff --git a/port/linux/include/keyboard_prompts.h b/port/linux/include/keyboard_prompts.h index b571b8e940..ac19f1e8f1 100644 --- a/port/linux/include/keyboard_prompts.h +++ b/port/linux/include/keyboard_prompts.h @@ -8,5 +8,6 @@ void keyboard_prompt_touch(void); /* Physical selection, also used while a menu's automatic choice is pending. */ int keyboard_prompt_active(short port); int keyboard_prompt_enabled(short port); +int keyboard_prompt_menu_enabled(int device); #endif diff --git a/port/linux/include/plasma_collision.h b/port/linux/include/plasma_collision.h new file mode 100644 index 0000000000..25894665da --- /dev/null +++ b/port/linux/include/plasma_collision.h @@ -0,0 +1,28 @@ +/* Synchronous render-only ray batches; no state survives end(). */ +#ifndef PLASMA_COLLISION_H +#define PLASMA_COLLISION_H +union real_point3d; +union real_vector3d; +struct collision_model_instance; +enum { PLASMA_COLLISION_RAYS = 1536, PLASMA_COLLISION_WORDS = PLASMA_COLLISION_RAYS / 32 }; +void plasma_collision_begin(unsigned long flags, union real_point3d const *point, long ignore); +float plasma_collision_depth(unsigned long flags, union real_point3d const *point, + union real_vector3d const *vector, long ignore); +void plasma_collision_end(void); +void plasma_collision_depths(unsigned long flags, union real_point3d const *point, + union real_vector3d const *vectors, int count, long ignore, float *depths); +/* Internal model-major phase; all state and borrowed pointers are synchronous. */ +void plasma_collision_model_depths(struct collision_model_instance const *instance, + union real_point3d const *point, union real_vector3d const *vectors, int count, + unsigned int const *pending, float *depths); +/* Value-only snapshots are bounded and reset with the occlusion fields. */ +enum { PLASMA_COLLISION_SCENE_BYTES = 64 * 1024 }; +struct plasma_collision_scene +{ + unsigned char bytes[PLASMA_COLLISION_SCENE_BYTES]; + unsigned long revision; + int size; +}; +unsigned long plasma_collision_scene_revision(struct plasma_collision_scene *scene, + union real_point3d const *point, float extent, int vehicles); +#endif diff --git a/port/linux/include/plasma_model_shader.h b/port/linux/include/plasma_model_shader.h new file mode 100644 index 0000000000..01f01ddedf --- /dev/null +++ b/port/linux/include/plasma_model_shader.h @@ -0,0 +1,13 @@ +/* Render-only plasma selection and shader additions. No tag data is changed. */ +#ifndef PLASMA_MODEL_SHADER_H +#define PLASMA_MODEL_SHADER_H +struct xgpu_text; +struct nv2a_vertex_lighting; +void plasma_model_lighting_reset(void); +void plasma_model_lighting_slot(long light_index, short slot); +unsigned int plasma_model_lighting_mask(void); +void plasma_model_emit_uniform(struct xgpu_text *text); +void plasma_model_emit_vertex(struct xgpu_text *text, const unsigned long *instruction, + unsigned long index, const struct nv2a_vertex_lighting *lighting); +void plasma_model_emit_pixel(struct xgpu_text *text); +#endif diff --git a/port/linux/include/plasma_occlusion.h b/port/linux/include/plasma_occlusion.h new file mode 100644 index 0000000000..9ac3885de0 --- /dev/null +++ b/port/linux/include/plasma_occlusion.h @@ -0,0 +1,21 @@ +/* Bounded, render-only collision visibility for plasma lights. */ +#ifndef PLASMA_OCCLUSION_H +#define PLASMA_OCCLUSION_H +void plasma_occlusion_reset(void); +void plasma_occlusion_window(void); +void plasma_occlusion_submit(long light, long rasterizer_index); +void plasma_occlusion_model_slot(long rasterizer_index, short slot); +void *plasma_occlusion_texture(long rasterizer_index, int specular); +void *plasma_occlusion_model_texture(int slot, float transform[4]); +unsigned long plasma_occlusion_view_serial(void); +/* Owned by the linked program; locations cannot outlive or alias its GL name. */ +struct plasma_occlusion_uniforms +{ + int enabled, transform[2]; + unsigned int known; + float last_transform[2][4], last_enabled[2]; +}; +void plasma_occlusion_model_initialize(unsigned long program, struct plasma_occlusion_uniforms *uniforms); +void plasma_occlusion_bind_model(struct plasma_occlusion_uniforms *uniforms); +float plasma_occlusion_specular_scale(long rasterizer_index); +#endif diff --git a/port/linux/src/changelog_menu.c b/port/linux/src/changelog_menu.c new file mode 100644 index 0000000000..619425b87b --- /dev/null +++ b/port/linux/src/changelog_menu.c @@ -0,0 +1,45 @@ +/* +CHANGELOG_MENU.C + +The generated main menu keeps its original positions, with the optional +changelog in the lower right corner. Disabling it removes only its own +entry. Custom layouts keep their positions. The parsed menu owns these +changes for its lifetime, with no state carried between game maps. +*/ + +#include "changelog_menu.h" +#include "halo_menus.h" + +#include + +void changelog_menu_configure(struct halo_menus *menus, int enabled) +{ + long widget; + + if (enabled) + return; + for (widget = 0; widget < menus->widget_count; widget++) + { + struct halo_menu_widget *list = &menus->widgets[widget]; + long count; + long *link; + + if (!list->name || strcmp(list->name, "main_menu/main_menu")) + continue; + /* Unlink without freeing: children share the parser's allocation. */ + link = &list->first_child; + for (count = 0; *link != HALO_MENU_NONE && count < menus->child_count; count++) + { + struct halo_menu_child *entry; + + if (*link < 0 || *link >= menus->child_count) + break; + entry = &menus->children[*link]; + if (entry->nested == HALO_MENU_NONE && entry->widget && + !strcmp(entry->widget, "main_menu/changelog_corner")) + *link = entry->next; + else + link = &entry->next; + } + } +} diff --git a/port/linux/src/changelog_menu.h b/port/linux/src/changelog_menu.h new file mode 100644 index 0000000000..9ae74f2d95 --- /dev/null +++ b/port/linux/src/changelog_menu.h @@ -0,0 +1,10 @@ +/* The changelog's optional entry in the generated PC main menu. */ +#ifndef CHANGELOG_MENU_H +#define CHANGELOG_MENU_H + +struct halo_menus; + +/* Called once after reading the menus. Their storage owns all changes. */ +void changelog_menu_configure(struct halo_menus *menus, int enabled); + +#endif diff --git a/port/linux/src/controller_buttons.c b/port/linux/src/controller_buttons.c index 02e33e0497..8818961066 100644 --- a/port/linux/src/controller_buttons.c +++ b/port/linux/src/controller_buttons.c @@ -66,6 +66,7 @@ int controller_button_style_index(char const *name) "ps_classic", "ps_gems", "ps_dark_gems", "ps_modern", "switch_classic", "switch_gems", "switch_modern"}; int i; + if (!strcmp(name, "keyboard")) return 11; if (!strcmp(name, "dark_gems")) return 2; for (i = 0; i < 11; i++) if (!strcmp(name, names[i])) return i; return 0; diff --git a/port/linux/src/controller_remap.c b/port/linux/src/controller_remap.c index 2015085e92..7fb2732aa9 100644 --- a/port/linux/src/controller_remap.c +++ b/port/linux/src/controller_remap.c @@ -14,7 +14,7 @@ static char const *const remap_names[] = {"south","east","west","north","rb","lb void controller_remap_defaults(unsigned char *buttons) { static unsigned char const defaults[CONTROLLER_REMAP_ACTIONS] = { - 0,4,2,3,1,5,6,7,14,15, 13,255,255,9,10,11, 8,255,255,255, 8,9,15,7,6,4 + 0,4,2,3,1,5,6,7,14,15, 13,255,255,9,10,11, 8,255,255,255, 8,9,15,7,6,4, 255,255 }; memcpy(buttons, defaults, sizeof(defaults)); } @@ -30,13 +30,17 @@ void controller_remap_complete(unsigned char *buttons) if (buttons[i] == buttons[j]) { buttons[i] = CONTROLLER_REMAP_UNBOUND; break; } } +static int debug_action(int action) +{ + return action >= PAD_CAMERA_FASTER && action <= PAD_CAMERA_CYCLE; +} + int controller_remap_conflict(unsigned char const *buttons, int action, int button) { - int i, first, end; + int i; if (action < 0 || action >= CONTROLLER_REMAP_ACTIONS || button == CONTROLLER_REMAP_UNBOUND) return -1; - first = action >= PAD_CAMERA_FASTER ? PAD_CAMERA_FASTER : 0; - end = action >= PAD_CAMERA_FASTER ? CONTROLLER_REMAP_ACTIONS : PAD_CAMERA_FASTER; - for (i = first; i < end; i++) if (i != action && buttons[i] == button) return i; + for (i = 0; i < CONTROLLER_REMAP_ACTIONS; i++) + if (i != action && debug_action(i) == debug_action(action) && buttons[i] == button) return i; return -1; } @@ -60,7 +64,8 @@ int controller_remap_parse(char const *text, unsigned char *buttons) unsigned char parsed[CONTROLLER_REMAP_ACTIONS]; int action, i, count; if (!text || !*text) return 0; - count = !strncmp(text, "v3:", 3) ? CONTROLLER_REMAP_ACTIONS : + count = !strncmp(text, "v4:", 3) ? CONTROLLER_REMAP_ACTIONS : + !strncmp(text, "v3:", 3) ? 26 : !strncmp(text, "v2:", 3) ? 25 : CONTROLLER_REMAP_GAME_ACTIONS; if (count != CONTROLLER_REMAP_GAME_ACTIONS) text += 3; controller_remap_defaults(parsed); @@ -75,8 +80,9 @@ int controller_remap_parse(char const *text, unsigned char *buttons) if (i == CONTROLLER_REMAP_BUTTONS) return 0; button = remap_buttons[i]; } - for (i = action >= PAD_CAMERA_FASTER ? PAD_CAMERA_FASTER : 0; i < action; i++) - if (button != CONTROLLER_REMAP_UNBOUND && parsed[i] == button) return 0; + for (i = 0; i < action; i++) + if (debug_action(i) == debug_action(action) && + button != CONTROLLER_REMAP_UNBOUND && parsed[i] == button) return 0; parsed[action] = (unsigned char)button; text += length; if (action < count - 1) { if (*text++ != ',') return 0; } @@ -98,7 +104,7 @@ void controller_remap_format(unsigned char const *buttons, char *text, unsigned if (!size) return; *text = 0; if (size < 4) return; - strcpy(text, "v3:"); + strcpy(text, "v4:"); for (action = 0; action < CONTROLLER_REMAP_ACTIONS; action++) { char const *name = "unbound"; @@ -124,7 +130,7 @@ int controller_remap_read(short port, unsigned char *buttons) { char const *text = config_string(controller_remap_setting((short)i)); valid[i] = controller_remap_parse(text, layouts[i]); - if (valid[i] && i && strncmp(text, "v2:", 3) && strncmp(text, "v3:", 3)) + if (valid[i] && i && strncmp(text, "v2:", 3) && strncmp(text, "v3:", 3) && strncmp(text, "v4:", 3)) { layouts[i][PAD_CHAT] = CONTROLLER_REMAP_UNBOUND; layouts[i][PAD_FORWARD] = 8; diff --git a/port/linux/src/controller_remap_input.c b/port/linux/src/controller_remap_input.c index 5c5324747b..d0235e18ac 100644 --- a/port/linux/src/controller_remap_input.c +++ b/port/linux/src/controller_remap_input.c @@ -100,6 +100,7 @@ int controller_remap_input(short port, XINPUT_GAMEPAD *pad, int connected) struct controller_device device; struct platform_input_state input; unsigned int actions = 0, allowed; + unsigned int debug = (1u << (PAD_CAMERA_CYCLE + 1)) - (1u << PAD_CAMERA_FASTER); int i, context, custom; if (port < 0 || port >= 4) return 0; /* Check from any polled port, including while the selected one is absent. */ @@ -163,8 +164,7 @@ int controller_remap_input(short port, XINPUT_GAMEPAD *pad, int connected) if (!connected) memset(pad, 0, sizeof(*pad)); return 0; /* Menus and the on-screen keyboard use physical buttons. */ } - allowed = context == 3 ? ((1u << CONTROLLER_REMAP_ACTIONS) - (1u << PAD_CAMERA_FASTER)) : - (1u << PAD_CAMERA_FASTER) - 1; + allowed = context == 3 ? debug : ((1u << CONTROLLER_REMAP_ACTIONS) - 1) & ~debug; if (context == 2) allowed |= 1u << PAD_CAMERA_SWITCH; allowed |= 1u << PAD_CAMERA_CYCLE; if (!custom) allowed = 0; /* Stock input retains its original shortcuts. */ @@ -174,7 +174,7 @@ int controller_remap_input(short port, XINPUT_GAMEPAD *pad, int connected) if (!(allowed & (1u << i)) || button == CONTROLLER_REMAP_UNBOUND) continue; /* While the player controls an available free camera, its switch * owns its button. The rest of the debug layout is inactive. */ - if (context == 2 && i < PAD_CAMERA_FASTER && button == layout[PAD_CAMERA_SWITCH]) continue; + if (context == 2 && !(debug & (1u << i)) && button == layout[PAD_CAMERA_SWITCH]) continue; if ((held & ~remap_ports[port].blocked) & (1u << button)) actions |= 1u << i; } if ((actions & (1u << PAD_CAMERA_CYCLE)) && !(remap_ports[port].held & (1u << PAD_CAMERA_CYCLE))) diff --git a/port/linux/src/d3d8_gl.c b/port/linux/src/d3d8_gl.c index 5b3e3e758c..9a339197cb 100644 --- a/port/linux/src/d3d8_gl.c +++ b/port/linux/src/d3d8_gl.c @@ -22,6 +22,9 @@ Conventions carried over from the Xbox: */ #include "xgpu.h" +#include "shader_prepare.h" +#include "plasma_model_shader.h" +#include "plasma_occlusion.h" #include "mcc_environment_shader.h" #include "sdl_platform.h" #include "halo_ui_pointer.h" @@ -544,6 +547,13 @@ struct vertex_shader_object /* a shader lit for each pixel failed to compile or link: lit as the vertex shader lights it from then on */ BOOL lighting_failed; +#ifndef HALO_ANDROID + /* Optional model lighting has separate lazy variants and failure state; + toggling it off must recover the original shaders. */ + GLuint plasma_shader[2], plasma_lit_shader[2]; + BOOL plasma_lighting_failed; + BOOL plasma_model; +#endif #ifndef HALO_GLES /* the vertex array its draws last used, and the streams they had (setup_streams: the layout follows from the two) */ @@ -551,8 +561,8 @@ struct vertex_shader_object unsigned long vertex_array_streams; #endif /* which of shader[] and lit_shader[] have been compiled (bits 0 and 1, - and 2 and 3): one that failed stays 0 and is not compiled again at each - draw */ + and 2 and 3), with bits 4..7 for their optional lighting variants: + one that failed stays 0 and is not compiled again at each draw */ unsigned char shaders_tried; }; @@ -566,6 +576,16 @@ struct fragment_entry GLuint shader; }; +/* Full render-state keys can translate to identical GLSL. Own each source + and shader once for the GL context's lifetime, like the program cache. */ +struct fragment_source_entry +{ + struct fragment_source_entry *next; + unsigned long hash; + char *source; + GLuint shader; +}; + /* the uniforms a draw sets besides the vertex constants */ struct draw_uniforms { @@ -585,6 +605,7 @@ struct draw_uniforms float screen_offset; float texture_lod_bias[4]; float height_fade[4]; + float shield_honeycomb[3][4]; /* display.reversed_depth: a z bias's depth units (nv2a_vsh.c) */ float depth_bias; }; @@ -605,6 +626,7 @@ struct program_entry GLint texture_lod_bias; GLint screen_offset; GLint height_fade; + GLint shield_honeycomb; GLint depth_bias; /* nv2a_pixel_shader_key's source_blend's color, and what it last had */ GLint blend_constant; @@ -612,6 +634,10 @@ struct program_entry /* the lights of a draw lit for each pixel (XGPU_MODEL_LIGHT_COUNT), and constants_serial at their last upload */ GLint model_lights; +#ifndef HALO_ANDROID + GLint plasma_model_slots; + struct plasma_occlusion_uniforms plasma_occlusion; +#endif unsigned long long model_lights_serial; /* the vertex constants c[0..constant_count) the program uses; with @@ -943,6 +969,7 @@ static void program_cache_store(GLuint program, unsigned long long vertex_hash, #endif static struct fragment_entry *fragment_buckets[FRAGMENT_BUCKETS]; +static struct fragment_source_entry *fragment_source_buckets[FRAGMENT_BUCKETS]; static struct program_entry *program_buckets[PROGRAM_BUCKETS]; /* ---------- render targets */ @@ -1196,6 +1223,57 @@ struct gl_device }; static struct gl_device device; +static BOOL material_preparing; + +int render_prepare_texture(void const *header) +{ +#ifndef HALO_GLES + struct xgpu_texture_description description; + GLenum target; + if (device.gl_ready) return xgpu_texture_get(header, NULL, &target, &description) != 0; +#else + (void)header; +#endif + return 0; +} + +int render_material_prepare_mode(int enabled) +{ +#ifndef HALO_GLES + if (!device.gl_ready) return 0; + material_preparing = enabled != 0; + if (!enabled) memset(device.textures, 0, sizeof(device.textures)); + return 1; +#else + (void)enabled; + return 0; +#endif +} + +/* The game owns map boundaries; only this backend knows whether GL exists. */ +void render_prepare_map(char const *name) +{ +#ifndef HALO_GLES + if (device.gl_ready) + { + shader_prepare_begin(name, program_cache_load, program_cache_store); + if (config_boolean("display.shader_prepare")) xgpu_texture_names_prepare(); + } +#else + (void)name; +#endif +} + +void render_prepare_end(void) +{ +#ifndef HALO_GLES + if (device.gl_ready) + { + shader_prepare_end(); + xgpu_texture_names_dispose(); + } +#endif +} /* debug.gpu_stats prints these once a second */ static struct @@ -2229,6 +2307,7 @@ static BOOL bind_targets(BOOL *has_depth) return TRUE; } + /* ---------- display.hdr */ static const char *const tone_mapping_names[NUMBER_OF_XGPU_TONE_MAPPINGS] = @@ -3672,6 +3751,15 @@ HRESULT WINAPI D3DDevice_CreateVertexShader(CONST DWORD *declaration, CONST DWOR memcpy(object->instructions, function + 1, object->instruction_count * 4 * sizeof(DWORD)); } parse_declaration(object, declaration); +#ifndef HALO_ANDROID + if (object->instructions) + { + struct nv2a_vertex_lighting lighting; + /* Keep the feature's instruction-based recognition independent of + which programs the game marks for per-pixel lighting. */ + object->plasma_model = nv2a_vertex_shader_lighting(object->instructions, object->instruction_count, &lighting) && lighting.lights == 2; + } +#endif /* odd values are FVF codes; programmable shader handles are even */ *handle = (DWORD)object; return S_OK; @@ -3850,16 +3938,23 @@ static BOOL words_equal(const void *a, const void *b, unsigned long size) /* lit: the shader that hands the lighting's normal and position on (vertex_shader_object lit_shader) */ -static GLuint vertex_shader_get(struct vertex_shader_object *program, BOOL immediate, BOOL lit) +static GLuint vertex_shader_get(struct vertex_shader_object *program, BOOL immediate, BOOL lit, BOOL plasma_model) { int variant = immediate ? 1 : 0; GLuint *shader = lit ? &program->lit_shader[variant] : &program->shader[variant]; unsigned char tried = (unsigned char)(1 << (variant + (lit ? 2 : 0))); +#ifndef HALO_ANDROID + if (plasma_model) + { + shader = lit ? &program->plasma_lit_shader[variant] : &program->plasma_shader[variant]; + tried <<= 4; + } +#endif if (!*shader && !(program->shaders_tried & tried)) { char *source = nv2a_vertex_shader_to_glsl(program->instructions, program->instruction_count, - immediate ? 0 : device.vertex_shader->packed_mask, lit ? &program->lighting : NULL); + immediate ? 0 : device.vertex_shader->packed_mask, lit ? &program->lighting : NULL, plasma_model); program->shaders_tried |= tried; *shader = xgpu_compile_shader(GL_VERTEX_SHADER, source, "vertex"); @@ -3869,8 +3964,8 @@ static GLuint vertex_shader_get(struct vertex_shader_object *program, BOOL immed char path[512]; FILE *file; - snprintf(path, sizeof(path), "%s/vs%03lu_%d%s.glsl", debug_settings.dump_shaders, program->id, variant, - lit ? "_lit" : ""); + snprintf(path, sizeof(path), "%s/vs%03lu_%d%s%s.glsl", debug_settings.dump_shaders, program->id, variant, + lit ? "_lit" : "", plasma_model ? "_plasma" : ""); if ((file = fopen(path, "w")) != NULL) { fputs(source, file); @@ -3884,6 +3979,51 @@ static GLuint vertex_shader_get(struct vertex_shader_object *program, BOOL immed typedef char pixel_shader_key_size_assert[sizeof(struct nv2a_pixel_shader_key) % 4 == 0 ? 1 : -1]; +static unsigned long fragment_source_hash(const char *source) +{ + unsigned long hash = 2166136261UL; + while (*source) + hash = (hash ^ (unsigned char)*source++) * 16777619UL; + return hash; +} + +/* Consumes source. A hash only chooses candidates: compare every byte before + sharing an object. No generator, driver workaround or shader state is changed. */ +static GLuint fragment_source_get(char *source) +{ + unsigned long hash = fragment_source_hash(source); + struct fragment_source_entry **bucket = &fragment_source_buckets[hash % FRAGMENT_BUCKETS]; + struct fragment_source_entry *entry; + GLuint shader; + + for (entry = *bucket; entry; entry = entry->next) + { + if (entry->hash == hash && !strcmp(entry->source, source)) + { + free(source); + return entry->shader; + } + } + shader = xgpu_compile_shader(GL_FRAGMENT_SHADER, source, "pixel"); + /* Register shared objects once for the upstream program-binary cache. */ + shader_hash_set(shader, source); + entry = malloc(sizeof(*entry)); + if (entry) + { + entry->hash = hash; + entry->source = source; + entry->shader = shader; + entry->next = *bucket; + *bucket = entry; + } + else + { + /* The full-key cache still owns the result if sharing cannot allocate. */ + free(source); + } + return shader; +} + static GLuint fragment_shader_get(const struct nv2a_pixel_shader_key *key) { /* consecutive draws mostly use one of a few pixel shaders (an object's @@ -3915,8 +4055,6 @@ static GLuint fragment_shader_get(const struct nv2a_pixel_shader_key *key) entry->hash = hash; entry->key = *key; source = nv2a_pixel_shader_to_glsl(key); - entry->shader = xgpu_compile_shader(GL_FRAGMENT_SHADER, source, "pixel"); - shader_hash_set(entry->shader, source); if (debug_settings.dump_shaders) { char path[512]; @@ -3929,14 +4067,14 @@ static GLuint fragment_shader_get(const struct nv2a_pixel_shader_key *key) fclose(file); } } - free(source); + entry->shader = fragment_source_get(source); entry->next = *bucket; *bucket = entry; recent[recent_next++ % RECENT_FRAGMENT_COUNT] = entry; return entry->shader; } -static struct program_entry *program_get(GLuint vertex_shader, GLuint fragment_shader) +static struct program_entry *program_get(GLuint vertex_shader, GLuint fragment_shader, BOOL plasma_model) { static struct program_entry *last; unsigned long hash = (vertex_shader * 2654435761UL) ^ fragment_shader; @@ -3944,6 +4082,10 @@ static struct program_entry *program_get(GLuint vertex_shader, GLuint fragment_s struct program_entry *entry; int stage; +#ifndef HALO_GLES + if (!material_preparing) + shader_prepare_record(vertex_shader, fragment_shader, shader_hash(vertex_shader), shader_hash(fragment_shader)); +#endif if (last && last->vertex_shader == vertex_shader && last->fragment_shader == fragment_shader) return last; for (entry = *bucket; entry; entry = entry->next) @@ -3966,7 +4108,9 @@ static struct program_entry *program_get(GLuint vertex_shader, GLuint fragment_s return NULL; #ifndef HALO_GLES - entry->program = program_cache_load(shader_hash(vertex_shader), shader_hash(fragment_shader)); + entry->program = shader_prepare_take(shader_hash(vertex_shader), shader_hash(fragment_shader)); + if (!entry->program) + entry->program = program_cache_load(shader_hash(vertex_shader), shader_hash(fragment_shader)); if (!entry->program) { /* (linked as xgpu_link_program does, keeping its binary) */ @@ -4043,9 +4187,21 @@ static struct program_entry *program_get(GLuint vertex_shader, GLuint fragment_s entry->texture_lod_bias = glGetUniformLocation(entry->program, "texture_lod_bias"); entry->screen_offset = glGetUniformLocation(entry->program, "screen_offset"); entry->height_fade = glGetUniformLocation(entry->program, "height_fade"); + entry->shield_honeycomb = glGetUniformLocation(entry->program, "shield_honeycomb"); entry->depth_bias = glGetUniformLocation(entry->program, "depth_bias"); entry->blend_constant = glGetUniformLocation(entry->program, "blend_constant"); entry->model_lights = glGetUniformLocation(entry->program, "model_lights"); +#ifndef HALO_ANDROID + entry->plasma_model_slots = -1; + if (plasma_model) + { + entry->plasma_model_slots = glGetUniformLocation(entry->program, "plasma_model_slots"); + if (entry->plasma_model_slots >= 0) + plasma_occlusion_model_initialize(entry->program, &entry->plasma_occlusion); + } +#else + (void)plasma_model; +#endif for (stage = 0; stage < D3DTSS_MAXSTAGES; stage++) { char name[8]; @@ -4057,6 +4213,44 @@ static struct program_entry *program_get(GLuint vertex_shader, GLuint fragment_s return entry; } +/* Select both stages together. Only actual selected feature lights need the + optional variant; the mask already respects local settings and host policy. */ +static BOOL per_pixel_lighting(void); +static struct program_entry *draw_program_get(struct vertex_shader_object *program, BOOL immediate, + struct nv2a_pixel_shader_key *key, unsigned int plasma_mask) +{ + struct program_entry *entry = NULL; + BOOL plasma_model = FALSE; + BOOL *failed = &program->lighting_failed; +#ifndef HALO_ANDROID + plasma_model = plasma_mask && program->plasma_model; + if (plasma_model) + failed = &program->plasma_lighting_failed; +#else + (void)plasma_mask; +#endif + key->plasma_model = 0; + key->per_pixel_lighting = 0; + if (program->lighting.lights && !*failed && per_pixel_lighting()) + { + key->per_pixel_lighting = (unsigned char)program->lighting.lights; + key->plasma_model = (unsigned char)plasma_model; + entry = program_get(vertex_shader_get(program, immediate, TRUE, plasma_model), fragment_shader_get(key), plasma_model); + if (!entry) + { + /* Keep each variant's fallback independent of the other. */ + platform_log("GPU: vertex shader %lu cannot be lit for each pixel here (refer to the shader log above): " + "lit for each vertex", program->id); + *failed = TRUE; + key->per_pixel_lighting = 0; + key->plasma_model = 0; + } + } + if (!entry) + entry = program_get(vertex_shader_get(program, immediate, FALSE, plasma_model), fragment_shader_get(key), plasma_model); + return entry; +} + /* ---------- per-draw state */ static unsigned long stage_texture_mode(int stage) @@ -4547,7 +4741,20 @@ static void bind_textures(struct nv2a_pixel_shader_key *key, float texture_scale GLenum gl_target; GLuint gl_texture; - if (target) + if (material_preparing) + { + if (!xgpu_mcc_texture_describe((DWORD const *)texture, &description)) + xgpu_texture_describe(texture->Format, texture->Size, &description); + gl_target = description.cube_map ? GL_TEXTURE_CUBE_MAP : + description.depth > 1 ? GL_TEXTURE_3D : GL_TEXTURE_2D; + gl_texture = 0; + if (description.linear) + { + texture_scale[stage][0] = 1.0f / (float)description.width; + texture_scale[stage][1] = 1.0f / (float)description.height; + } + } + else if (target) { /* (multisampled: its pixels drawn since, resolved) */ render_target_resolve(target); @@ -4886,11 +5093,27 @@ static void gl_check_errors(const char *where) /* the uniforms of the latest draws, converted from these inputs; the serial counts the conversions */ -#define DRAW_UNIFORM_INPUT_COUNT (4 + 4 + 16 + 1 + 16 + 2 + 4 + 1 + 1 + 7 * D3DTSS_MAXSTAGES + 4 + 2) +#define DRAW_UNIFORM_INPUT_COUNT (4 + 4 + 16 + 1 + 16 + 2 + 4 + 1 + 1 + 7 * D3DTSS_MAXSTAGES + 4 + 12 + 2) /* the height fade of the draws that follow (d3d8_gl_set_height_fade): off while its scale is zero */ static float height_fade_value[4]; +static float shield_honeycomb_value[3][4]; + +/* Draw-local extension for shield_honeycomb_gl.h. A zero scale disables it; +the caller restores that state immediately after the owned plasma draw. */ +void d3d8_gl_set_shield_honeycomb(float scale, float time, + const float *difference, const float *parallel, float classic_surface) +{ + shield_honeycomb_value[0][0] = scale != 0.f ? classic_surface : 0.f; + shield_honeycomb_value[0][3] = scale; + if (scale != 0.f) + { + memcpy(shield_honeycomb_value[1], difference, 4 * sizeof(float)); + memcpy(shield_honeycomb_value[2], parallel, 4 * sizeof(float)); + shield_honeycomb_value[1][3] = time; + } +} /* The draws that follow fade out above a height on their model (the shield flare rising up a body: port/linux/game/overshield_effect.c): each vertex's @@ -4979,6 +5202,7 @@ static struct program_entry *prepare_draw(BOOL immediate) struct program_entry *entry; struct draw_uniforms uniforms; BOOL has_depth = FALSE; + unsigned int plasma_mask = 0; int stage; /* (the fixed-function pipeline's draws: immediate mode's only) */ @@ -5008,6 +5232,7 @@ static struct program_entry *prepare_draw(BOOL immediate) key.combiner_state[D3DRS_PSFINALCOMBINERCONSTANT1] = 0; key.texture_modes = D3D__RenderState[D3DRS_PSTEXTUREMODES]; key.mcc_bump_attenuation = mcc_environment_shader_active(); + key.shield_honeycomb = shield_honeycomb_value[0][3] != 0.f; /* the textures before the targets: a render target the draw samples has its multisampled pixels resolved by a blit (render_target_resolve), which binds framebuffers of its own, and the back buffer can be both @@ -5042,23 +5267,13 @@ static struct program_entry *prepare_draw(BOOL immediate) key.count_samples = device.visibility_test_active && xgpu_capabilities.atomic_counters; #endif - entry = NULL; - if (program->lighting.lights && !program->lighting_failed && per_pixel_lighting()) - { - key.per_pixel_lighting = (unsigned char)program->lighting.lights; - entry = program_get(vertex_shader_get(program, immediate, TRUE), fragment_shader_get(&key)); - if (!entry) - { - /* drawn as the vertex shader lights it instead (not at all, - were it to fail too) */ - platform_log("GPU: vertex shader %lu cannot be lit for each pixel here (refer to the shader log above): " - "lit for each vertex", program->id); - program->lighting_failed = TRUE; - key.per_pixel_lighting = 0; - } - } - if (!entry) - entry = program_get(vertex_shader_get(program, immediate, FALSE), fragment_shader_get(&key)); +#ifndef HALO_ANDROID + if (program->plasma_model) + plasma_mask = plasma_model_lighting_mask(); +#endif + entry = draw_program_get(program, immediate, &key, plasma_mask); + /* The loading pass needs the identical shader key, but no draw uniforms. */ + if (material_preparing) return entry; if (!entry) { stats.skipped_link++; @@ -5144,6 +5359,13 @@ static struct program_entry *prepare_draw(BOOL immediate) constants_checkpoint_first = XGPU_VERTEX_CONSTANT_COUNT; constants_checkpoint_last = 0; } +#ifndef HALO_ANDROID + if (plasma_mask && entry->plasma_model_slots >= 0) + { + plasma_occlusion_bind_model(&entry->plasma_occlusion); + glUniform2f(entry->plasma_model_slots, (plasma_mask & 1) ? 1.0f : 0.0f, (plasma_mask & 2) ? 1.0f : 0.0f); + } +#endif /* the lights of a draw lit for each pixel, from the same registers, when any of them changed since the program last had them */ if (entry->model_lights >= 0 && entry->model_lights_serial != constants_serial) @@ -5206,6 +5428,8 @@ static struct program_entry *prepare_draw(BOOL immediate) } memcpy(&inputs[count], height_fade_value, sizeof(height_fade_value)); count += 4; + memcpy(&inputs[count], shield_honeycomb_value, sizeof(shield_honeycomb_value)); + count += 12; inputs[count++] = D3D__RenderState[D3DRS_SOLIDOFFSETENABLE]; inputs[count++] = D3D__RenderState[D3DRS_POLYGONOFFSETZOFFSET]; if (!draw_uniforms_serial || !words_equal(inputs, draw_uniform_inputs, sizeof(inputs))) @@ -5247,6 +5471,7 @@ static struct program_entry *prepare_draw(BOOL immediate) } converted->screen_offset = (float)UI_OFFSET; memcpy(converted->height_fade, height_fade_value, sizeof(converted->height_fade)); + memcpy(converted->shield_honeycomb, shield_honeycomb_value, sizeof(converted->shield_honeycomb)); /* (display.reversed_depth: the z bias's units, the Xbox's depth units toward the camera, in the depth the vertex program writes: one is 1 / viewport_scale.z, the depth buffer's range over the @@ -5276,10 +5501,16 @@ static struct program_entry *prepare_draw(BOOL immediate) uniform_float(entry->screen_offset, &entry->uniforms.screen_offset, draw_uniforms.screen_offset); uniform_vec4(entry->texture_lod_bias, entry->uniforms.texture_lod_bias, draw_uniforms.texture_lod_bias, 1); uniform_vec4(entry->height_fade, entry->uniforms.height_fade, draw_uniforms.height_fade, 1); + uniform_vec4(entry->shield_honeycomb, entry->uniforms.shield_honeycomb[0], draw_uniforms.shield_honeycomb[0], 3); uniform_float(entry->depth_bias, &entry->uniforms.depth_bias, draw_uniforms.depth_bias); return entry; } +void render_material_prepare_draw(void) +{ + if (material_preparing) prepare_draw(FALSE); +} + /* ---------- tracing (debug.gpu_trace_frame) */ static BOOL trace_frame(void) @@ -7769,7 +8000,9 @@ reads back (GetBackBuffer with -1, progress_bar.c) and draws again blurred, a little larger and fainter, under each new frame: the trails of its light. Here it is a render target of the menus' 640x480, which takes the 640 columns in the middle of the frame (where the loading screen draws, as the -menus do on a wide screen) once the loading screen has drawn it, while the +menus do on a wide screen), or the whole width while widescreen loading is +active. The effect and its feedback stay in their original 640x480 space; +only their horizontal presentation changes. Capture happens while the screen asks for it: at its BlockUntilVerticalBlank, its last call, so that what is drawn over it after (the download screen's words) leaves no trail. */ diff --git a/port/linux/src/dualsense.c b/port/linux/src/dualsense.c new file mode 100644 index 0000000000..004e92282b --- /dev/null +++ b/port/linux/src/dualsense.c @@ -0,0 +1,836 @@ +/* +DUALSENSE.C + +A PS5 DualSense's adaptive triggers, lightbar and player lights (dualsense.h). The bytes are dualsense_rules.c's; what +each player wants is the game's (port/linux/game/dualsense_game.c). +*/ + +#include + +#include "platform.h" +#include "port_config.h" +#include "dualsense.h" + +#ifndef DUALSENSE_NONE +#include +#include +#include +#include +#include +#include +#ifdef __linux__ +#include +#include +#include +#include +#include +#endif + +/* the udev rule that lets the player at the seat write the pad's hidraw node (a DualSense is 054C:0CE6, a DualSense +Edge 054C:0DF2; the HID device's own name, bus:vendor:product.instance, is the same on USB and Bluetooth) */ +#define DUALSENSE_UDEV_RULE \ + "KERNEL==\"hidraw*\", KERNELS==\"*:054C:0CE6.*|*:054C:0DF2.*\", MODE=\"0660\", TAG+=\"uaccess\"" + +#define PORTS 4 +#define PADS 8 +/* a port's wish this old (the player died, a menu, the game left) lets the triggers go */ +#define WISH_STALE_MS 300 +/* the triggers sent again though unchanged, while both are up: this long after the game's rumble changed, and at +least this often */ +#define REFRESH_AFTER_RUMBLE_MS 40 +#define REFRESH_EVERY_MS 1000 +/* a trigger counts as up below this (SDL's axis, 0-32767) */ +#define TRIGGER_UP 3000 +/* the game's motors this old (it stopped setting them) are stopped (SDL's rumble lasts 100 ms a call) */ +#define RUMBLE_STALE_MS 150 +/* a node that went is looked for again this often */ +#define REOPEN_MS 1000 +/* a pad is given its fields back for this long at exit and when it leaves, if its queue is full */ +#define RESET_WAIT_MS 200 + +enum backend +{ + BACKEND_UNKNOWN, + BACKEND_NONE, /* not a DualSense, or no way to write to it */ + BACKEND_SDL, /* SDL's own PS5 driver */ + BACKEND_HIDRAW /* Linux: the kernel's driver reads it, we write its hidraw node */ +}; + +struct pad +{ + SDL_JoystickID id; + int used; + int port; + enum backend backend; + int fd; + int bluetooth; + int sequence; + char node[32]; + /* what the pad has from us and what is wanted, by field; on Bluetooth one report every 50 ms at most */ + struct dualsense_link link; + /* the hidraw node went (the pad left: ENODEV, EIO): closed, and opened again when the pad is back */ + int gone; + Uint64 reopen_at; + int reopen_logged; + int failed_logged; + /* the trigger's kick under way (until kick_until, SDL_GetTicks ms) and the events seen */ + int events_known; + unsigned long kicks; + unsigned long context; + int kick_pending, kick_ms, kick_trigger; + Uint64 kick_wait_since; + Uint64 kick_until; + unsigned char kick[DUALSENSE_EFFECT_SIZE]; + /* the rumble seen, and when the triggers are next sent again though unchanged */ + unsigned short rumble_left, rumble_right; + Uint64 refresh_at; + Uint64 triggers_sent_at; + /* the fields to be given back (a busy write keeps them for the next frame) */ + int reset_pending; + int lights_owned, saved_player_index, restoring; +}; + +/* shared with the game's thread and XInputSetState's (spinlock); the pads are the event thread's */ +static SDL_SpinLock shared_lock; +static struct +{ + SDL_JoystickID bound[PORTS]; + struct dualsense_wish wish[PORTS]; + Uint64 wish_ms[PORTS]; + int wished[PORTS]; + /* the motors on each port (XInputSetState) and when they were set */ + unsigned short rumble_left[PORTS], rumble_right[PORTS]; + Uint64 rumble_ms[PORTS]; + /* whether the port's pad is a DualSense this machine drives (the game works out a wish for it only then) */ + int active[PORTS]; +} shared; +static struct pad pads[PADS]; +static int exit_registered; +/* the settings as last sent (for the change to off: the triggers let go, the lightbar given back once) */ +static struct dualsense_settings applied; +static int applied_known; + +/* (read by the game's thread and the event thread: their own lock) */ +static SDL_SpinLock settings_lock; + +struct dualsense_settings dualsense_settings_get(void) +{ + static struct dualsense_settings settings; + static unsigned long read_at; + static int read; + struct dualsense_settings result, before; + + SDL_LockSpinlock(&settings_lock); + if (!read || read_at != config_changes()) + { + char const *strength = config_string("input.trigger_strength"); + char const *lightbar = config_string("input.lightbar"); + + before = settings; + settings.triggers = config_boolean("input.adaptive_triggers"); + settings.percent = dualsense_strength_percent(strength ? strength : ""); + settings.lights = lightbar && !strcmp(lightbar, "player_color"); + if (!read || memcmp(&before, &settings, sizeof(settings))) + platform_log("dualsense: adaptive triggers %s (strength %d%%), lightbar %s (a DualSense's only)", + settings.triggers ? "on" : "off", settings.percent, settings.lights ? "player color" : "off"); + read = 1; + read_at = config_changes(); + } + result = settings; + SDL_UnlockSpinlock(&settings_lock); + return result; +} + +int dualsense_on(void) +{ + struct dualsense_settings settings = dualsense_settings_get(); + + return settings.triggers || settings.lights; +} + +int dualsense_port_active(int port) +{ + int active; + + if (port < 0 || port >= PORTS) + return 0; + SDL_LockSpinlock(&shared_lock); + active = shared.active[port]; + SDL_UnlockSpinlock(&shared_lock); + return active; +} + +void dualsense_wish_set(int port, struct dualsense_wish const *wish) +{ + if (port < 0 || port >= PORTS || !wish) + return; + SDL_LockSpinlock(&shared_lock); + shared.wish[port] = *wish; + shared.wish_ms[port] = SDL_GetTicks(); + shared.wished[port] = 1; + SDL_UnlockSpinlock(&shared_lock); +} + +void dualsense_clear(void) +{ + SDL_LockSpinlock(&shared_lock); + memset(shared.wished, 0, sizeof(shared.wished)); + SDL_UnlockSpinlock(&shared_lock); +} + +void dualsense_port(int port, struct SDL_Gamepad *gamepad, unsigned short left_motor, unsigned short right_motor) +{ + SDL_JoystickID id; + int other; + + if (port < 0 || port >= PORTS) + return; + id = gamepad ? SDL_GetGamepadID(gamepad) : 0; + SDL_LockSpinlock(&shared_lock); + for (other = 0; other < PORTS; other++) + { + if ((other == port && shared.bound[other] != id) || + (other != port && id && shared.bound[other] == id)) + { + shared.wished[other] = 0; + shared.active[other] = 0; + } + } + /* (one pad, one port: a pad that moved here is no longer its old port's) */ + dualsense_bind(shared.bound, PORTS, port, id); + shared.rumble_left[port] = left_motor; + shared.rumble_right[port] = right_motor; + shared.rumble_ms[port] = SDL_GetTicks(); + SDL_UnlockSpinlock(&shared_lock); +} + +#ifdef __linux__ +/* the pad's hidraw node from its input event node (/dev/input/eventN -> /sys/class/input/eventN/device/device is +the HID device, whose hidraw/ folder names the node), and whether it is on Bluetooth (HID_ID's bus 0005); 0 when it +is not a DualSense (054C:0CE6) or DualSense Edge (054C:0DF2) */ +static int hidraw_find(char const *event_path, char *node, size_t node_size, int *bluetooth) +{ + char const *name = strrchr(event_path, '/'); + char path[160]; + char line[160]; + FILE *uevent; + DIR *folder; + struct dirent *entry; + unsigned int bus = 0, vendor = 0, product = 0; + int found = 0; + + name = name ? name + 1 : event_path; + if (strncmp(name, "event", 5)) + return 0; + snprintf(path, sizeof(path), "/sys/class/input/%s/device/device/uevent", name); + uevent = fopen(path, "r"); + if (!uevent) + return 0; + while (fgets(line, sizeof(line), uevent)) + { + if (!strncmp(line, "HID_ID=", 7)) + sscanf(line + 7, "%x:%x:%x", &bus, &vendor, &product); + } + fclose(uevent); + if (vendor != 0x054c || (product != 0x0ce6 && product != 0x0df2)) + return 0; + *bluetooth = bus == 0x0005; + snprintf(path, sizeof(path), "/sys/class/input/%s/device/device/hidraw", name); + folder = opendir(path); + if (!folder) + return 0; + while ((entry = readdir(folder)) != NULL) + { + if (!strncmp(entry->d_name, "hidraw", 6)) + { + snprintf(node, node_size, "/dev/%s", entry->d_name); + found = 1; + break; + } + } + closedir(folder); + return found; +} +#endif + +/* how this pad is driven, said once in debug.txt: the way, the bus, write access, the settings */ +static void pad_choose_backend(struct pad *pad, SDL_Gamepad *gamepad, struct dualsense_settings const *settings) +{ + char const *name = SDL_GetGamepadName(gamepad); + SDL_PropertiesID properties = SDL_GetGamepadProperties(gamepad); + + if (!name) + name = "(unnamed)"; + pad->backend = BACKEND_NONE; + pad->fd = -1; + dualsense_link_init(&pad->link, 0); + /* (other makers' pads that SDL takes for a PS5 pad are left alone) */ + if (!dualsense_is_dualsense(SDL_GetGamepadVendor(gamepad), SDL_GetGamepadProduct(gamepad))) + return; + if (properties && SDL_GetBooleanProperty(properties, SDL_PROP_GAMEPAD_CAP_RGB_LED_BOOLEAN, false)) + { + int wireless = SDL_GetGamepadConnectionState(gamepad) == SDL_JOYSTICK_CONNECTION_WIRELESS; + + pad->backend = BACKEND_SDL; + dualsense_link_init(&pad->link, wireless); + platform_log("dualsense: %s on port %d: through SDL's own PS5 driver (effects with SDL_SendGamepadEffect%s); " + "adaptive triggers %s, lightbar %s", name, pad->port + 1, + wireless ? "; wireless: one report every 50 ms at most" : "", settings->triggers ? "on" : "off", + settings->lights ? "on" : "off"); + return; + } +#ifdef __linux__ + { + char const *path = SDL_GetGamepadPath(gamepad); + + if (!path || !hidraw_find(path, pad->node, sizeof(pad->node), &pad->bluetooth)) + { + platform_log("dualsense: %s on port %d: no hidraw node found for %s: no adaptive triggers or lightbar", + name, pad->port + 1, path ? path : "(no path)"); + return; + } + pad->fd = open(pad->node, O_WRONLY | O_CLOEXEC | O_NONBLOCK); + if (pad->fd < 0) + { + platform_log("dualsense: %s on port %d: cannot write %s (%s): no adaptive triggers or lightbar. A udev " + "rule gives the player at the seat the node: put this line in /etc/udev/rules.d/70-dualsense.rules, " + "run sudo udevadm control --reload, and plug the pad in again: %s", name, pad->port + 1, pad->node, + strerror(errno), DUALSENSE_UDEV_RULE); + return; + } + pad->backend = BACKEND_HIDRAW; + dualsense_link_init(&pad->link, pad->bluetooth); + platform_log("dualsense: %s on port %d: input through the kernel's driver (%s), effects written to %s (%s); " + "adaptive triggers %s, lightbar %s", name, pad->port + 1, path, pad->node, + pad->bluetooth ? "Bluetooth" : "USB", settings->triggers ? "on" : "off", settings->lights ? "on" : "off"); + } +#else + platform_log("dualsense: %s on port %d: SDL's driver does not drive it: no adaptive triggers or lightbar", name, + pad->port + 1); +#endif +} + +/* sends the body (only the enable bits set in it count) */ +static enum dualsense_write_result pad_send(struct pad *pad, SDL_Gamepad *gamepad, + unsigned char const body[DUALSENSE_BODY_SIZE]) +{ + if (pad->backend == BACKEND_SDL) + { + int ok = 1; + + if (!gamepad) + return DUALSENSE_WRITE_GONE; + if (gamepad && (body[DUALSENSE_BODY_ENABLE1] & + (DUALSENSE_ENABLE1_RIGHT_TRIGGER | DUALSENSE_ENABLE1_LEFT_TRIGGER))) + { + unsigned char triggers[DUALSENSE_BODY_SIZE]; + + memcpy(triggers, body, sizeof(triggers)); + triggers[DUALSENSE_BODY_ENABLE2] = 0; + ok = SDL_SendGamepadEffect(gamepad, triggers, (int)sizeof(triggers)); + } + /* (SDL keeps its own LED state: its calls, not our bytes) */ + if (gamepad && (body[DUALSENSE_BODY_ENABLE2] & DUALSENSE_ENABLE2_LIGHTBAR)) + ok = SDL_SetGamepadLED(gamepad, body[DUALSENSE_BODY_RED], body[DUALSENSE_BODY_GREEN], + body[DUALSENSE_BODY_BLUE]) && ok; + if (gamepad && (body[DUALSENSE_BODY_ENABLE2] & DUALSENSE_ENABLE2_PLAYER_LIGHTS)) + ok = SDL_SetGamepadPlayerIndex(gamepad, + pad->restoring ? pad->saved_player_index : + dualsense_player_index_of_lights(body[DUALSENSE_BODY_PLAYER_LIGHTS])) && ok; + if (!ok && !pad->failed_logged) + { + platform_log("dualsense: SDL refused the effect: %s", SDL_GetError()); + pad->failed_logged = 1; + } + /* SDL has no portable busy/error classification. Keep the desired fields for a bounded-rate retry, + including a reset after a partially successful LED/trigger batch. */ + return ok ? DUALSENSE_WRITE_SENT : DUALSENSE_WRITE_BUSY; + } +#ifdef __linux__ + if (pad->backend == BACKEND_HIDRAW) + { + unsigned char report[DUALSENSE_BLUETOOTH_REPORT_SIZE]; + size_t size = dualsense_output_report(report, sizeof(report), pad->bluetooth, pad->sequence, body); + enum dualsense_write_result result; + ssize_t written; + int error; + + if (pad->fd < 0) + return DUALSENSE_WRITE_GONE; + written = write(pad->fd, report, size); + error = errno; + /* (the next sequence number only once this report went: a busy write is sent again with the same one) */ + if (written == (ssize_t)size) + { + pad->sequence = (pad->sequence + 1) & 0x0f; + return DUALSENSE_WRITE_SENT; + } + /* (a short write: tried again as the next window opens) */ + result = written < 0 ? dualsense_write_result_of_errno(error) : DUALSENSE_WRITE_BUSY; + if (result == DUALSENSE_WRITE_GONE) + platform_log("dualsense: port %d: writing %s failed (%s): the pad went; its node is opened again when it " + "is back, and everything sent again", pad->port + 1, pad->node, strerror(error)); + else if (result == DUALSENSE_WRITE_REFUSED) + platform_log("dualsense: port %d: writing %s failed (%s): the pad is left alone", pad->port + 1, + pad->node, strerror(error)); + return result; + } +#endif + (void)gamepad; + return DUALSENSE_WRITE_REFUSED; +} + +static void pad_close(struct pad *pad) +{ +#ifdef __linux__ + if (pad->fd >= 0) + close(pad->fd); +#endif + memset(pad, 0, sizeof(*pad)); + pad->fd = -1; +} + +/* the hidraw node went (ENODEV, EIO): closed; opened again when the pad is back */ +static void pad_lose(struct pad *pad, Uint64 now) +{ +#ifdef __linux__ + if (pad->fd >= 0) + close(pad->fd); +#endif + pad->fd = -1; + pad->gone = 1; + pad->reopen_at = now + REOPEN_MS; + pad->reopen_logged = 0; +} + +#ifdef __linux__ +/* the pad's node again (its path may have changed: a new hidraw number, or the other bus); everything is sent again */ +static void pad_reopen(struct pad *pad, SDL_Gamepad *gamepad, Uint64 now) +{ + char const *path = SDL_GetGamepadPath(gamepad); + char node[sizeof(pad->node)]; + int bluetooth = 0, fd = -1; + + pad->reopen_at = now + REOPEN_MS; + if (path && hidraw_find(path, node, sizeof(node), &bluetooth)) + fd = open(node, O_WRONLY | O_CLOEXEC | O_NONBLOCK); + if (fd < 0) + { + if (!pad->reopen_logged) + platform_log("dualsense: port %d: waiting for the pad's node to come back (tried every %d ms)", + pad->port + 1, REOPEN_MS); + pad->reopen_logged = 1; + return; + } + pad->fd = fd; + memcpy(pad->node, node, sizeof(node)); + pad->bluetooth = bluetooth; + pad->gone = 0; + pad->failed_logged = 0; + pad->sequence = 0; + pad->link.bluetooth = bluetooth; + dualsense_link_forget(&pad->link); + platform_log("dualsense: port %d: %s opened again (%s): everything sent again", pad->port + 1, pad->node, + bluetooth ? "Bluetooth" : "USB"); +} +#endif + +/* one write if one is due (immediate: the window ignored); the fields written, 0 for none */ +static int pad_write(struct pad *pad, SDL_Gamepad *gamepad, Uint64 now, int immediate, + unsigned char body[DUALSENSE_BODY_SIZE]) +{ + enum dualsense_write_result result; + int fields; + + if (pad->gone || pad->backend == BACKEND_NONE || pad->backend == BACKEND_UNKNOWN) + return 0; + fields = immediate ? dualsense_link_due_now(&pad->link, now, body) : dualsense_link_due(&pad->link, now, body); + if (!fields) + return 0; + result = pad_send(pad, gamepad, body); + dualsense_link_result(&pad->link, fields, result, now); + if (result == DUALSENSE_WRITE_SENT) + return fields; + if (result == DUALSENSE_WRITE_GONE) + pad_lose(pad, now); + else if (result == DUALSENSE_WRITE_REFUSED) + /* (a pad that refuses is left alone until it comes back) */ + pad->backend = BACKEND_NONE; + return 0; +} + +/* SDL's default lightbar palette, indexed as its PS5 driver does (SDL 3.4.16, zlib; +see port/third_party/dualsense/README.md). SDL cannot report a previous application's custom RGB. */ +static void default_lightbar(struct pad *pad) +{ + static unsigned char const rgb[7][3] = { + {0, 0, 64}, {64, 0, 0}, {0, 64, 0}, {32, 0, 32}, + {32, 16, 0}, {0, 16, 16}, {16, 16, 16} + }; + int index = pad->saved_player_index < 0 ? 0 : pad->saved_player_index % 7; + + if (pad->backend == BACKEND_SDL) + dualsense_link_want_lightbar(&pad->link, rgb[index][0], rgb[index][1], rgb[index][2]); + else + dualsense_link_want_lightbar(&pad->link, 0, 0, 128); +} + +static void pad_cancel_kick(struct pad *pad) +{ + pad->events_known = 0; + pad->kick_pending = 0; + pad->kick_until = 0; +} + +/* Restore owned fields, retrying busy writes; never leave a pending kick after a reset. */ +static int pad_reset(struct pad *pad, SDL_Gamepad *gamepad, int fields, Uint64 now) +{ + unsigned char body[DUALSENSE_BODY_SIZE]; + unsigned char off[DUALSENSE_EFFECT_SIZE]; + int wanted, forced, sent; + + if (fields & DUALSENSE_FIELD_TRIGGERS) + pad_cancel_kick(pad); + /* A batch may have partly succeeded before SDL reported it busy. */ + fields &= (pad->link.known | pad->link.wanted) & DUALSENSE_FIELDS; + if (!fields || pad->gone || (pad->backend != BACKEND_SDL && pad->backend != BACKEND_HIDRAW)) + return 0; + wanted = pad->link.wanted; + forced = pad->link.forced; + if (fields & DUALSENSE_FIELD_TRIGGERS) + { + dualsense_effect_off(off); + dualsense_link_want_triggers(&pad->link, off, off); + } + if (fields & DUALSENSE_FIELD_LIGHTBAR) + default_lightbar(pad); + if (fields & DUALSENSE_FIELD_PLAYER_LIGHTS) + dualsense_link_want_player_lights(&pad->link, 0); + /* (only these fields, sent though the pad may have them already) */ + pad->link.wanted = fields; + pad->link.forced = fields; + pad->restoring = 1; + sent = pad_write(pad, gamepad, now, 1, body); + pad->restoring = 0; + pad->link.wanted = wanted & ~fields; + pad->link.forced = forced & ~fields; + if (!sent) + /* (busy: kept; gone or refused: nothing more to give back) */ + { + if (pad->gone || pad->backend == BACKEND_NONE) + return 0; + pad->link.wanted |= fields; + return fields; + } + /* (driven again later: sent again then) */ + pad->link.known &= ~sent; + if (sent & DUALSENSE_FIELD_PLAYER_LIGHTS) + pad->lights_owned = 0; + return fields & ~sent; +} + +/* as pad_reset, tried again for up to `ms` (at exit and when a pad leaves, when no later frame will do it) */ +static void pad_reset_wait(struct pad *pad, SDL_Gamepad *gamepad, int fields, Uint64 ms) +{ + Uint64 end = SDL_GetTicks() + ms; + Uint64 now = SDL_GetTicks(); + + for (fields = pad_reset(pad, gamepad, fields, now); fields && now < end; now = SDL_GetTicks()) + { + SDL_Delay(4); + fields = pad_reset(pad, gamepad, fields, SDL_GetTicks()); + } +} + +static void dualsense_exit(void) +{ + int i; + + for (i = 0; i < PADS; i++) + { + if (pads[i].used) + { + pad_reset_wait(&pads[i], SDL_GetGamepadFromID(pads[i].id), DUALSENSE_FIELDS, RESET_WAIT_MS); + pad_close(&pads[i]); + } + } +} + +static struct pad *pad_for(SDL_JoystickID id, int port) +{ + int i, free_slot = -1; + + for (i = 0; i < PADS; i++) + { + if (pads[i].used && pads[i].id == id) + { + if (pads[i].port != port) + pad_cancel_kick(&pads[i]); + pads[i].port = port; + return &pads[i]; + } + if (!pads[i].used && free_slot < 0) + free_slot = i; + } + if (free_slot < 0) + return NULL; + memset(&pads[free_slot], 0, sizeof(pads[free_slot])); + pads[free_slot].used = 1; + pads[free_slot].id = id; + pads[free_slot].port = port; + pads[free_slot].fd = -1; + pads[free_slot].backend = BACKEND_UNKNOWN; + return &pads[free_slot]; +} + +/* both triggers up (SDL's axes) */ +static int triggers_up(SDL_Gamepad *gamepad) +{ + return SDL_GetGamepadAxis(gamepad, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER) < TRIGGER_UP && + SDL_GetGamepadAxis(gamepad, SDL_GAMEPAD_AXIS_LEFT_TRIGGER) < TRIGGER_UP; +} + +/* one pad on its port this frame: what is wanted, then at most one report */ +static void pad_frame(struct pad *pad, SDL_Gamepad *gamepad, struct dualsense_wish const *wish, int fresh, + unsigned short rumble_left, unsigned short rumble_right, struct dualsense_settings const *settings, Uint64 now) +{ + unsigned char body[DUALSENSE_BODY_SIZE]; + unsigned char right[DUALSENSE_EFFECT_SIZE], left[DUALSENSE_EFFECT_SIZE]; + int written, wanted; + + /* (driven again: nothing more to give back of what is wanted) */ + if (settings->triggers) + pad->reset_pending &= ~DUALSENSE_FIELD_TRIGGERS; + if (settings->lights && fresh && wish->player_lights) + pad->reset_pending &= ~(DUALSENSE_FIELD_LIGHTBAR | DUALSENSE_FIELD_PLAYER_LIGHTS); + + /* the rumble changed: it is the kernel's or SDL's own report, so the trigger effects are sent again once both + triggers are up, in case the pad dropped them */ + if (rumble_left != pad->rumble_left || rumble_right != pad->rumble_right) + { + pad->rumble_left = rumble_left; + pad->rumble_right = rumble_right; + pad->refresh_at = now + REFRESH_AFTER_RUMBLE_MS; + } + if (settings->triggers) + { + int unchanged, kicking = 0; + + if (!fresh || !wish->playing || !pad->events_known || pad->context != wish->context || + pad->kick_trigger != wish->kick_trigger) + pad_cancel_kick(pad); + if (fresh && wish->playing) + { + if (pad->events_known && wish->kicks != pad->kicks && wish->kick_ms > 0 && wish->kick_trigger) + { + /* Only the latest event waits. Its duration starts on successful delivery, not observation. */ + pad->kick_pending = 1; + pad->kick_wait_since = now; + pad->kick_ms = wish->kick_ms; + memcpy(pad->kick, wish->kick, sizeof(pad->kick)); + } + pad->kicks = wish->kicks; + pad->context = wish->context; + pad->kick_trigger = wish->kick_trigger; + pad->events_known = 1; + if (pad->kick_pending && now - pad->kick_wait_since >= WISH_STALE_MS) + pad->kick_pending = 0; + kicking = pad->kick_pending || now < pad->kick_until; + memcpy(right, kicking && pad->kick_trigger == 1 ? pad->kick : wish->right, sizeof(right)); + memcpy(left, kicking && pad->kick_trigger == 2 ? pad->kick : wish->left, sizeof(left)); + } + else + { + dualsense_effect_off(right); + dualsense_effect_off(left); + } + dualsense_link_want_triggers(&pad->link, right, left); + unchanged = (pad->link.known & DUALSENSE_FIELD_TRIGGERS) && + !(dualsense_link_dirty(&pad->link) & DUALSENSE_FIELD_TRIGGERS); + /* (a refresh waiting for the Bluetooth window is let go if a trigger is pulled meanwhile) */ + if ((pad->link.forced & DUALSENSE_FIELD_TRIGGERS) && !triggers_up(gamepad)) + pad->link.forced &= ~DUALSENSE_FIELD_TRIGGERS; + if (unchanged && fresh && !kicking && !(pad->link.forced & DUALSENSE_FIELD_TRIGGERS) && + ((pad->refresh_at && now >= pad->refresh_at) || now - pad->triggers_sent_at >= REFRESH_EVERY_MS) && + triggers_up(gamepad)) + { + dualsense_link_force(&pad->link, DUALSENSE_FIELD_TRIGGERS); + pad->refresh_at = 0; + } + if (pad->kick_pending) + dualsense_link_force(&pad->link, DUALSENSE_FIELD_TRIGGERS); + } + else + { + pad_cancel_kick(pad); + dualsense_link_drop(&pad->link, DUALSENSE_FIELD_TRIGGERS & ~pad->reset_pending); + } + + if (settings->lights) + { + if (fresh && wish->player_lights) + { + if (!pad->lights_owned) + { + pad->saved_player_index = SDL_GetGamepadPlayerIndex(gamepad); + pad->lights_owned = 1; + } + dualsense_link_want_lightbar(&pad->link, wish->red, wish->green, wish->blue); + dualsense_link_want_player_lights(&pad->link, wish->player_lights); + } + else if (pad->lights_owned) + pad->reset_pending |= DUALSENSE_FIELD_LIGHTBAR | DUALSENSE_FIELD_PLAYER_LIGHTS; + } + else + dualsense_link_drop(&pad->link, + (DUALSENSE_FIELD_LIGHTBAR | DUALSENSE_FIELD_PLAYER_LIGHTS) & ~pad->reset_pending); + + /* Restorations must go through pad_reset, which restores SDL's saved player index. */ + wanted = pad->link.wanted; + pad->link.wanted &= ~pad->reset_pending; + written = pad_write(pad, gamepad, now, 0, body); + pad->link.wanted = wanted; + if ((written & DUALSENSE_FIELD_TRIGGERS) != 0) + { + pad->triggers_sent_at = now; + if (pad->kick_pending) + { + pad->kick_pending = 0; + pad->kick_until = now + (Uint64)pad->kick_ms; + } + } +} + +void dualsense_frame(void) +{ + struct dualsense_settings settings = dualsense_settings_get(); + SDL_JoystickID bound[PORTS]; + struct dualsense_wish wish[PORTS]; + int fresh[PORTS]; + unsigned short rumble_left[PORTS], rumble_right[PORTS]; + Uint64 now = SDL_GetTicks(); + int port, i; + + /* a setting turned off: the pads' triggers let go and the lightbar and player lights given back */ + if (applied_known) + { + int fields = 0; + + if (applied.triggers && !settings.triggers) + fields |= DUALSENSE_FIELD_TRIGGERS; + if (applied.lights && !settings.lights) + fields |= DUALSENSE_FIELD_LIGHTBAR | DUALSENSE_FIELD_PLAYER_LIGHTS; + for (i = 0; i < PADS && fields; i++) + { + if (pads[i].used) + pads[i].reset_pending |= fields; + } + } + applied = settings; + applied_known = 1; + /* (what a busy write kept, until it is sent) */ + for (i = 0; i < PADS; i++) + { + if (pads[i].used && pads[i].reset_pending) + pads[i].reset_pending = pad_reset(&pads[i], SDL_GetGamepadFromID(pads[i].id), pads[i].reset_pending, now); + } + if (!settings.triggers && !settings.lights) + { + SDL_LockSpinlock(&shared_lock); + memset(shared.active, 0, sizeof(shared.active)); + memset(shared.wished, 0, sizeof(shared.wished)); + SDL_UnlockSpinlock(&shared_lock); + return; + } + if (!exit_registered) + { + atexit(dualsense_exit); + exit_registered = 1; + } + SDL_LockSpinlock(&shared_lock); + for (port = 0; port < PORTS; port++) + { + int rumble_fresh = now - shared.rumble_ms[port] < RUMBLE_STALE_MS; + + bound[port] = shared.bound[port]; + wish[port] = shared.wish[port]; + fresh[port] = shared.wished[port] && now - shared.wish_ms[port] < WISH_STALE_MS; + /* (the game no longer setting the motors: stopped, as SDL's rumble would after its 100 ms) */ + rumble_left[port] = rumble_fresh ? shared.rumble_left[port] : 0; + rumble_right[port] = rumble_fresh ? shared.rumble_right[port] : 0; + } + SDL_UnlockSpinlock(&shared_lock); + + /* a pad no longer bound to a port lets its triggers go */ + for (i = 0; i < PADS; i++) + { + int still = 0; + + if (!pads[i].used) + continue; + for (port = 0; port < PORTS; port++) + still |= bound[port] == pads[i].id && pads[i].port == port; + if (!still) + { + pad_cancel_kick(&pads[i]); + pads[i].reset_pending |= DUALSENSE_FIELDS; + } + } + + for (port = 0; port < PORTS; port++) + { + SDL_Gamepad *gamepad = bound[port] ? SDL_GetGamepadFromID(bound[port]) : NULL; + struct pad *pad = gamepad ? pad_for(bound[port], port) : NULL; + int active; + + if (pad && pad->backend == BACKEND_UNKNOWN) + pad_choose_backend(pad, gamepad, &settings); +#ifdef __linux__ + if (pad && pad->backend == BACKEND_HIDRAW && pad->gone && now >= pad->reopen_at) + pad_reopen(pad, gamepad, now); +#endif + active = pad && pad->backend != BACKEND_NONE; + SDL_LockSpinlock(&shared_lock); + shared.active[port] = active; + SDL_UnlockSpinlock(&shared_lock); + if (active && !pad->gone) + pad_frame(pad, gamepad, &wish[port], fresh[port], rumble_left[port], rumble_right[port], &settings, now); + } +} + +void dualsense_removed(struct SDL_Gamepad *gamepad) +{ + SDL_JoystickID id; + int i; + + if (!gamepad) + return; + id = SDL_GetGamepadID(gamepad); + for (i = 0; i < PADS; i++) + { + if (pads[i].used && pads[i].id == id) + { + /* (the pad may still be there: SDL closing it for another reason; its hidraw node gone, it is not) */ +#ifdef __linux__ + if (pads[i].backend != BACKEND_HIDRAW || (!pads[i].gone && access(pads[i].node, F_OK) == 0)) +#endif + pad_reset_wait(&pads[i], gamepad, DUALSENSE_FIELDS, RESET_WAIT_MS); + if (pads[i].backend != BACKEND_NONE) + platform_log("dualsense: the pad on port %d left", pads[i].port + 1); + pad_close(&pads[i]); + } + } + SDL_LockSpinlock(&shared_lock); + for (i = 0; i < PORTS; i++) + { + if (shared.bound[i] == id) + { + shared.bound[i] = 0; + shared.active[i] = 0; + shared.wished[i] = 0; + } + } + SDL_UnlockSpinlock(&shared_lock); +} + +#endif diff --git a/port/linux/src/dualsense.h b/port/linux/src/dualsense.h new file mode 100644 index 0000000000..3436289c26 --- /dev/null +++ b/port/linux/src/dualsense.h @@ -0,0 +1,91 @@ +/* +DUALSENSE.H + +A PS5 DualSense's (and DualSense Edge's) adaptive triggers, lightbar and player lights, driven from the game +(port/linux/game/dualsense_game.c says what each player wants: lightbar colour, player number, R2 and L2 effects). +Settings: input.adaptive_triggers, input.trigger_strength and input.lightbar. Other pads are never touched. Two ways +to the pad: +- SDL's own PS5 driver (the default; also on Windows and macOS): SDL_SendGamepadEffect with the 47-byte effects body, + SDL_SetGamepadLED, SDL_SetGamepadPlayerIndex. +- Linux with the kernel's hid-playstation driver (input.playstation_kernel_driver): the input stays the kernel's, and + the output reports are written to the pad's own /dev/hidraw node when this user may write it. Only the trigger, + lightbar and player light enable bits are set, so the kernel's own reports (its rumble) and these leave each + other's fields alone. +A pad gets at most one report a frame, only of the fields that changed, and on Bluetooth at most one every 50 ms. A +pad whose hidraw node goes (ENODEV, EIO: the Bluetooth link lost) has it closed, looked for again each second and, +back, everything sent again. A kick is the firing trigger's shape for a round; its duration starts after delivery, +then the held shape returns. Pending kicks are discarded when their gameplay context changes. The +triggers are sent again though unchanged, while both are up, once a second and after the game's rumble changes. The +triggers are let go (and the lightbar given back) at exit, when a pad leaves and when a setting is turned off. +debug.txt says how each DualSense is driven, or why not. +*/ + +#ifndef __DUALSENSE_H +#define __DUALSENSE_H + +#include "dualsense_rules.h" + +struct SDL_Gamepad; + +/* no adaptive triggers, lightbar or player lights on Android and in a browser: SDL's gamepad calls are not there */ +#if defined(HALO_ANDROID) || defined(HALO_ARM64_GUEST) || defined(HALO_WEB) +#define DUALSENSE_NONE +#endif + +/* the settings (read again when one was written) */ +struct dualsense_settings +{ + int triggers; /* input.adaptive_triggers */ + int percent; /* input.trigger_strength (dualsense_strength_percent) */ + int lights; /* input.lightbar not "off": the lightbar and the player lights */ +}; + +/* what one controller port's player wants on its pad (the game side, each frame it has a player) */ +struct dualsense_wish +{ + /* A changed context cancels pending feedback (weapon, mapping, player or map). */ + unsigned long context; + int playing; + unsigned char red, green, blue; + /* the player lights' bits (dualsense_player_lights; 0: none) */ + unsigned char player_lights; + unsigned char right[DUALSENSE_EFFECT_SIZE]; + unsigned char left[DUALSENSE_EFFECT_SIZE]; + /* the weapon's last event kick (ms 0: none) and its events so far (a change = a kick) */ + unsigned char kick[DUALSENSE_EFFECT_SIZE]; + int kick_ms; + unsigned long kicks; + /* 0: no weapon trigger, 1: R2, 2: L2. */ + int kick_trigger; +}; + +#ifndef DUALSENSE_NONE +struct dualsense_settings dualsense_settings_get(void); +/* whether either feature is on */ +int dualsense_on(void); +/* whether controller port `port`'s pad is a DualSense this machine drives (the game works out a wish only then) */ +int dualsense_port_active(int port); +/* the game: controller port `port`'s player wants this (copied) */ +void dualsense_wish_set(int port, struct dualsense_wish const *wish); +/* Discard requests at a map/checkpoint boundary without touching SDL on the game thread. */ +void dualsense_clear(void); +/* xinput_sdl.c XInputSetState: the SDL pad that drives controller port `port` (NULL: none), and whether the game's +rumble is on (the triggers are sent again after it changes) */ +void dualsense_port(int port, struct SDL_Gamepad *gamepad, unsigned short left_motor, unsigned short right_motor); +/* sdl_platform.c: once a frame, after the events (sends what changed) */ +void dualsense_frame(void); +/* sdl_platform.c: a pad is about to be closed (NULL: nothing) */ +void dualsense_removed(struct SDL_Gamepad *gamepad); +#else +#define dualsense_settings_get() (dualsense_no_settings) +#define dualsense_on() 0 +#define dualsense_port_active(port) 0 +#define dualsense_wish_set(port, wish) ((void)0) +#define dualsense_clear() ((void)0) +#define dualsense_port(port, gamepad, left_motor, right_motor) ((void)0) +#define dualsense_frame() ((void)0) +#define dualsense_removed(gamepad) ((void)0) +static struct dualsense_settings const dualsense_no_settings = { 0, 100, 0 }; +#endif + +#endif diff --git a/port/linux/src/dualsense_rules.c b/port/linux/src/dualsense_rules.c new file mode 100644 index 0000000000..00d17e2601 --- /dev/null +++ b/port/linux/src/dualsense_rules.c @@ -0,0 +1,667 @@ +/* +DUALSENSE_RULES.C + +A PS5 DualSense's output bytes (dualsense_rules.h). The zone-based trigger effects are packed as in John "Nielk1" +Klein's TriggerEffectGenerator (MIT licence, 2021-2022); the body layout, the player lights' patterns and the report +framing follow SDL3's PS5 driver (zlib licence). Notices and pinned references are in +port/third_party/dualsense/README.md. Pure: no SDL, no game. +*/ + +#include +#include + +#include "dualsense_rules.h" + +static int clamp(int value, int low, int high) +{ + return value < low ? low : value > high ? high : value; +} + +enum dualsense_weapon_kind dualsense_weapon_kind(int needler, float rate_of_fire, float charging_time, + float heat_per_round, int zoom_levels, int no_projectile, int plasma_rifle_type) +{ + if (no_projectile) + return DUALSENSE_WEAPON_CARRY; + if (charging_time > 0.0f) + return DUALSENSE_WEAPON_CHARGE; + if (zoom_levels >= 2 && rate_of_fire < 3.0f) + return DUALSENSE_WEAPON_SNIPER; + if (needler) + return DUALSENSE_WEAPON_NEEDLER; + if (heat_per_round > 0.0f && rate_of_fire >= 4.0f) + return plasma_rifle_type ? DUALSENSE_WEAPON_PLASMA_HEAT : DUALSENSE_WEAPON_FLAME; + if (rate_of_fire >= 6.0f) + return DUALSENSE_WEAPON_AUTOMATIC; + if (rate_of_fire > 0.0f && rate_of_fire < 1.6f) + return DUALSENSE_WEAPON_HEAVY; + return DUALSENSE_WEAPON_SEMI; +} + +char const *dualsense_weapon_kind_name(enum dualsense_weapon_kind kind) +{ + static char const *const names[DUALSENSE_WEAPON_KINDS] = { + "none", "semi", "heavy", "automatic", "sniper", "charge", "needler", "plasma heat", "carry", "flame" }; + + return kind >= 0 && kind < DUALSENSE_WEAPON_KINDS ? names[kind] : "?"; +} + +void dualsense_effect_off(unsigned char effect[DUALSENSE_EFFECT_SIZE]) +{ + memset(effect, 0, DUALSENSE_EFFECT_SIZE); + effect[0] = 0x05; +} + +/* zones `position` to `last` active, each with the same 3-bit level (Feedback and Vibration share it) */ +static void zones(unsigned char effect[DUALSENSE_EFFECT_SIZE], int position, int last, int level) +{ + unsigned long active = 0, levels = 0; + int zone; + + for (zone = position; zone <= last && zone < 10; zone++) + { + active |= 1UL << zone; + levels |= (unsigned long)(level & 7) << (3 * zone); + } + effect[1] = (unsigned char)(active & 0xff); + effect[2] = (unsigned char)((active >> 8) & 0xff); + effect[3] = (unsigned char)(levels & 0xff); + effect[4] = (unsigned char)((levels >> 8) & 0xff); + effect[5] = (unsigned char)((levels >> 16) & 0xff); + effect[6] = (unsigned char)((levels >> 24) & 0xff); +} + +void dualsense_effect_feedback(unsigned char effect[DUALSENSE_EFFECT_SIZE], int position, int strength) +{ + if (strength <= 0) + { + dualsense_effect_off(effect); + return; + } + memset(effect, 0, DUALSENSE_EFFECT_SIZE); + effect[0] = 0x21; + zones(effect, clamp(position, 0, 9), 9, clamp(strength, 1, 8) - 1); +} + +void dualsense_effect_feedback_span(unsigned char effect[DUALSENSE_EFFECT_SIZE], int first, int last, int strength) +{ + if (strength <= 0) + { + dualsense_effect_off(effect); + return; + } + first = clamp(first, 0, 9); + memset(effect, 0, DUALSENSE_EFFECT_SIZE); + effect[0] = 0x21; + zones(effect, first, clamp(last, first, 9), clamp(strength, 1, 8) - 1); +} + +void dualsense_effect_weapon(unsigned char effect[DUALSENSE_EFFECT_SIZE], int start, int end, int strength) +{ + unsigned long both; + + if (strength <= 0) + { + dualsense_effect_off(effect); + return; + } + start = clamp(start, 2, 7); + end = clamp(end, start + 1, 8); + both = (1UL << start) | (1UL << end); + memset(effect, 0, DUALSENSE_EFFECT_SIZE); + effect[0] = 0x25; + effect[1] = (unsigned char)(both & 0xff); + effect[2] = (unsigned char)((both >> 8) & 0xff); + effect[3] = (unsigned char)(clamp(strength, 1, 8) - 1); +} + +void dualsense_effect_vibration(unsigned char effect[DUALSENSE_EFFECT_SIZE], int position, int amplitude, + int frequency) +{ + if (amplitude <= 0 || frequency <= 0) + { + dualsense_effect_off(effect); + return; + } + memset(effect, 0, DUALSENSE_EFFECT_SIZE); + effect[0] = 0x26; + zones(effect, clamp(position, 0, 9), 9, clamp(amplitude, 1, 8) - 1); + effect[9] = (unsigned char)clamp(frequency, 1, 255); +} + +/* a shape: OFF, FEEDBACK (a position, b strength), WEAPON (a start, b strength, c end), VIBRATION (a position, +b amplitude, c frequency; c 0: the gun's rate of fire times the profile's per_round) */ +enum { OFF, FEEDBACK, WEAPON, VIBRATION, SAME }; +struct shape +{ + unsigned char mode, a, b, c; +}; + +/* ONE profile a weapon kind (the trigger strength setting scales every b): +- held: the trigger as it rests and is pulled; +- firing: while a round went in the last ~170 ms (SAME: the held one), e.g. a vibration at the rate of fire, one + pulse a round, timed by the pad itself (no report a round); +- kick: a short shape sent at each round, then back to held/firing after kick_ms (two reports a round); +- ramp: 1 heat: the held and firing shapes' b goes from its table value at 0 to ramp_to at 1; 2 charge: while + charging, a hum from the held shape's zone whose amplitude goes so; +- charged_kick: a fully charged shot's instead (the plasma pistol's blast); +- the weapon's state comes first, for every kind (dualsense_right_held). */ +#define NO { OFF, 0, 0, 0 } +#define SM { SAME, 0, 0, 0 } +#define F(position, strength) { FEEDBACK, position, strength, 0 } +#define W(start, end, strength) { WEAPON, start, strength, end } +#define V(position, amplitude, frequency) { VIBRATION, position, amplitude, frequency } +static struct profile +{ + struct shape held, firing, kick; + int kick_ms; + int per_round; + int ramp, ramp_to; + char const *feel; + struct shape charged_kick; + int charged_kick_ms; +} const profiles[DUALSENSE_WEAPON_KINDS] = { + /* (strong has room above normal: a hold at most 4 here, a click 5, a kick 7) */ + /* none */ { NO, SM, NO, 0, 0, 0, 0, "off", NO, 0 }, + /* semi (pistol): its click, a sharp snap back each shot (35 ms of 285) */ + { W(4, 7, 4), SM, F(0, 7), 35, 0, 0, 0, "click, snap a shot", NO, 0 }, + /* heavy (shotgun, rockets): a heavy click, a big kick each shot (a 30 Hz jolt, 130 ms of ~700) */ + { W(3, 7, 5), SM, V(0, 7, 30), 130, 0, 0, 0, "heavy click, big kick", NO, 0 }, + /* automatic (assault rifle): light hold; firing, round 1's buzz at 1x the rate of fire = a pulse a round */ + { F(3, 2), V(3, 5, 0), NO, 0, 1, 0, 0, "light hold, a pulse a round", NO, 0 }, + /* sniper: firm, a heavy thump each shot (90 ms of 500) */ + { F(2, 4), SM, F(0, 7), 90, 0, 0, 0, "firm, heavy thump", NO, 0 }, + /* charge (plasma pistol): a hold from zone 2; while it charges a hum from there rising to full; each ordinary + shot a 40 Hz jolt, 70 ms; the overcharged release a longer, lower one (15 Hz, 240 ms) */ + { F(2, 3), SM, V(0, 7, 40), 70, 0, 2, 8, "hums as it charges, a pulse a shot, a blast charged", V(0, 8, 15), 240 }, + /* needler: barely there; firing, a fast light buzz (2x the rate of fire, amplitude 3) */ + { F(3, 2), V(3, 3, 0), NO, 0, 2, 0, 0, "fast light buzz", NO, 0 }, + /* plasma heat (plasma rifle): resistance and hum rising with heat (locked while overheated, as every weapon) */ + { F(2, 2), V(2, 3, 0), NO, 0, 1, 1, 6, "rises with heat, locked overheated", NO, 0 }, + /* carry (ball, flag: no projectile, R2 swings it): free, nothing to shoot */ + { NO, SM, NO, 0, 0, 0, 0, "free (melee carry)", NO, 0 }, + /* flame (flamethrower): light hold; firing, a low 18 Hz roar rising with heat */ + { F(3, 2), V(3, 3, 18), NO, 0, 0, 1, 6, "light hold, a roar while it burns", NO, 0 }, +}; +#define THROB_TICKS 8 +#define THROB_ON_TICKS 2 + +/* the charging hum's frequency (Hz), and the fully charged one's */ +#define CHARGING_HUM_HZ 25 +#define CHARGED_HUM_HZ 40 +#define CHARGING_HUM_LOW 1 +#define CHARGING_HUM_HIGH 3 +/* L2's grenade: a hair trigger, the lightest tick that is still felt, early in the pull, nothing after it */ +#define GRENADE_TICK_START 1 +#define GRENADE_TICK_END 2 +#define GRENADE_TICK_STRENGTH 2 + +static int ramped(int base, int to, float amount) +{ + if (amount <= 0.0f) + return base; + if (amount >= 1.0f) + return to; + return base + (int)((float)(to - base) * amount + 0.5f); +} + +/* the table is for normal. Strong: a hold (resistance from a zone to the end of the pull) two steps up, at most +HOLD_STRONGEST so a full pull held through a fight does not tire; a click CLICK_STRONGEST; a kick or buzz two steps up +(at most 8). Light is a hair trigger on both triggers: every hold and click, whatever the weapon, a tiny tick early in +the pull (a resistance over zones HAIR_START to HAIR_END only, at HAIR_STRENGTH), so the pull is almost free; kicks +and buzzes at most LIGHT_PULSE_MOST */ +#define STRONG_STEPS 2 +#define HOLD_STRONGEST 6 +#define CLICK_STRONGEST 7 +#define HAIR_START 1 +#define HAIR_END 2 +#define HAIR_STRENGTH 2 +#define LIGHT_PULSE_MOST 2 + +static int hair_trigger(int percent) +{ + return percent <= DUALSENSE_STRENGTH_LIGHT; +} + +static int strong(int percent) +{ + return percent > 100; +} + +/* a hold's or click's strength (normal's value) on strong, never above `strongest` (nor under the value) */ +static int held_strong(int value, int strongest) +{ + int result = value + STRONG_STEPS; + + if (result > strongest) + result = strongest > value ? strongest : value; + return clamp(result, 1, 8); +} + +/* light's tick: early in the pull, nothing after it */ +static void hair_tick(unsigned char effect[DUALSENSE_EFFECT_SIZE]) +{ + dualsense_effect_feedback_span(effect, HAIR_START, HAIR_END, HAIR_STRENGTH); +} + +/* a kick's or buzz's strength / amplitude for the setting */ +static int pulse_scaled(int value, int percent) +{ + if (value <= 0) + return value; + if (hair_trigger(percent)) + return value < LIGHT_PULSE_MOST ? value : LIGHT_PULSE_MOST; + if (strong(percent)) + return clamp(value + STRONG_STEPS, 1, 8); + return clamp(value, 1, 8); +} + +/* the shape's bytes for the setting (the shape's numbers normal's) */ +static void shape_effect(unsigned char effect[DUALSENSE_EFFECT_SIZE], struct shape shape, float rate_of_fire, + int per_round, int percent) +{ + int frequency; + + switch (shape.mode) + { + case FEEDBACK: + if (shape.a == 0) + /* (from zone 0: a kick after the shot, or the overheat's lock) */ + dualsense_effect_feedback(effect, 0, pulse_scaled(shape.b, percent)); + else if (hair_trigger(percent)) + hair_tick(effect); + else + dualsense_effect_feedback(effect, shape.a, + strong(percent) ? held_strong(shape.b, HOLD_STRONGEST) : clamp(shape.b, 1, 8)); + break; + case WEAPON: + if (hair_trigger(percent)) + hair_tick(effect); + else + dualsense_effect_weapon(effect, shape.a, shape.c, + strong(percent) ? held_strong(shape.b, CLICK_STRONGEST) : clamp(shape.b, 1, 8)); + break; + case VIBRATION: + frequency = shape.c ? shape.c : clamp((int)(rate_of_fire * (float)(per_round > 0 ? per_round : 1) + 0.5f), 6, 60); + dualsense_effect_vibration(effect, shape.a, pulse_scaled(shape.b, percent), frequency); + break; + default: + dualsense_effect_off(effect); + break; + } +} + +/* dry click (an empty weapon, L2 with no grenades): slack, then a weak hollow click at the bottom of the pull, on every +setting (the click is news, not resistance): light the faintest, strong a step firmer */ +#define DRY_STRENGTH 2 +static void dry_click(unsigned char effect[DUALSENSE_EFFECT_SIZE], int percent) +{ + dualsense_effect_weapon(effect, 7, 8, hair_trigger(percent) ? 1 : DRY_STRENGTH + (strong(percent) ? 1 : 0)); +} + +void dualsense_right_held(unsigned char effect[DUALSENSE_EFFECT_SIZE], struct dualsense_weapon_state const *state, + int percent) +{ + struct profile const *profile = + &profiles[state->kind >= 0 && state->kind < DUALSENSE_WEAPON_KINDS ? state->kind : 0]; + struct shape shape = profile->held; + + /* (the weapon's state first, for every kind: free while it comes up or reloads) */ + if (shape.mode == OFF || state->readying || (state->reloading && !state->overheated)) + { + dualsense_effect_off(effect); + return; + } + if (state->overheated) + { + /* locked solid, with a two-tick throb every eight, until the game lets it fire */ + struct shape locked = F(0, 8), throb = V(0, 8, 8); + + shape_effect(effect, state->ticks % THROB_TICKS < THROB_ON_TICKS ? throb : locked, 0.0f, 1, percent); + return; + } + if (state->empty) + { + dry_click(effect, percent); + return; + } + if (state->firing && profile->firing.mode != SAME) + shape = profile->firing; + if (profile->ramp == 1) + shape.b = (unsigned char)ramped(shape.b, profile->ramp_to, state->heat); + else if (profile->ramp == 2 && state->charge > 0.0f) + { + /* the trigger is held down while it charges, so a resistance building with the charge would not be felt: a + vibration from the hold's zone, its amplitude rising with the charge, faster once fully charged */ + shape = (struct shape)V(profile->held.a, 0, 0); + shape.b = (unsigned char)ramped(CHARGING_HUM_LOW, CHARGING_HUM_HIGH, state->charge); + shape.c = (unsigned char)(state->charge >= 1.0f ? CHARGED_HUM_HZ : CHARGING_HUM_HZ); + } + shape_effect(effect, shape, state->rate_of_fire, profile->per_round, percent); +} + +int dualsense_event(unsigned char effect[DUALSENSE_EFFECT_SIZE], enum dualsense_weapon_kind kind, + enum dualsense_event event, int percent) +{ + struct profile const *profile = &profiles[kind >= 0 && kind < DUALSENSE_WEAPON_KINDS ? kind : 0]; + struct shape shape = NO; + int ms = 0; + + switch (event) + { + case DUALSENSE_EVENT_SHOT_CHARGED: + if (profile->charged_kick.mode != OFF && profile->charged_kick_ms > 0) + { + shape = profile->charged_kick; + ms = profile->charged_kick_ms; + break; + } + /* (no charged kick: an ordinary shot) */ + /* fall through */ + case DUALSENSE_EVENT_SHOT: + shape = profile->kick; + ms = profile->kick_ms; + break; + } + if (shape.mode == OFF || ms <= 0) + { + dualsense_effect_off(effect); + return 0; + } + shape_effect(effect, shape, 0.0f, 1, percent); + return ms; +} + +void dualsense_left_effect(unsigned char effect[DUALSENSE_EFFECT_SIZE], int zoomed, int grenades, int winding, + int percent) +{ + /* the zoom's hold: light none, normal feedback 2, strong 3; grenades in hand the hair tick (zones 1-2, + strength 2) on every setting; wound up, free */ + if (zoomed) + { + if (hair_trigger(percent)) + dualsense_effect_off(effect); + else + dualsense_effect_feedback(effect, 2, strong(percent) ? 3 : 2); + } + else if (winding) + dualsense_effect_off(effect); + else if (grenades > 0) + dualsense_effect_feedback_span(effect, GRENADE_TICK_START, GRENADE_TICK_END, GRENADE_TICK_STRENGTH); + else + dry_click(effect, percent); +} + +int dualsense_strength_percent(char const *name) +{ + if (!strcmp(name, "light")) + return DUALSENSE_STRENGTH_LIGHT; + if (!strcmp(name, "strong")) + return DUALSENSE_STRENGTH_STRONG; + return 100; +} + +int dualsense_is_dualsense(int vendor, int product) +{ + return vendor == 0x054c && (product == 0x0ce6 || product == 0x0df2); +} + +/* (SDL's PS5 driver's pattern for each player, zlib licence: 1 the middle light, 2 the two beside it, 3 the middle +and the two outer ones, 4 all but the middle; 0x20 changes them at once instead of fading) */ +static unsigned char const player_lights[4] = { 0x04, 0x0a, 0x15, 0x1b }; + +unsigned char dualsense_player_lights(int player_number) +{ + if (player_number < 1 || player_number > 4) + return 0; + return (unsigned char)(player_lights[player_number - 1] | 0x20); +} + +int dualsense_player_index_of_lights(unsigned char lights) +{ + int i; + + for (i = 0; i < 4; i++) + { + if ((lights & 0x1f) == player_lights[i]) + return i; + } + return -1; +} + +unsigned long dualsense_crc32(unsigned long crc, unsigned char const *data, size_t size) +{ + size_t i; + int bit; + + crc = ~crc & 0xffffffffUL; + for (i = 0; i < size; i++) + { + crc ^= data[i]; + for (bit = 0; bit < 8; bit++) + crc = (crc >> 1) ^ (0xEDB88320UL & (0UL - (crc & 1UL))); + } + return ~crc & 0xffffffffUL; +} + +size_t dualsense_output_report(unsigned char *report, size_t size, int bluetooth, int sequence, + unsigned char const body[DUALSENSE_BODY_SIZE]) +{ + if (!bluetooth) + { + if (size < DUALSENSE_USB_REPORT_SIZE) + return 0; + memset(report, 0, DUALSENSE_USB_REPORT_SIZE); + report[0] = 0x02; + memcpy(report + 1, body, DUALSENSE_BODY_SIZE); + return DUALSENSE_USB_REPORT_SIZE; + } + else + { + static unsigned char const hidp_header = 0xA2; /* the Bluetooth HID "data, output" header, part of the CRC */ + unsigned long crc; + + if (size < DUALSENSE_BLUETOOTH_REPORT_SIZE) + return 0; + memset(report, 0, DUALSENSE_BLUETOOTH_REPORT_SIZE); + report[0] = 0x31; + report[1] = (unsigned char)((sequence & 0x0f) << 4); + report[2] = 0x10; + memcpy(report + 3, body, DUALSENSE_BODY_SIZE); + crc = dualsense_crc32(0, &hidp_header, 1); + crc = dualsense_crc32(crc, report, DUALSENSE_BLUETOOTH_REPORT_SIZE - 4); + report[74] = (unsigned char)(crc & 0xff); + report[75] = (unsigned char)((crc >> 8) & 0xff); + report[76] = (unsigned char)((crc >> 16) & 0xff); + report[77] = (unsigned char)((crc >> 24) & 0xff); + return DUALSENSE_BLUETOOTH_REPORT_SIZE; + } +} + +/* ---- one report at a time a pad (dualsense_rules.h: the link) ---- */ + +/* a field's bytes in the body */ +struct field_span +{ + int field; + int at, size; +}; +static struct field_span const field_spans[] = +{ + { DUALSENSE_FIELD_TRIGGERS, DUALSENSE_BODY_RIGHT_TRIGGER, 2 * DUALSENSE_EFFECT_SIZE }, + { DUALSENSE_FIELD_LIGHTBAR, DUALSENSE_BODY_RED, 3 }, + { DUALSENSE_FIELD_PLAYER_LIGHTS, DUALSENSE_BODY_PLAYER_LIGHTS, 1 } +}; +#define FIELD_SPANS ((int)(sizeof(field_spans) / sizeof(field_spans[0]))) + +enum dualsense_write_result dualsense_write_result_of_errno(int error) +{ + switch (error) + { + /* the queue full, or a moment's shortage: the next window */ + case EAGAIN: + case EINTR: + case ENOMEM: +#ifdef ENOBUFS + case ENOBUFS: +#endif + return DUALSENSE_WRITE_BUSY; + /* the device went: a Bluetooth link lost, the cable pulled */ + case ENODEV: + case EIO: + case ENXIO: + case EPIPE: + return DUALSENSE_WRITE_GONE; + default: + return DUALSENSE_WRITE_REFUSED; + } +} + +void dualsense_link_init(struct dualsense_link *link, int bluetooth) +{ + memset(link, 0, sizeof(*link)); + link->bluetooth = bluetooth != 0; +} + +void dualsense_link_forget(struct dualsense_link *link) +{ + link->known = 0; + link->open_ms = 0; +} + +static void link_want(struct dualsense_link *link, int field, int at, unsigned char const *bytes, int size) +{ + memcpy(link->want + at, bytes, (size_t)size); + link->wanted |= field; +} + +void dualsense_link_want_triggers(struct dualsense_link *link, unsigned char const right[DUALSENSE_EFFECT_SIZE], + unsigned char const left[DUALSENSE_EFFECT_SIZE]) +{ + link_want(link, DUALSENSE_FIELD_TRIGGERS, DUALSENSE_BODY_RIGHT_TRIGGER, right, DUALSENSE_EFFECT_SIZE); + link_want(link, DUALSENSE_FIELD_TRIGGERS, DUALSENSE_BODY_LEFT_TRIGGER, left, DUALSENSE_EFFECT_SIZE); +} + +void dualsense_link_want_lightbar(struct dualsense_link *link, int red, int green, int blue) +{ + unsigned char rgb[3]; + + rgb[0] = (unsigned char)clamp(red, 0, 255); + rgb[1] = (unsigned char)clamp(green, 0, 255); + rgb[2] = (unsigned char)clamp(blue, 0, 255); + link_want(link, DUALSENSE_FIELD_LIGHTBAR, DUALSENSE_BODY_RED, rgb, 3); +} + +void dualsense_link_want_player_lights(struct dualsense_link *link, unsigned char lights) +{ + link_want(link, DUALSENSE_FIELD_PLAYER_LIGHTS, DUALSENSE_BODY_PLAYER_LIGHTS, &lights, 1); +} + +void dualsense_link_force(struct dualsense_link *link, int fields) +{ + link->forced |= fields & DUALSENSE_FIELDS; +} + +void dualsense_link_drop(struct dualsense_link *link, int fields) +{ + link->wanted &= ~fields; + link->forced &= ~fields; +} + +int dualsense_link_dirty(struct dualsense_link const *link) +{ + int dirty = link->wanted & (~link->known | link->forced); + int i; + + for (i = 0; i < FIELD_SPANS; i++) + { + struct field_span const *span = &field_spans[i]; + + if ((link->wanted & span->field) && !(dirty & span->field) && + memcmp(link->want + span->at, link->sent + span->at, (size_t)span->size)) + dirty |= span->field; + } + return dirty & DUALSENSE_FIELDS; +} + +/* the body for these fields: their enable bits, the wanted bytes */ +static void link_body(struct dualsense_link const *link, int fields, unsigned char body[DUALSENSE_BODY_SIZE]) +{ + memcpy(body, link->want, DUALSENSE_BODY_SIZE); + body[DUALSENSE_BODY_ENABLE1] = 0; + body[DUALSENSE_BODY_ENABLE2] = 0; + if (fields & DUALSENSE_FIELD_TRIGGERS) + body[DUALSENSE_BODY_ENABLE1] |= DUALSENSE_ENABLE1_RIGHT_TRIGGER | DUALSENSE_ENABLE1_LEFT_TRIGGER; + if (fields & DUALSENSE_FIELD_LIGHTBAR) + body[DUALSENSE_BODY_ENABLE2] |= DUALSENSE_ENABLE2_LIGHTBAR; + if (fields & DUALSENSE_FIELD_PLAYER_LIGHTS) + body[DUALSENSE_BODY_ENABLE2] |= DUALSENSE_ENABLE2_PLAYER_LIGHTS; +} + +static int link_due(struct dualsense_link *link, unsigned long long now, unsigned char body[DUALSENSE_BODY_SIZE], + int window) +{ + int dirty = dualsense_link_dirty(link); + + if (!dirty || (window && now < link->open_ms)) + return 0; + link_body(link, dirty, body); + return dirty; +} + +int dualsense_link_due(struct dualsense_link *link, unsigned long long now, unsigned char body[DUALSENSE_BODY_SIZE]) +{ + return link_due(link, now, body, 1); +} + +int dualsense_link_due_now(struct dualsense_link *link, unsigned long long now, + unsigned char body[DUALSENSE_BODY_SIZE]) +{ + return link_due(link, now, body, 0); +} + +void dualsense_link_result(struct dualsense_link *link, int fields, enum dualsense_write_result result, + unsigned long long now) +{ + int i; + + fields &= DUALSENSE_FIELDS; + if (result == DUALSENSE_WRITE_SENT) + { + for (i = 0; i < FIELD_SPANS; i++) + { + struct field_span const *span = &field_spans[i]; + + if (fields & span->field) + memcpy(link->sent + span->at, link->want + span->at, (size_t)span->size); + } + link->known |= fields; + link->forced &= ~fields; + link->open_ms = now + (link->bluetooth ? DUALSENSE_BLUETOOTH_INTERVAL_MS : 0); + return; + } + if (result == DUALSENSE_WRITE_BUSY) + { + /* (kept: tried again as the next window opens, never at once) */ + link->open_ms = now + (link->bluetooth ? DUALSENSE_BLUETOOTH_INTERVAL_MS : DUALSENSE_BUSY_RETRY_MS); + return; + } + if (result == DUALSENSE_WRITE_GONE) + dualsense_link_forget(link); +} + +void dualsense_bind(unsigned int *bound, int ports, int port, unsigned int id) +{ + int other; + + if (port < 0 || port >= ports) + return; + if (id) + { + for (other = 0; other < ports; other++) + { + if (other != port && bound[other] == id) + bound[other] = 0; + } + } + bound[port] = id; +} diff --git a/port/linux/src/dualsense_rules.h b/port/linux/src/dualsense_rules.h new file mode 100644 index 0000000000..82bc9c7646 --- /dev/null +++ b/port/linux/src/dualsense_rules.h @@ -0,0 +1,206 @@ +/* +DUALSENSE_RULES.H + +A PS5 DualSense's (and DualSense Edge's) output bytes: trigger effects, lightbar, player lights, the reports that carry +them, and the link that decides what to write when. Pure (no SDL, no game), so tools/harness/tests/dualsense_rules.c +checks it. + +- The shared 47-byte body: the layout of SDL3's DS5EffectsState_t (src/joystick/hidapi/SDL_hidapi_ps5.c, zlib licence). +- A trigger effect's 11 bytes: the zone-based modes (feedback 0x21, weapon 0x25, vibration 0x26) packed as in + John "Nielk1" Klein's TriggerEffectGenerator (MIT licence), and 0x05, the "off" SDL's testcontroller.c sends. +- The whole report for a hidraw write: USB report 0x02 (48 bytes) or Bluetooth report 0x31 (78 bytes: the sequence in + the high nibble, tag 0x10, the body, a CRC-32 over 0xA2 and the first 74 bytes), as SDL's driver frames them. +*/ + +#ifndef __DUALSENSE_RULES_H +#define __DUALSENSE_RULES_H + +#include + +#define DUALSENSE_EFFECT_SIZE 11 +#define DUALSENSE_BODY_SIZE 47 +#define DUALSENSE_USB_REPORT_SIZE 48 +#define DUALSENSE_BLUETOOTH_REPORT_SIZE 78 + +/* the body's fields used here (byte offsets) */ +#define DUALSENSE_BODY_ENABLE1 0 /* 0x04 right trigger effect, 0x08 left trigger effect */ +#define DUALSENSE_BODY_ENABLE2 1 /* 0x04 lightbar colour, 0x10 player lights */ +#define DUALSENSE_BODY_RIGHT_TRIGGER 10 +#define DUALSENSE_BODY_LEFT_TRIGGER 21 +#define DUALSENSE_BODY_PLAYER_LIGHTS 43 +#define DUALSENSE_BODY_RED 44 +#define DUALSENSE_BODY_GREEN 45 +#define DUALSENSE_BODY_BLUE 46 + +#define DUALSENSE_ENABLE1_RIGHT_TRIGGER 0x04 +#define DUALSENSE_ENABLE1_LEFT_TRIGGER 0x08 +#define DUALSENSE_ENABLE2_LIGHTBAR 0x04 +#define DUALSENSE_ENABLE2_PLAYER_LIGHTS 0x10 + +/* the weapon kinds, each with its own R2 profile */ +enum dualsense_weapon_kind +{ + DUALSENSE_WEAPON_NONE = 0, + DUALSENSE_WEAPON_SEMI, /* the pistol: a short click */ + DUALSENSE_WEAPON_HEAVY, /* slow single shots (shotgun, rocket launcher): a heavy click */ + DUALSENSE_WEAPON_AUTOMATIC, /* assault rifle: buzz at the rate of fire */ + DUALSENSE_WEAPON_SNIPER, /* two zoom levels and a slow trigger: firm resistance */ + DUALSENSE_WEAPON_CHARGE, /* a trigger that charges (plasma pistol): resistance from mid pull */ + DUALSENSE_WEAPON_NEEDLER, /* the needler: a fast light buzz */ + DUALSENSE_WEAPON_PLASMA_HEAT, /* rounds make heat (plasma rifle): rises with heat, locked when overheated */ + DUALSENSE_WEAPON_CARRY, /* no trigger with a projectile (ball, flag): free */ + DUALSENSE_WEAPON_FLAME, /* fast, with heat, not the plasma rifle (flamethrower): a roar while it burns */ + DUALSENSE_WEAPON_KINDS +}; + +/* the kind from the weapon's tag numbers: whether its weapon type is the needler, its first trigger's rate of fire +(rounds a second), the longest charging time of its triggers (seconds), its first trigger's heat a round, its zoom +level count, whether no trigger has a projectile (a carried ball or flag), whether its weapon type is the plasma rifle +(a fast weapon with heat is the plasma rifle's kind if so, else the flamethrower's) */ +enum dualsense_weapon_kind dualsense_weapon_kind(int needler, float rate_of_fire, float charging_time, + float heat_per_round, int zoom_levels, int no_projectile, int plasma_rifle_type); +char const *dualsense_weapon_kind_name(enum dualsense_weapon_kind kind); + +/* the weapon in hand now (the game side reads it each frame) */ +struct dualsense_weapon_state +{ + enum dualsense_weapon_kind kind; + float rate_of_fire; + float heat; /* 0-1 */ + int overheated; + float charge; /* 0-1 while charging or charged, else 0 */ + int firing; /* a round in the last few ticks */ + int reloading; + int empty; /* the magazine has no round loaded, or a battery weapon's battery is spent */ + int readying; /* switching weapons: readying or putting away */ + long ticks; /* the game time, for the overheat's throb */ +}; + +/* the events R2 feels once (a kick, then the held shape again) */ +enum dualsense_event +{ + DUALSENSE_EVENT_SHOT, + DUALSENSE_EVENT_SHOT_CHARGED /* a fully charged shot (the plasma pistol's blast) */ +}; + +/* the 11 bytes of a trigger effect; out-of-range numbers are clamped, a strength or amplitude of 0 is "off" */ +void dualsense_effect_off(unsigned char effect[DUALSENSE_EFFECT_SIZE]); +/* resistance from zone `position` (0-9) to the end, strength 1-8 */ +void dualsense_effect_feedback(unsigned char effect[DUALSENSE_EFFECT_SIZE], int position, int strength); +/* resistance between zone `start` (2-7) and `end` (start+1 to 8) that gives way: a click; strength 1-8 */ +void dualsense_effect_weapon(unsigned char effect[DUALSENSE_EFFECT_SIZE], int start, int end, int strength); +/* resistance over zones `first` to `last` (0-9) only, free after it, strength 1-8 */ +void dualsense_effect_feedback_span(unsigned char effect[DUALSENSE_EFFECT_SIZE], int first, int last, int strength); +/* vibration from zone `position` (0-9) on, amplitude 1-8, frequency 1-255 (Hz) */ +void dualsense_effect_vibration(unsigned char effect[DUALSENSE_EFFECT_SIZE], int position, int amplitude, + int frequency); + +/* R2 as the trigger rests / is pulled now, first rule that applies: no weapon or a carried ball/flag: off; readying: +free; overheated: locked with a throb; reloading: free; empty: a dry click; firing: the profile's firing shape; else +its held shape. Heat or charge ramps the strength where the profile says. `percent` is the trigger strength +(dualsense_strength_percent) */ +void dualsense_right_held(unsigned char effect[DUALSENSE_EFFECT_SIZE], struct dualsense_weapon_state const *state, + int percent); +/* an event's kick on R2 and how long it lasts (ms; 0: no kick, e.g. an automatic's shot, which its firing shape does) */ +int dualsense_event(unsigned char effect[DUALSENSE_EFFECT_SIZE], enum dualsense_weapon_kind kind, + enum dualsense_event event, int percent); +/* L2: light while zoomed (free on LIGHT); grenades in hand a hair trigger (the lightest tick still felt, zones 1-2, +nothing after it); a grenade wound up free; none, the dry click */ +void dualsense_left_effect(unsigned char effect[DUALSENSE_EFFECT_SIZE], int zoomed, int grenades, int winding, + int percent); + +/* input.trigger_strength (light, normal, strong) as a percent (DUALSENSE_STRENGTH_LIGHT, 100, +DUALSENSE_STRENGTH_STRONG; anything else 100). The effects are written for normal; strong makes a hold, a click, a +kick and a buzz two steps firmer (a hold at most 6, a click 7, a kick 8); light is a hair trigger on both triggers: a +tiny tick early in the pull (zones 1-2, strength 2) and nothing after it, kicks and buzzes at most 2. */ +#define DUALSENSE_STRENGTH_LIGHT 75 +#define DUALSENSE_STRENGTH_STRONG 175 +int dualsense_strength_percent(char const *name); + +/* whether a USB vendor and product id are Sony's DualSense (054C:0CE6) or DualSense Edge (054C:0DF2): SDL's PS5 type +and LED also match other makers' pads, which are never written to */ +int dualsense_is_dualsense(int vendor, int product); +/* the player lights' byte for split-screen player 1-4 (0 for another number), and back: the player index (0-3) a +byte shows, -1 for none */ +unsigned char dualsense_player_lights(int player_number); +int dualsense_player_index_of_lights(unsigned char lights); + +/* CRC-32 (the zlib / IEEE one, reflected, polynomial 0xEDB88320), continued from `crc` (0 to start) */ +unsigned long dualsense_crc32(unsigned long crc, unsigned char const *data, size_t size); + +/* the whole output report for a hidraw write: the body framed for USB or Bluetooth (sequence 0-15); returns its +size, or 0 when `size` is too small */ +size_t dualsense_output_report(unsigned char *report, size_t size, int bluetooth, int sequence, + unsigned char const body[DUALSENSE_BODY_SIZE]); + +/* A pad's link keeps the state it has from us and the state wanted, by field (the triggers, the lightbar, the player +lights). Each frame the wanted fields are set, then dualsense_link_due says what to write now: only the fields whose +bytes differ from the pad's (or not sent yet, or asked again), all in one report. On Bluetooth at most one report every +DUALSENSE_BLUETOOTH_INTERVAL_MS: a change inside the window waits for it, later changes fold into the waiting one (the +latest wins). USB: one report a frame at most. A report the pad's queue had no room for (busy) waits a window */ +#define DUALSENSE_BLUETOOTH_INTERVAL_MS 50 +/* (busy on USB: the next try this long after) */ +#define DUALSENSE_BUSY_RETRY_MS 16 + +enum dualsense_field +{ + DUALSENSE_FIELD_TRIGGERS = 1, + DUALSENSE_FIELD_LIGHTBAR = 2, + DUALSENSE_FIELD_PLAYER_LIGHTS = 4, + DUALSENSE_FIELDS = 7 +}; + +/* a write's outcome: sent; busy (the queue full, try the next window); gone (the pad left: its node is closed, opened +again when it is back, and everything sent again); refused (the pad is left alone) */ +enum dualsense_write_result +{ + DUALSENSE_WRITE_SENT, + DUALSENSE_WRITE_BUSY, + DUALSENSE_WRITE_GONE, + DUALSENSE_WRITE_REFUSED +}; +/* a failed write's errno as an outcome */ +enum dualsense_write_result dualsense_write_result_of_errno(int error); + +struct dualsense_link +{ + int bluetooth; + /* the wanted state (every field's bytes in a body), the fields wanted, the ones to send though unchanged */ + unsigned char want[DUALSENSE_BODY_SIZE]; + int wanted; + int forced; + /* what the pad has from us, and which fields it has */ + unsigned char sent[DUALSENSE_BODY_SIZE]; + int known; + /* when the next write may be made (ms) */ + unsigned long long open_ms; +}; + +void dualsense_link_init(struct dualsense_link *link, int bluetooth); +/* the pad has nothing from us (opened again after it left): everything wanted is sent again */ +void dualsense_link_forget(struct dualsense_link *link); +/* this frame's wanted fields */ +void dualsense_link_want_triggers(struct dualsense_link *link, unsigned char const right[DUALSENSE_EFFECT_SIZE], + unsigned char const left[DUALSENSE_EFFECT_SIZE]); +void dualsense_link_want_lightbar(struct dualsense_link *link, int red, int green, int blue); +void dualsense_link_want_player_lights(struct dualsense_link *link, unsigned char lights); +/* the fields sent next time though unchanged (a refresh) */ +void dualsense_link_force(struct dualsense_link *link, int fields); +/* the fields no longer driven (the pad keeps what it has) */ +void dualsense_link_drop(struct dualsense_link *link, int fields); +/* the fields that differ from the pad's */ +int dualsense_link_dirty(struct dualsense_link const *link); +/* once a frame: the fields to write now (0: none) with the body to send (their enable bits set); `now` in ms */ +int dualsense_link_due(struct dualsense_link *link, unsigned long long now, unsigned char body[DUALSENSE_BODY_SIZE]); +/* as dualsense_link_due, the window ignored (at exit, a reset) */ +int dualsense_link_due_now(struct dualsense_link *link, unsigned long long now, + unsigned char body[DUALSENSE_BODY_SIZE]); +/* the outcome of writing what dualsense_link_due gave */ +void dualsense_link_result(struct dualsense_link *link, int fields, enum dualsense_write_result result, + unsigned long long now); + +/* ONE PAD, ONE PORT: `port` is now pad `id`'s (0: no pad), and no other port is. A pad moves port mid-game when the +one before it is unplugged; the old port's handle went with that pad, so nothing sets the old port again */ +void dualsense_bind(unsigned int *bound, int ports, int port, unsigned int id); + +#endif diff --git a/port/linux/src/frontend_input.c b/port/linux/src/frontend_input.c new file mode 100644 index 0000000000..bb518d99f8 --- /dev/null +++ b/port/linux/src/frontend_input.c @@ -0,0 +1,58 @@ +/* Input-source selection for the optional frontend. The caller reports raw + * physical edges, before keyboard, touch and controller emulation are merged. */ +#include "frontend_input.h" +#include + +static int frontend_input_enabled; +static int frontend_device = -1; +static int frontend_nonpad_device = -1; +static unsigned long frontend_pad_buttons[4]; +static unsigned char frontend_keys[512]; + +void frontend_input_enable(int enabled) +{ + frontend_input_enabled = enabled; +#ifdef HALO_ANDROID + frontend_device = -2; +#else + frontend_device = -1; +#endif + frontend_nonpad_device = frontend_device; + memset(frontend_pad_buttons, 0, sizeof(frontend_pad_buttons)); + memset(frontend_keys, 0, sizeof(frontend_keys)); +} + +int frontend_input_device(void) +{ + return frontend_device; +} + +void frontend_input_pad(short port, unsigned long buttons, int connected) +{ + if (!frontend_input_enabled || port < 0 || port >= 4) return; + if (!connected) + { + frontend_pad_buttons[port] = 0; + if (frontend_device == port) frontend_device = frontend_nonpad_device; + return; + } + if (buttons & ~frontend_pad_buttons[port]) frontend_device = port; + frontend_pad_buttons[port] = buttons; +} + +void frontend_input_keys(unsigned char const *keys, unsigned int count) +{ + unsigned int i; + if (!frontend_input_enabled) return; + if (count > sizeof(frontend_keys)) count = sizeof(frontend_keys); + for (i = 0; i < count; i++) + { + if (keys[i] && !frontend_keys[i]) frontend_device = frontend_nonpad_device = -1; + frontend_keys[i] = keys[i]; + } +} + +void frontend_input_pointer(int touch, int activity) +{ + if (frontend_input_enabled && activity) frontend_device = frontend_nonpad_device = touch ? -2 : -1; +} diff --git a/port/linux/src/frontend_menu_files.inl b/port/linux/src/frontend_menu_files.inl new file mode 100644 index 0000000000..7608e3d694 --- /dev/null +++ b/port/linux/src/frontend_menu_files.inl @@ -0,0 +1,39 @@ +/* A separate immutable parse preserves the stock Settings set when disabled. + * The enabled set serves main-menu and paused Settings; map-owned pause roots + * retain their existing definitions. The ordinary reader owns discovery. */ +#include "../game/frontend_menu.h" + +struct halo_menus const *frontend_menu_files_load(void) +{ + static int read, succeeded; + static struct halo_menus menus; + struct halo_menus const *legacy = halo_menus_load(); + struct reader reader; + long index; + + if (!legacy || read) + return succeeded ? &menus : legacy; + read = 1; + memset(&reader, 0, sizeof(reader)); + for (index = 0; index < file_count && !reader.failed; index++) + { + size_t length = strlen(files[index].path); + + if (length > 4 && !strcmp(files[index].path + length - 4, ".xml")) + read_file(&reader, &files[index]); + } + free(reader.last_child); + free(reader.last_handler); + free(reader.last_input); + free(reader.last_conditional); + free(reader.last_replace); + if (reader.failed || !reader.menus.widget_count) + { + platform_log("menus: modern frontend unavailable; using legacy menus"); + return legacy; + } + menus = reader.menus; + changelog_menu_configure(&menus, config_boolean("display.changelog")); + succeeded = 1; + return &menus; +} diff --git a/port/linux/src/gl.h b/port/linux/src/gl.h index d490b26f36..7f71b6e0de 100644 --- a/port/linux/src/gl.h +++ b/port/linux/src/gl.h @@ -103,6 +103,7 @@ this list to generate the guest's entry points */ X(glBindBufferBase) \ X(glBindBufferRange) \ X(glGenVertexArrays) \ + X(glDeleteVertexArrays) \ X(glBindVertexArray) \ X(glEnableVertexAttribArray) \ X(glDisableVertexAttribArray) \ @@ -125,6 +126,7 @@ this list to generate the guest's entry points */ X(glLinkProgram) \ X(glGetProgramiv) \ X(glGetProgramInfoLog) \ + X(glDeleteProgram) \ X(glUseProgram) \ X(glGetUniformLocation) \ X(glUniform1i) \ @@ -220,6 +222,7 @@ context has the extension, never required (gl_functions.c). On ES 3.0 and X(glMapBufferRange) \ X(glBindBufferBase) \ X(glGenVertexArrays) \ + X(glDeleteVertexArrays) \ X(glBindVertexArray) \ X(glEnableVertexAttribArray) \ X(glDisableVertexAttribArray) \ @@ -357,6 +360,7 @@ pointers, sees the declarations without these aliases */ #define glBindBufferBase halo_glBindBufferBase #define glBindBufferRange halo_glBindBufferRange #define glGenVertexArrays halo_glGenVertexArrays +#define glDeleteVertexArrays halo_glDeleteVertexArrays #define glBindVertexArray halo_glBindVertexArray #define glEnableVertexAttribArray halo_glEnableVertexAttribArray #define glDisableVertexAttribArray halo_glDisableVertexAttribArray @@ -379,6 +383,7 @@ pointers, sees the declarations without these aliases */ #define glLinkProgram halo_glLinkProgram #define glGetProgramiv halo_glGetProgramiv #define glGetProgramInfoLog halo_glGetProgramInfoLog +#define glDeleteProgram halo_glDeleteProgram #define glUseProgram halo_glUseProgram #define glGetUniformLocation halo_glGetUniformLocation #define glUniform1i halo_glUniform1i @@ -466,6 +471,7 @@ pointers, sees the declarations without these aliases */ #define glMapBufferRange halo_glMapBufferRange #define glBindBufferBase halo_glBindBufferBase #define glGenVertexArrays halo_glGenVertexArrays +#define glDeleteVertexArrays halo_glDeleteVertexArrays #define glBindVertexArray halo_glBindVertexArray #define glEnableVertexAttribArray halo_glEnableVertexAttribArray #define glDisableVertexAttribArray halo_glDisableVertexAttribArray diff --git a/port/linux/src/keyboard_prompts.c b/port/linux/src/keyboard_prompts.c index 58f348a177..2c635399e3 100644 --- a/port/linux/src/keyboard_prompts.c +++ b/port/linux/src/keyboard_prompts.c @@ -53,8 +53,16 @@ int keyboard_prompt_active(short port) int keyboard_prompt_enabled(short port) { - if (port < 0 || port >= 4) return 0; + if (port < 0 || port >= 4 || !config_boolean("display.high_res_hud")) return 0; if (!config_boolean("input.auto_button_detection")) return !strcmp(config_string("display.hud_button_style"), "keyboard"); - return config_boolean("display.keyboard_glyphs") && keyboard_prompt_active(port); + return keyboard_prompt_active(port); +} + +int keyboard_prompt_menu_enabled(int device) +{ + if (!config_boolean("display.high_res_hud")) return 0; + if (!config_boolean("input.auto_button_detection")) + return !strcmp(config_string("display.hud_button_style"), "keyboard"); + return device == -1; } diff --git a/port/linux/src/lighting_settings_migration.inl b/port/linux/src/lighting_settings_migration.inl new file mode 100644 index 0000000000..d6218ec4f2 --- /dev/null +++ b/port/linux/src/lighting_settings_migration.inl @@ -0,0 +1,95 @@ +/* One-time reset of saved optional lighting, before environment overrides. + * TOML source positions let us preserve comments, quoted/dotted keys and + * inline tables without rewriting unrelated preferences. */ +static const char *const lighting_reset_keys[] = { + "display.plasma_lighting", "display.muzzle_lighting", "display.plasma_occlusion", + "display.weapon_glow", "display.fuel_rod_lighting", "display.ammo_counter_lighting", + "display.needler_lighting", "display.plasma_prong_lighting", "display.vehicle_lighting", + "display.world_lighting", "display.jackal_shield_lighting", "display.covenant_shield_lighting", + "display.shield_glow", "display.shield_glow_intensity" +}; +#define LIGHTING_RESET_MARKER "display.dynamic_lighting_reset" +#define LIGHTING_RESET_COUNT (sizeof(lighting_reset_keys) / sizeof(lighting_reset_keys[0])) + +static int lighting_settings_legacy(toml_datum_t table) +{ + toml_datum_t marker = toml_seek(table, LIGHTING_RESET_MARKER); + return marker.type != TOML_BOOLEAN || !marker.u.boolean; +} + +static int lighting_settings_reset_key(const char *name) +{ + size_t i; + for (i = 0; i < LIGHTING_RESET_COUNT; i++) + if (!strcmp(name, lighting_reset_keys[i])) return 1; + return 0; +} + +static char *lighting_settings_migrate(const char *text, toml_datum_t table) +{ + struct lighting_edit { size_t offset, length; const char *value; } edits[LIGHTING_RESET_COUNT + 1], swap; + size_t i, j, count = 0, length = strlen(text), capacity = length + 256, cursor = 0, used = 0; + char *out; + if (!lighting_settings_legacy(table)) return NULL; + for (i = 0; i <= LIGHTING_RESET_COUNT; i++) + { + const char *key = i < LIGHTING_RESET_COUNT ? lighting_reset_keys[i] : LIGHTING_RESET_MARKER; + int intensity = !strcmp(key, "display.shield_glow_intensity"); + toml_datum_t datum = toml_seek(table, key); + const char *start = text, *end; + int line = 1; + if (datum.type == TOML_UNKNOWN) continue; + if (datum.lineno < 1 || datum.colno < 1) return NULL; + while (*start && line < datum.lineno) if (*start++ == '\n') line++; + if (line != datum.lineno || (size_t)(datum.colno - 1) > strcspn(start, "\n")) return NULL; + start += datum.colno - 1; + if (datum.type == TOML_BOOLEAN) + { + const char *old = datum.u.boolean ? "true" : "false"; + if (strncmp(start, old, strlen(old))) return NULL; + end = start + strlen(old); + } + else if (intensity && datum.type == TOML_STRING) + { + char quote; + int triple; + /* tomlc17 locates string content after its opening delimiter + * and the optional first newline of a multiline string. */ + if (start > text && start[-1] == '\n') + { start--; if (start > text && start[-1] == '\r') start--; } + if (start == text || (start[-1] != '"' && start[-1] != '\'')) return NULL; + quote = start[-1]; + triple = start - text >= 3 && start[-2] == quote && start[-3] == quote; + start -= triple ? 3 : 1; + end = start + (triple ? 3 : 1); + while (*end) + { + if (quote == '"' && *end == '\\') { if (!end[1]) return NULL; end += 2; continue; } + if (*end == quote && (!triple || (end[1] == quote && end[2] == quote))) break; + end++; + } + if (!*end) return NULL; + end += triple ? 3 : 1; + } + else return NULL; /* Invalid types remain diagnosable; never mark a partial reset complete. */ + edits[count].offset = (size_t)(start - text); + edits[count].length = (size_t)(end - start); + edits[count++].value = i == LIGHTING_RESET_COUNT ? "true" : intensity ? "\"default\"" : "false"; + } + for (i = 1; i < count; i++) + for (j = i; j && edits[j].offset < edits[j-1].offset; j--) + { swap = edits[j]; edits[j] = edits[j-1]; edits[j-1] = swap; } + out = malloc(capacity); + if (!out) return NULL; + for (i = 0; i < count; i++) + { + size_t prefix = edits[i].offset - cursor, value_length = strlen(edits[i].value); + if (edits[i].offset < cursor || edits[i].offset + edits[i].length > length) + { free(out); return NULL; } + memcpy(out + used, text + cursor, prefix); used += prefix; + memcpy(out + used, edits[i].value, value_length); used += value_length; + cursor = edits[i].offset + edits[i].length; + } + memcpy(out + used, text + cursor, length - cursor + 1); + return out; +} diff --git a/port/linux/src/menu_files.c b/port/linux/src/menu_files.c index 6b9ab58131..75e1699099 100644 --- a/port/linux/src/menu_files.c +++ b/port/linux/src/menu_files.c @@ -18,6 +18,7 @@ high-res HUD's are (hud_hires.c). */ #include "halo_menus.h" +#include "changelog_menu.h" #include "hud_hires.h" #include "menu_files.h" #include "platform.h" @@ -966,7 +967,9 @@ struct halo_menus const *halo_menus_load(void) { size_t length = strlen(files[index].path); - if (length > 4 && !strcmp(files[index].path + length - 4, ".xml")) + /* The optional frontend has a separate, ui.map-only parse. */ + if (strncmp(files[index].path, "modern/", 7) && + length > 4 && !strcmp(files[index].path + length - 4, ".xml")) read_file(&reader, &files[index]); } free(reader.last_child); @@ -983,10 +986,13 @@ struct halo_menus const *halo_menus_load(void) if (!reader.menus.root) reader.menus.root = "main_menu"; menus = reader.menus; + changelog_menu_configure(&menus, config_boolean("display.changelog")); succeeded = 1; return &menus; } +#include "frontend_menu_files.inl" + long halo_menus_utf16(char const *utf8, unsigned short *out, long capacity) { const unsigned char *in = (const unsigned char *)utf8; diff --git a/port/linux/src/nv2a_psh.c b/port/linux/src/nv2a_psh.c index 6b529122be..7ef70b5977 100644 --- a/port/linux/src/nv2a_psh.c +++ b/port/linux/src/nv2a_psh.c @@ -16,8 +16,10 @@ Register values are clamped to [-1, 1] between stages, as on the hardware. */ #include "xgpu.h" +#include "plasma_model_shader.h" #include "port_config.h" #include "mcc_environment_shader.h" +#include "shield_honeycomb_gl.h" #include #include @@ -574,10 +576,17 @@ world position the vertex program hands on and the same constants terms, clamped where the programs clamp them. The diffuse alpha, which the programs write apart (0, or planar fog's), is kept. */ -static void model_lighting(struct xgpu_text *text, BOOL point_lights) +static void model_lighting(struct xgpu_text *text, BOOL point_lights, BOOL plasma_model) { int light; +#ifndef HALO_ANDROID + if (point_lights && plasma_model) + plasma_model_emit_pixel(text); +#else + (void)plasma_model; +#endif + xgpu_text_append(text, "uniform vec4 model_lights[%d];\n" "in vec4 xWorldNormal;\n" @@ -604,18 +613,79 @@ static void model_lighting(struct xgpu_text *text, BOOL point_lights) "\t{\n" "\t\tvec3 to_light = model_lights[%d].xyz - xWorldPosition;\n" "\t\tfloat distance_squared = dot(to_light, to_light);\n" - "\t\tvec3 l = to_light * inversesqrt(max(distance_squared, 1.0e-12));\n" - "\t\tlight += max(1.0 - distance_squared * model_lights[%d].w, 0.0) * clamp(dot(l, n), 0.0, 1.0) *\n" + "\t\tvec3 l = to_light * inversesqrt(max(distance_squared, 1.0e-12));\n", first); +#ifndef HALO_ANDROID + if (plasma_model) + xgpu_text_append(text, + "\t\tlight += plasma_model_falloff(max(1.0 - distance_squared * model_lights[%d].w, 0.0), plasma_model_slots[%d],%d,xWorldPosition) * clamp(dot(l, n), 0.0, 1.0) *\n", + first, light, light); + else +#endif + xgpu_text_append(text, + "\t\tlight += max(1.0 - distance_squared * model_lights[%d].w, 0.0) * clamp(dot(l, n), 0.0, 1.0) *\n", first); + xgpu_text_append(text, "\t\t\tclamp(dot(l, -model_lights[%d].xyz) * model_lights[%d].w + model_lights[%d].w, 0.0, 1.0) *\n" "\t\t\tmodel_lights[%d].xyz;\n" "\t}\n", - first, first, first + 1, first + 1, first + 2, first + 2); + first + 1, first + 1, first + 2, first + 2); } xgpu_text_append(text, "\treturn clamp(light, 0.0, 1.0);\n}\n"); } +#ifndef HALO_GLES +static BOOL inputs_read_r0_alpha(DWORD inputs) +{ + int input; + for (input = 0; input < 4; input++, inputs >>= 8) + if ((inputs & 0x1f) == (_register_r0 | 0x10)) return TRUE; + return FALSE; +} + +/* Model draws can inherit an unused alpha combiner from preceding materials. + * Its source still costs a new driver link. Remove only alpha portions whose + * destinations are discard or r0.a, with no later read of r0.a. RGB writes, + * all other destinations, mux selectors and the implicit final r0 are retained. + * This is deliberately conservative; no general liveness analysis is needed. */ +static void discard_dead_r0_alpha(DWORD *state) +{ + unsigned count = state[D3DRS_PSCOMBINERCOUNT] & 0xff; + unsigned stage, later, destination; + DWORD final_abcd = state[D3DRS_PSFINALCOMBINERINPUTSABCD]; + DWORD final_efg = state[D3DRS_PSFINALCOMBINERINPUTSEFG]; + if (count > 8) count = 8; + for (stage = 0; stage < count; stage++) + { + DWORD outputs = state[D3DRS_PSALPHAOUTPUTS0 + stage]; + BOOL writes_r0 = FALSE, live = FALSE; + for (destination = 0; destination < 3; destination++) + { + unsigned reg = (outputs >> (destination * 4)) & 0xf; + if (reg == _register_r0) writes_r0 = TRUE; + else if (reg) live = TRUE; + } + if (writes_r0) + { + if ((!final_abcd && !final_efg) || inputs_read_r0_alpha(final_abcd) || + inputs_read_r0_alpha(final_efg & 0xffffff00UL)) live = TRUE; + for (later = stage + 1; later < count && !live; later++) + if (inputs_read_r0_alpha(state[D3DRS_PSRGBINPUTS0 + later]) || + inputs_read_r0_alpha(state[D3DRS_PSALPHAINPUTS0 + later]) || + ((state[D3DRS_PSRGBOUTPUTS0 + later] | state[D3DRS_PSALPHAOUTPUTS0 + later]) & 0x4000)) live = TRUE; + } + if (!live) + { + state[D3DRS_PSALPHAINPUTS0 + stage] = 0; + state[D3DRS_PSALPHAOUTPUTS0 + stage] = 0; + } + } +} +#endif + char *nv2a_pixel_shader_to_glsl(const struct nv2a_pixel_shader_key *key) { +#ifndef HALO_GLES + struct nv2a_pixel_shader_key normalized; +#endif const DWORD *state = key->combiner_state; struct xgpu_text text = { 0 }; unsigned long combiner_count = state[D3DRS_PSCOMBINERCOUNT] & 0xff; @@ -623,6 +693,15 @@ char *nv2a_pixel_shader_to_glsl(const struct nv2a_pixel_shader_key *key) DWORD final_efg = state[D3DRS_PSFINALCOMBINERINPUTSEFG]; int stage; +#ifndef HALO_GLES + normalized = *key; + /* A diagnostic expression may explicitly inspect an otherwise dead register. */ + if (!*config_string("debug.gpu_debug_expression")) + discard_dead_r0_alpha(normalized.combiner_state); + key = &normalized; + state = key->combiner_state; +#endif + if (combiner_count > 8) combiner_count = 8; @@ -650,12 +729,14 @@ char *nv2a_pixel_shader_to_glsl(const struct nv2a_pixel_shader_key *key) "in float xFog;\n" "layout(location = 0) out vec4 fragment_color;\n" XGPU_PIXEL_UNIFORMS); + if (key->shield_honeycomb) + xgpu_text_append(&text, "%s", shield_honeycomb_glsl); for (stage = 0; stage < 4; stage++) xgpu_text_append(&text, "uniform %s tex%d;\n", sampler_declaration(key->sampler_type[stage]), stage); if (key->source_blend) xgpu_text_append(&text, "uniform vec4 blend_constant;\n"); if (key->per_pixel_lighting) - model_lighting(&text, key->per_pixel_lighting == 2); + model_lighting(&text, key->per_pixel_lighting == 2, key->plasma_model); xgpu_text_append(&text, "float signed_byte(float x)\n" "{\n" @@ -742,6 +823,8 @@ char *nv2a_pixel_shader_to_glsl(const struct nv2a_pixel_shader_key *key) xgpu_text_append(&text, ";\n\tvec4 result = vec4(fA * fB + (1.0 - fA) * fC + fD, fG);\n"); } + if (key->shield_honeycomb) + xgpu_text_append(&text, "\tresult = shield_honeycomb_surface(result);\n"); if (key->coverage_alpha) xgpu_text_append(&text, "\tresult.a = mix(1.0, result.a, t0.g);\n"); if (key->alpha_test_function) diff --git a/port/linux/src/nv2a_vsh.c b/port/linux/src/nv2a_vsh.c index 905a977107..8550db53ac 100644 --- a/port/linux/src/nv2a_vsh.c +++ b/port/linux/src/nv2a_vsh.c @@ -18,6 +18,7 @@ clip-space position again. */ #include "xgpu.h" +#include "plasma_model_shader.h" #include #include @@ -358,6 +359,8 @@ static const char shader_prologue[] = "out vec4 xT2;\n" "out vec4 xT3;\n" "out float xFog;\n" + /* The shield surface uses the model UVs, without changing the original outputs. */ + "out vec2 shield_uv;\n" "invariant gl_Position;\n" "vec4 unpack_normpacked3(uint p)\n" "{\n" @@ -467,12 +470,18 @@ static void reversed_depth_instruction(struct xgpu_text *text, const DWORD *inst } char *nv2a_vertex_shader_to_glsl(const DWORD *instructions, unsigned long instruction_count, - unsigned long packed_attribute_mask, const struct nv2a_vertex_lighting *lighting) + unsigned long packed_attribute_mask, const struct nv2a_vertex_lighting *lighting, BOOL plasma_model) { struct xgpu_text text = { 0 }; unsigned long index; struct reversed_depth_rows rows; BOOL position_converted = FALSE, reversed_rows; +#ifndef HALO_ANDROID + struct nv2a_vertex_lighting plasma_lighting; + plasma_model = plasma_model && nv2a_vertex_shader_lighting(instructions, instruction_count, &plasma_lighting) && plasma_lighting.lights == 2; +#else + (void)plasma_model; +#endif rows.z_row = rows.w_row = -1; rows.other = FALSE; @@ -481,6 +490,10 @@ char *nv2a_vertex_shader_to_glsl(const DWORD *instructions, unsigned long instru xgpu_text_append(&text, "#version %s\n", xgpu_capabilities.shading_language); #endif xgpu_text_append(&text, "%s", shader_prologue); +#ifndef HALO_ANDROID + if (plasma_model) + plasma_model_emit_uniform(&text); +#endif /* (the pixel shader's model_lighting; the normal's length in w) */ if (lighting) xgpu_text_append(&text, "out vec4 xWorldNormal;\n"); @@ -546,6 +559,11 @@ char *nv2a_vertex_shader_to_glsl(const DWORD *instructions, unsigned long instru xgpu_text_append(&text, "\tB = "); operand(&text, instruction, 'B', relative); xgpu_text_append(&text, ";\n"); xgpu_text_append(&text, "\tC = "); operand(&text, instruction, 'C', relative); xgpu_text_append(&text, ";\n"); +#ifndef HALO_ANDROID + if (plasma_model) + plasma_model_emit_vertex(&text, instruction, index, &plasma_lighting); +#endif + switch (mac) { case _mac_nop: break; @@ -709,6 +727,7 @@ char *nv2a_vertex_shader_to_glsl(const DWORD *instructions, unsigned long instru "\txD1 = clamp(oD1, 0.0, 1.0);\n" "\txB0 = clamp(oB0, 0.0, 1.0);\n" "\txB1 = clamp(oB1, 0.0, 1.0);\n" + "\tshield_uv = v4.xy;\n" "\txT0 = oT0;\n" "\txT1 = oT1;\n" "\txT2 = oT2;\n" @@ -748,6 +767,7 @@ char *nv2a_fixed_function_glsl(void) "\txD1 = clamp(v4_in, 0.0, 1.0);\n" "\txB0 = vec4(0.0, 0.0, 0.0, 1.0);\n" "\txB1 = vec4(0.0, 0.0, 0.0, 1.0);\n" + "\tshield_uv = vec2(0.0);\n" "\txT0 = v9_in;\n" "\txT1 = v10_in;\n" "\txT2 = v11_in;\n" @@ -755,6 +775,6 @@ char *nv2a_fixed_function_glsl(void) "\txFog = 1.0;\n" "}\n", /* (display.reversed_depth) */ - xgpu_reversed_depth ? "\tgl_Position.z = gl_Position.w - gl_Position.z;\n" : ""); + xgpu_reversed_depth ? "\tgl_Position.z = gl_Position.w - gl_Position.z + depth_bias * gl_Position.w;\n" : ""); return text.buffer; } diff --git a/port/linux/src/plasma_model_shader.c b/port/linux/src/plasma_model_shader.c new file mode 100644 index 0000000000..193e57ada4 --- /dev/null +++ b/port/linux/src/plasma_model_shader.c @@ -0,0 +1,51 @@ +/* The selected point light gets (1 - d*d/r*r)^2. All other contributions + and the stock shader's alpha, cone and material terms are retained. */ +#include "xgpu.h" +#include "plasma_model_shader.h" + +void plasma_model_emit_uniform(struct xgpu_text *text) +{ + xgpu_text_append(text, "uniform vec2 plasma_model_slots;\n" + "uniform vec2 plasma_occ_enabled;\n" + "uniform sampler3D plasma_occ_texture0;\n" + "uniform sampler3D plasma_occ_texture1;\n" + "uniform vec4 plasma_occ_transform0;\n" + "uniform vec4 plasma_occ_transform1;\n" + "float plasma_visibility(int slot, vec3 position) {\n" + " if (plasma_occ_enabled[slot] < 0.5) return 1.0;\n" + " vec4 tr = slot == 0 ? plasma_occ_transform0 : plasma_occ_transform1;\n" + " vec3 uv = (position-tr.xyz)*tr.w+vec3(0.5);\n" + " if (any(lessThan(uv,vec3(0.0))) || any(greaterThan(uv,vec3(1.0)))) return 1.0;\n" + " return slot == 0 ? textureLod(plasma_occ_texture0,uv,0.0).r : textureLod(plasma_occ_texture1,uv,0.0).r;\n}\n"); +} + +void plasma_model_emit_vertex(struct xgpu_text *text, const unsigned long *instruction, + unsigned long index, const struct nv2a_vertex_lighting *lighting) +{ + unsigned long constant = (instruction[1] >> 13) & 255; + int slot; + if (index == lighting->position_instruction) + xgpu_text_append(text, "\tvec3 plasma_model_position = r%lu.xyz;\n", lighting->position_register); + /* Only the color multiply-add of a recognized two-point-light model + program: B is the unswizzled, positive color constant. The ILU reads C, + so changing B.xyz cannot affect the parallel scalar instruction. */ + if (((instruction[1] >> 21) & 15) != 4 || (instruction[3] & 2) || + ((instruction[2] >> 11) & 3) != 3 || ((instruction[2] >> 25) & 1) || + ((instruction[2] >> 19) & 63) != 6 || index <= lighting->position_instruction) + return; + for (slot = 0; slot < 2; slot++) + if (constant == (unsigned long)(XGPU_VERTEX_CONSTANT_BIAS - 77 + slot * 3)) + xgpu_text_append(text, + "\tif (plasma_model_slots[%d] > 0.5) {\n" + "\t\tvec3 delta = c[%d].xyz - plasma_model_position;\n" + "\t\tB.xyz *= max(1.0 - dot(delta, delta) * c[%d].w, 0.0) * plasma_visibility(%d,plasma_model_position);\n\t}\n", + slot, XGPU_VERTEX_CONSTANT_BIAS - 79 + slot * 3, XGPU_VERTEX_CONSTANT_BIAS - 79 + slot * 3, slot); +} + +void plasma_model_emit_pixel(struct xgpu_text *text) +{ + plasma_model_emit_uniform(text); + xgpu_text_append(text, + "float plasma_model_falloff(float attenuation, float selected, int slot, vec3 position) {\n" + "\treturn selected > 0.5 ? attenuation * attenuation * plasma_visibility(slot,position) : attenuation;\n}\n"); +} diff --git a/port/linux/src/plasma_occlusion_gl.c b/port/linux/src/plasma_occlusion_gl.c new file mode 100644 index 0000000000..cbbcfcc924 --- /dev/null +++ b/port/linux/src/plasma_occlusion_gl.c @@ -0,0 +1,167 @@ +/* Additional model samplers use units 6/7; the game's four texture stages + and their cached bindings are not changed. */ +#include "plasma_occlusion.h" +#include "xgpu.h" +#include +#include + +static int model_bindings_known; + +void plasma_occlusion_model_initialize(unsigned long program, struct plasma_occlusion_uniforms *uniforms) +{ + int slot; + char name[40]; + uniforms->known = 0; + uniforms->enabled = glGetUniformLocation(program, "plasma_occ_enabled"); + if (uniforms->enabled < 0) return; + for (slot = 0; slot < 2; slot++) + { + snprintf(name, sizeof(name), "plasma_occ_transform%d", slot); + uniforms->transform[slot] = glGetUniformLocation(program, name); + snprintf(name, sizeof(name), "plasma_occ_texture%d", slot); + glUniform1i(glGetUniformLocation(program, name), 6 + slot); + } +} + +/* Each model mask is immutable for its view. Resolve/decode/upload a resource + once, rather than asking the texture cache again for every material draw. + Discard the table at every view boundary, including map reset. */ +static GLuint model_texture_get(DWORD const *resource) +{ + static struct { DWORD const *resource; GLuint texture; } resolved[16]; + static unsigned long view; + static int count; + unsigned long current = plasma_occlusion_view_serial(); + GLuint texture; + GLint active; + GLenum target; + struct xgpu_texture_description description; + int i; + if (view != current) { view = current; count = 0; model_bindings_known = 0; } + for (i = 0; i < count; i++) + if (resolved[i].resource == resource) return resolved[i].texture; + /* A cache miss can upload and bind a texture. Confine that side effect + to our units; ordinary material draws need no active-unit query. */ + glGetIntegerv(GL_ACTIVE_TEXTURE, &active); + glActiveTexture(GL_TEXTURE0 + 6); + texture = xgpu_texture_get(resource, NULL, &target, &description); + glActiveTexture(active); + model_bindings_known = 0; + if (texture && count < 16) + { + resolved[count].resource = resource; + resolved[count++].texture = texture; + } + return texture; +} + +static void model_bind_textures(const GLuint textures[2], GLuint sampler) +{ + static GLuint bound[2], bound_sampler; + static unsigned long view; + unsigned long current = plasma_occlusion_view_serial(); + GLint active; + int slot; + if (view != current) { view = current; model_bindings_known = 0; } + if (sampler && model_bindings_known && bound_sampler == sampler && + !memcmp(bound, textures, sizeof(bound))) return; + /* Only this module owns units 6/7. Reset at every view (including map + cleanup), and after any resource upload that may change their bindings. + Desktop multi-bind leaves the active unit and stock stages untouched. */ +#ifndef HALO_GLES + if (sampler) + { + glBindTextures(6, 2, textures); + if (!model_bindings_known || bound_sampler != sampler) + for (slot = 0; slot < 2; slot++) glBindSampler(6 + slot, sampler); + } + else +#endif + { + glGetIntegerv(GL_ACTIVE_TEXTURE, &active); + for (slot = 0; slot < 2; slot++) + { + glActiveTexture(GL_TEXTURE0 + 6 + slot); + glBindTexture(GL_TEXTURE_3D, textures[slot]); + glBindSampler(6 + slot, sampler); + if (!sampler) + { + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); + } + } + glActiveTexture(active); + } + memcpy(bound, textures, sizeof(bound)); + bound_sampler = sampler; + model_bindings_known = 1; +} + +void plasma_occlusion_bind_model(struct plasma_occlusion_uniforms *uniforms) +{ + GLint active; + GLuint texture, textures[2]; + DWORD const *resource; + int slot; + float transform[4], enabled[2] = {0, 0}; + /* Like the fallback texture, this immutable sampler belongs to the GL + context, not a map or light. It never touches the game's four stages. */ + static GLuint white, sampler; + if (uniforms->enabled < 0) + return; + if (!sampler) + { + glGenSamplers(1, &sampler); + if (sampler) + { + glSamplerParameteri(sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glSamplerParameteri(sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glSamplerParameteri(sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glSamplerParameteri(sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glSamplerParameteri(sampler, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); + } + } + for (slot = 0; slot < 2; slot++) + { + resource = plasma_occlusion_model_texture(slot, transform); + texture = 0; + if (resource) + texture = model_texture_get(resource); + if (texture) + { + enabled[slot] = 1; + if (!(uniforms->known & (1 << slot)) || memcmp(uniforms->last_transform[slot], transform, sizeof(transform))) + { + glUniform4fv(uniforms->transform[slot], 1, transform); + memcpy(uniforms->last_transform[slot], transform, sizeof(transform)); + uniforms->known |= 1 << slot; + } + } + else + { + if (!white) + { + unsigned char pixel[4] = {255, 255, 255, 255}; + glGetIntegerv(GL_ACTIVE_TEXTURE, &active); + glActiveTexture(GL_TEXTURE0 + 6); + glGenTextures(1, &white); + glBindTexture(GL_TEXTURE_3D, white); + glTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA8, 1, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixel); + glActiveTexture(active); + model_bindings_known = 0; + } + texture = white; + } + textures[slot] = texture; + } + model_bind_textures(textures, sampler); + if (!(uniforms->known & 4) || memcmp(uniforms->last_enabled, enabled, sizeof(enabled))) + { + glUniform2f(uniforms->enabled, enabled[0], enabled[1]); + memcpy(uniforms->last_enabled, enabled, sizeof(enabled)); + uniforms->known |= 4; + } +} diff --git a/port/linux/src/port_config.c b/port/linux/src/port_config.c index b9fed32457..b65e8ae129 100644 --- a/port/linux/src/port_config.c +++ b/port/linux/src/port_config.c @@ -159,6 +159,19 @@ static const struct config_setting config_settings[] = "In first person, point the view where the player aims now instead of\n" "where the last tick left it: the view turns the frame the mouse moves,\n" "not up to two ticks (66 ms) later." }, + { "display.third_person_smooth", _config_boolean, "true", "HALO_THIRD_PERSON_SMOOTH", _environment_value, _platform_all, + "Smooth camera recovery and shoulder changes; false uses sharp movement." }, + { "display.third_person_left_shoulder", _config_boolean, "false", "HALO_THIRD_PERSON_LEFT_SHOULDER", _environment_value, _platform_all, + "Use the left shoulder. Swap shoulders with B (controls.swap_shoulder)." }, + { "display.third_person_distance", _config_real, "0.85", "HALO_THIRD_PERSON_DISTANCE", _environment_value, _platform_all, + "Shoulder camera distance behind the eye, in world units (0.3 to 2.0)." }, + { "display.third_person_height", _config_real, "0.12", "HALO_THIRD_PERSON_HEIGHT", _environment_value, _platform_all, + "Shoulder camera height along camera up, in world units (-0.2 to 0.6)." }, + { "display.third_person_offset", _config_real, "0.24", "HALO_THIRD_PERSON_OFFSET", _environment_value, _platform_all, + "Shoulder camera lateral offset, in world units (0.0 to 0.6)." }, + { "display.third_person", _config_boolean, "false", "HALO_THIRD_PERSON", _environment_value, _platform_all, + "On foot, use a right-shoulder camera. Zoom returns to first person.\n" + "The reticle follows the stock aim point; weapon behaviour is unchanged." }, { "display.fov", _config_real, "0.0", "HALO_FOV", _environment_value, _platform_all, "The first-person view's field of view on foot, in degrees across at\n" "16:9 (20 to 150); 0 keeps the stock view. Vehicles, cinematics and\n" @@ -172,6 +185,21 @@ static const struct config_setting config_settings[] = "Off, they are not drawn; firing, animation, sound and lights go on." }, { "display.passenger_third_person", _config_boolean, "false", "HALO_PASSENGER_THIRD_PERSON", _environment_value, _platform_all, "Third-person Warthog and Scorpion passengers. Weapon zoom is disabled." }, + { "display.shield_look", _config_string, "\"classic\"", "HALO_SHIELD_LOOK", _environment_value, _platform_all, + "Shield appearance (saved values retain their existing profiles):\n" + "\"classic\" (DEFAULT) keeps the map's own look.\n" + "\"classic_with_sprinkles\" (CLASSIC WITH SPRINKLES) adds layers, arcs\n" + "and recharge to the classic surface. \"classic_honeycomb2\"\n" + "(INFINITE HONEYCOMB) lights hexagonal links with flowing classic plasma.\n" + "\"enhanced\" (MARK VI) uses CMT body and first-person shields.\n" + "Non-default looks preserve custom map colour.\n" + "Arm Shields controls all arms. Local drawing only; independent of mods." }, + { "display.viewmodel_shield", _config_boolean, "false", "HALO_VIEWMODEL_SHIELD", _environment_value, _platform_all, + "The energy shield's flare on the first-person arms too, as on the body\n" + "(the stock game draws it on the body only)." }, + { "display.first_person_legs", _config_boolean, "false", "HALO_FIRST_PERSON_LEGS", _environment_value, _platform_all, + "Your own legs in first person, seen looking down: your body as others\n" + "see it, drawn from the waist down, moving as it moves." }, { "display.high_res_hud", _config_boolean, "true", "HALO_HIGH_RES_HUD", _environment_value, _platform_all, "Draw the HUD (meters, counters, panels, motion sensor, reticles,\n" "waypoints, scopes) from the high-res assets (8x the maps' bitmaps);\n" @@ -180,24 +208,22 @@ static const struct config_setting config_settings[] = "Manual high-res gameplay button style, preserved while automatic detection\n" "is on. Xbox: classic, gems, menu_gems (dark gems), xbox_modern.\n" "PlayStation: ps_classic, ps_gems, ps_dark_gems, ps_modern.\n" - "Switch: switch_classic, switch_gems, switch_modern. Controllers require high_res_hud.\n" - "keyboard selects binding-aware gameplay keycaps independently of high_res_hud." }, - { "display.menu_button_glyphs", _config_boolean, "false", "HALO_MENU_BUTTON_GLYPHS", _environment_value, _platform_all, - "Use the selected keyboard/controller style in PC-menu face-button legends." }, - { "display.keyboard_glyphs", _config_boolean, "false", "HALO_KEYBOARD_GLYPHS", _environment_value, _platform_all, - "With auto button detection on, show binding-aware gameplay keycaps after\n" - "keyboard/mouse activity. Off preserves existing prompts. Manual keyboard\n" - "style works with detection off. Menu legends require menu_button_glyphs." }, + "Switch: switch_classic, switch_gems, switch_modern. Glyphs require high_res_hud.\n" + "keyboard selects binding-aware keyboard/mouse glyphs within the same requirement." }, { "display.hud_bumper_style", _config_string, "\"original\"", "HALO_HUD_BUMPER_STYLE", _environment_value, _platform_all, "Xbox Classic, Gems and Dark Gems bumpers: original (black/white) or modern\n" "(LB/RB). Shared by local players, including automatic button detection.\n" "Requires high_res_hud; other button styles keep their own artwork." }, + { "display.menu_button_glyphs", _config_boolean, "false", "HALO_MENU_BUTTON_GLYPHS", _environment_value, _platform_all, + "Use the selected keyboard or controller artwork in stock PC menus and pause legends.\n" + "Requires high_res_hud. Modern prompts are separate; Xbox menus are unchanged." }, { "input.auto_button_detection", _config_boolean, "true", "HALO_AUTO_BUTTON_DETECTION", _environment_value, _platform_all, - "Limit Button Style to the assigned controller's family. Unknown devices\n" - "keep the manual choice. Device detection itself is always available." }, + "Follow active keyboard/mouse or controller input for button prompts.\n" + "Controllers use their family's saved artwork; unknown controllers keep\n" + "the manual choice. Off uses the manual style. Device detection always runs." }, { "input.controller_p1", _config_string, "\"\"", "HALO_CONTROLLER_P1", _environment_value, _platform_all, "P1 custom controller layout; empty uses the profile. Edit in Gamepads >\n" - "Button Remapping. v3: stores 26 physical-button names, including unbound.\n" + "Button Remapping. v4: stores 28 physical-button names, including unbound.\n" "Gameplay and debug camera have separate bindings. Old ten-action and v2 layouts\n" "are accepted. See docs/reading/controller_remapping.md for the full order." }, { "input.controller_p2", _config_string, "\"\"", "HALO_CONTROLLER_P2", _environment_value, _platform_all, @@ -218,7 +244,7 @@ static const struct config_setting config_settings[] = "from port/assets/titles; false draws the maps' bitmap fonts and titles." }, { "display.widescreen_loading", _config_boolean, "true", "HALO_WIDESCREEN_LOADING", _environment_value, _platform_all, "Widen the stock loading screen, keeping its original picture, sweep\n" - "and glow trails. False keeps the central 4:3 framing." }, + "and glow trails, including MCC. False keeps the central 4:3 framing." }, { "display.shadow_resolution", _config_integer, "128", "HALO_SHADOW_RESOLUTION", _environment_value, _platform_all, "The size the objects' shadows are drawn at, in pixels each way: 128 as\n" @@ -226,6 +252,14 @@ static const struct config_setting config_settings[] = { "display.menus", _config_string, "\"pc\"", "HALO_MENUS", _environment_value, _platform_all, "The menus: \"pc\" for the PC version's main menu (port/assets/menus,\n" "and a menus folder here for your own), \"xbox\" for the Xbox's." }, + { "display.changelog", _config_boolean, "true", "HALO_CHANGELOG", _environment_value, _platform_all, + "Show CHANGELOG beneath the build labels in the PC main menu.\n" + "Restart the game after changing this setting." }, + { "display.menu_frontend", _config_string, "\"modern\"", "HALO_MENU_FRONTEND", _environment_value, _platform_all, + "Optional submenu frontend: \"off\" keeps display.menus, or choose\n" + "\"modern\", \"pc\" or \"xbox\". Change it in Interface or Video Setup > Graphics.\n" + "Settings use the selected style in gameplay too. Changes made while\n" + "playing take effect on return to the main menu. Pause roots stay native." }, { "display.menu_language", _config_string, "\"maps\"", "HALO_MENU_LANGUAGE", _environment_value, _platform_all, "The PC menus' language: \"maps\" for the language of the Custom Edition\n" "whose loc.map is in custom_maps (as that edition shows them; English\n" @@ -274,10 +308,18 @@ static const struct config_setting config_settings[] = "Keep the GPU programs the game links under the save root (shader_cache),\n" "and load them from there next time instead of linking them again, which\n" "stalls a frame on some drivers; false links each every run." }, + { "display.shader_prepare", _config_boolean, "false", "HALO_SHADER_PREPARE", _environment_value, _platform_desktop, + "Prepare observed shader pairs and bounded opaque/transparent material\n" + "variants while loading. Uses recipe files in shader_cache and can\n" + "extend loading. Effects outside this pass still prepare on first use." }, { "display.mcc_texture_prepare_mb", _config_integer, "0", "HALO_MCC_TEXTURE_PREPARE_MB", _environment_value, _platform_desktop, "MCC only: prepare large non-paletted textures during loading, within\n" "this estimated GPU memory budget in MiB (0 disables, maximum 512).\n" "Does not change texture quality or the Xbox/Custom Edition caches." }, + { "display.texture_prepare_mb", _config_integer, "0", "HALO_TEXTURE_PREPARE_MB", _environment_value, _platform_desktop, + "Xbox/Custom Edition: prepare non-paletted textures while loading.\n" + "Budget in MiB (0 disables, maximum 128), conservatively accounting\n" + "for both guest and GPU storage. MCC uses its own preparation budget." }, { "display.stats_log", _config_boolean, "false", "HALO_STATS_LOG", _environment_value, _platform_all, "A line a second in the log with the frame rate, the mode, the map, the\n" "renderer and the size of the 3D view, so a graphics bug's report or two\n" @@ -303,10 +345,10 @@ static const struct config_setting config_settings[] = "resolutions; \"highest\" draws the models \"native\" does, each at its most\n" "detailed level." }, { "display.reversed_depth", _config_boolean, "true", "HALO_REVERSED_DEPTH", _environment_value, _platform_desktop, - "Keep depth in 32-bit floats, reversed (1 near, 0 far), as precise far\n" - "away as near: surfaces a few millimetres apart (the lights on Blood\n" - "Gulch's base) stay apart at any distance in place of flickering\n" - "through each other. false: 24 bits, as the Xbox's. Taken up when the\n" + "Keep depth in 32-bit floats, reversed (1 near, 0 far), improving\n" + "precision at a distance. This reduces flickering between closely\n" + "spaced surfaces, such as the lights on Blood Gulch's base.\n" + "false: 24 bits, as the Xbox's. Taken up when the\n" "game starts." }, { "display.hdr", _config_boolean, "false", "HALO_HDR", _environment_value, _platform_all, "Draw the 3D view into a floating-point back buffer, which keeps what\n" @@ -399,6 +441,22 @@ static const struct config_setting config_settings[] = "The touch controls' swipe aiming gets a controller's aim assist: the\n" "aim slows over a target and follows a moving one. false: none, as a\n" "mouse (the bullets' own autoaim stays)." }, + { "input.gyro_aim", _config_string, "\"legacy\"", "HALO_GYRO_AIM", _environment_value, _platform_android, + "Android gyro: \"legacy\" keeps the touch layout's saved gyro switch\n" + "and look sensitivity (off in a new layout). \"false\" disables it,\n" + "\"true\" enables it, \"zoom\" enables it only while zoomed. The last\n" + "two use the independent gyro sensitivity and inversion below." }, + { "input.gyro_sensitivity_horizontal", _config_real, "1.0", "HALO_GYRO_SENSITIVITY_HORIZONTAL", + _environment_value, _platform_android, + "Android gyro horizontal sensitivity in true/zoom mode: 0.25 to 10.\n" + "1 follows the sensor's turn; independent of swipe sensitivity." }, + { "input.gyro_sensitivity_vertical", _config_real, "1.0", "HALO_GYRO_SENSITIVITY_VERTICAL", + _environment_value, _platform_android, + "Android gyro vertical sensitivity in true/zoom mode: 0.25 to 10." }, + { "input.gyro_invert_horizontal", _config_boolean, "false", "HALO_GYRO_INVERT_HORIZONTAL", + _environment_value, _platform_android, "Invert Android gyro yaw in true/zoom mode." }, + { "input.gyro_invert_vertical", _config_boolean, "false", "HALO_GYRO_INVERT_VERTICAL", + _environment_value, _platform_android, "Invert Android gyro pitch in true/zoom mode." }, { "input.mouse_sensitivity", _config_real, "1.0", "HALO_MOUSE_SENSITIVITY", _environment_value, _platform_desktop, "How far the view turns for the mouse's movement." }, { "input.playstation_kernel_driver", _config_boolean, "false", "HALO_PLAYSTATION_KERNEL_DRIVER", @@ -407,6 +465,23 @@ static const struct config_setting config_settings[] = "kernel's driver of it (hid-playstation, hid-sony), which needs no setup;\n" "false: through SDL's own, which needs Steam's udev rules to open it. Read\n" "at start-up." }, + { "input.adaptive_triggers", _config_boolean, "false", "HALO_ADAPTIVE_TRIGGERS", _environment_value, + _platform_desktop, + "A PS5 DualSense's adaptive triggers (dualsense.c): the trigger mapped\n" + "to fire feels like the weapon; grenade/zoom effects follow their\n" + "trigger. Only L2/R2 have actuators. Free while paused, in menus,\n" + "reloading or switching. Other controllers are never touched. On\n" + "Linux with input.playstation_kernel_driver it needs write access to the\n" + "controller's hidraw device (Steam's udev rules)." }, + { "input.trigger_strength", _config_string, "\"normal\"", "HALO_TRIGGER_STRENGTH", _environment_value, + _platform_desktop, + "How strong a DualSense's trigger effects are: \"light\" (a hair\n" + "trigger: every hold or click a short light break at the top of the\n" + "pull), \"normal\", \"strong\" (every effect two steps firmer)." }, + { "input.lightbar", _config_string, "\"off\"", "HALO_LIGHTBAR", _environment_value, _platform_desktop, + "A PS5 DualSense's lightbar and player lights: \"player_color\", the\n" + "lightbar in your color (your team's in a team game) and the player\n" + "lights your split-screen number. \"off\": left alone." }, { "input.invert_mouse", _config_boolean, "false", "HALO_MOUSE_INVERT", _environment_set_is_true, _platform_desktop, "Moving the mouse forward looks down." }, { "network.block_mouse_aim_assist", _config_boolean, "false", "HALO_NET_BLOCK_MOUSE_AIM_ASSIST", _environment_value, @@ -488,8 +563,21 @@ static const struct config_setting config_settings[] = "Showing the scores (the controller's Back)." }, { "controls.pause", _config_string, "\"Escape\"", "HALO_KEY_PAUSE", _environment_value, _platform_all, "The pause menu (the controller's Start)." }, + { "controls.free_look", _config_string, "\"Left Alt\"", "HALO_KEY_FREE_LOOK", _environment_value, _platform_all, + "Hold to orbit the third-person camera without changing aim." }, + { "controls.toggle_perspective", _config_string, "\"N\"", "HALO_KEY_TOGGLE_PERSPECTIVE", _environment_value, _platform_all, + "Toggle first-person and third-person view during play." }, + { "controls.swap_shoulder", _config_string, "\"B\"", "HALO_KEY_SWAP_SHOULDER", _environment_value, _platform_all, + "Swap third-person shoulders. Up to two keyboard or mouse bindings." }, { "controls.screenshot", _config_string, "\"F10\"", "HALO_KEY_SCREENSHOT", _environment_value, _platform_all, "Save a PNG screenshot beside maps/ (press once per capture)." }, + { "controls.camera_distance", _config_string, "\"Left Alt\"", "HALO_KEY_CAMERA_DISTANCE", _environment_value, _platform_all, + "Hold with the mouse wheel to adjust shoulder distance; ordinary scrolling switches weapons." }, + { "controls.camera_height", _config_string, "\"Left Shift, Right Shift\"", "HALO_KEY_CAMERA_HEIGHT", _environment_value, _platform_all, + "Hold with the mouse wheel to raise or lower the shoulder camera." }, + { "controls.camera_offset", _config_string, "\"CapsLock\"", "HALO_KEY_CAMERA_OFFSET", _environment_value, _platform_all, + "Hold with the mouse wheel to move the camera left or right, across either shoulder.\n" + "Caps Lock is a held key, not its typing-toggle state. Wheel up moves right." }, { "controls.push_to_talk", _config_string, "\"V\"", "HALO_KEY_PUSH_TO_TALK", _environment_value, _platform_all, "Voice chat: talk while it is held (audio.voice_chat \"push_to_talk\")." }, { "controls.chat", _config_string, "\"T\"", "HALO_KEY_CHAT", _environment_value, _platform_all, @@ -535,10 +623,32 @@ static const struct config_setting config_settings[] = "as CUSTOM SINGLEPLAYER and CUSTOM MULTIPLAYER. Their tags are checked\n" "as the game's own maps' are before they run; false refuses them\n" "(docs/custom_edition_caches.md)." }, + { "android.cheat_menu", _config_boolean, "false", "HALO_ANDROID_CHEAT_MENU", _environment_value, _platform_android, + "Show a CHEATS touch button and Options entry during offline or hosted games.\n" + "Off by default; joining clients cannot use it.\n" + "Menu-owned switches reset on disabling the menu or leaving a map." }, + { "bots.enhanced", _config_boolean, "false", "HALO_BOTS_ENHANCED", _environment_value, _platform_all, + "Optional enhanced bots: tactical roles, navigation and CTF/King goals.\n" + "Read at map load. False keeps the inherited Slayer bot behavior." }, + { "bots.network", _config_boolean, "false", "HALO_BOTS_NETWORK", _environment_value, _platform_all, + "Allow host-controlled bots in multiplayer network games. Read when\n" + "creating a host or pressing OK in the lobby's Bots settings. Enabling\n" + "reserves 63 free machine IDs until the host closes, even if disabled\n" + "again. Clients use ordinary player replication. False by default." }, + { "bots.routes", _config_string, "\"direct\"", "HALO_BOT_ROUTES", _environment_value, _platform_all, + "Enhanced bots' routes: \"direct\", \"lanes\" or \"mixed\". Direct takes\n" + "the shortest route; lanes spreads attackers across side routes." }, + { "bots.vehicles", _config_boolean, "false", "HALO_BOT_VEHICLES", _environment_value, _platform_all, + "Let enhanced bots enter, drive and use vehicles and turrets." }, + { "bots.thread", _config_boolean, "false", "HALO_BOT_THREAD", _environment_value, _platform_all, + "Run enhanced bots' path searches on a snapshot worker. Read at map\n" + "load; off by default. Fixed-tick benchmarks always search synchronously." }, { "bots.count", _config_integer, "0", "HALO_BOTS", _environment_value, _platform_all, - "Computer players (bots) in a local (split screen) Slayer game: 0 to 15\n" - "join its lobby with the players, as far as the game has room. Not in\n" - "system link or internet games. 0: none, as in the stock game." }, + "Computer players (bots): 0 to 63. Local Slayer by default; bots.enhanced\n" + "also allows CTF/King, and bots.network enables host-controlled network\n" + "bots. Network humans replace bots, which return when humans leave.\n" + "The initial humans plus this count set the session population target.\n" + "0: no initial bots, as in the stock game." }, { "bots.skill", _config_string, "\"normal\"", "HALO_BOT_SKILL", _environment_value, _platform_all, "How well the bots play: \"recruit\", \"easy\", \"normal\", \"heroic\",\n" "\"veteran\" or \"legendary\" (how soon they react, how well they aim,\n" @@ -546,35 +656,60 @@ static const struct config_setting config_settings[] = { "bots.teams", _config_string, "\"even\"", "HALO_BOT_TEAMS", _environment_value, _platform_all, "In team games: \"even\" puts the bots on both teams, evening them with\n" "the players; \"against\" puts them all on the team the players are not on." }, - { "display.viewmodel_shield", _config_boolean, "false", "HALO_VIEWMODEL_SHIELD", _environment_value, _platform_all, - "The energy shield's flare on the first-person arms too, as on the body\n" - "(the stock game draws it on the body only)." }, - { "display.first_person_legs", _config_boolean, "false", "HALO_FIRST_PERSON_LEGS", _environment_value, _platform_all, - "Your own legs in first person, seen looking down: your body as others\n" - "see it, drawn from the waist down, moving as it moves." }, + { "display.dynamic_lighting_reset", _config_boolean, "true", "HALO_DYNAMIC_LIGHTING_RESET", _environment_value, _platform_all, + "Migration marker: old saved dynamic-lighting preferences were reset to off.\n" + "Leave true to retain lighting choices made after that one-time reset." }, + { "display.plasma_occlusion", _config_boolean, "false", "HALO_PLASMA_OCCLUSION", _environment_value, _platform_desktop, + "Collision-filtered projectile, Covenant emitter and Shield Glow visibility.\n" + "Off preserves unoccluded plasma lighting. At most eight occluded lights." }, + { "display.jackal_shield_lighting", _config_boolean, "false", "HALO_JACKAL_SHIELD_LIGHTING", _environment_value, _platform_desktop, + "Soft illumination from visible Jackal shields, following their colour and pose.\n" + "Stock shield effects remain intact. Optional occlusion uses plasma_occlusion." }, + { "display.weapon_glow", _config_boolean, "false", "HALO_WEAPON_GLOW", _environment_value, _platform_desktop, + "Held energy weapons cast soft light. Disabled by default." }, + { "display.plasma_prong_lighting", _config_boolean, "false", "HALO_PLASMA_PRONG_LIGHTING", _environment_value, _platform_desktop, + "Short, soft forward spill from plasma-weapon prongs. Separate from Weapon Glow.\n" + "Off by default; uses the shared eight-light occlusion budget when enabled." }, + { "display.vehicle_lighting", _config_boolean, "false", "HALO_VEHICLE_LIGHTING", _environment_value, _platform_desktop, + "Vehicle engines and headlights illuminate nearby surfaces. Disabled by default." }, + { "display.world_lighting", _config_boolean, "false", "HALO_WORLD_LIGHTING", _environment_value, _platform_desktop, + "Visible powerups and teleporters cast soft light. Disabled by default." }, + { "display.needler_lighting", _config_boolean, "false", "HALO_NEEDLER_LIGHTING", _environment_value, _platform_desktop, + "Soft pink-purple spill and luminous crystals on held Needlers." }, + { "display.ammo_counter_lighting", _config_boolean, "false", "HALO_AMMO_COUNTER_LIGHTING", _environment_value, _platform_desktop, + "Blue spill and screen emission from held Assault Rifle ammo counters (off by default)." }, + { "display.fuel_rod_lighting", _config_boolean, "false", "HALO_FUEL_ROD_LIGHTING", _environment_value, _platform_desktop, + "Soft green illumination from exposed Grunt and Hunter fuel rods.\n" + "Stock weapon effects remain intact. Optional occlusion uses plasma_occlusion." }, + { "display.covenant_shield_lighting", _config_boolean, "false", "HALO_COVENANT_SHIELD_LIGHTING", _environment_value, _platform_desktop, + "Soft illumination from active stationary Covenant shield emitters.\n" + "Stock shield effects remain intact. Optional occlusion uses plasma_occlusion." }, + { "display.muzzle_lighting", _config_boolean, "false", "HALO_MUZZLE_LIGHTING", _environment_value, _platform_desktop, + "Optional soft muzzle illumination with a smooth render-time fade.\n" + "Stock flash effects remain intact. Off keeps stock lighting." }, + { "display.plasma_lighting", _config_boolean, "false", "HALO_PLASMA_LIGHTING", _environment_value, _platform_desktop, + "Supported plasma, Covenant and rocket flight lights follow rendered poses\n" + "with soft world/model falloff and omni highlights. Off keeps stock lighting." }, { "display.overshield_effect", _config_boolean, "false", "HALO_OVERSHIELD_EFFECT", _environment_value, _platform_all, "The overshield as this machine draws it: its flare rising up the body as\n" "it charges (2 seconds, 3 from a shield that was down) and staying lit,\n" - "its energy slower, in its own color (the powerup's), on the first-person\n" - "arms too with viewmodel_shield; a hit on it plays what the projectile\n" - "plays on an Elite's shield. Only what is drawn and heard changes.\n" - "In a network game, the host's network.shield_effects decides, unless\n" - "it is \"players\" (each player's own) or the game is co-op." }, - { "display.shield_glow", _config_boolean, "false", "HALO_SHIELD_GLOW", _environment_value, _platform_all, - "Energy shields light what is around them as they flare, as plasma\n" - "does, in the shield's own color. In a network game, the host's\n" + "its energy slower: green above 200% shields, reddish-pink below.\n" + "Arms also require Arm Shields. A hit on it plays\n" + "what the projectile plays on an Elite's shield. Only what is drawn\n" + "and heard changes. Online, the host decides through network.shield_effects,\n" + "unless it is \"players\" or the game is co-op (each player's own)." }, + + { "display.shield_glow", _config_boolean, "false", "HALO_SHIELD_GLOW", _environment_value, _platform_desktop, + "Energy shields cast soft body-sized light using the selected shield\n" + "appearance and overshield layer colour. Optional wall blocking uses\n" + "plasma_occlusion. In a network game, the host's\n" "network.shield_effects decides, unless it is \"players\" (each\n" - "player's own) or the game is co-op." }, - { "display.shield_glow_intensity", _config_string, "\"default\"", "HALO_SHIELD_GLOW_INTENSITY", _environment_value, _platform_all, + "player's own)." }, + { "display.shield_glow_intensity", _config_string, "\"default\"", "HALO_SHIELD_GLOW_INTENSITY", _environment_value, _platform_desktop, "How far the shield glow reaches: \"default\" or \"light_show\" (three\n" "times as far, and at full strength from a third of the flare).\n" "In a network game, the host's network.shield_effects decides, unless\n" - "it is \"players\" (each player's own) or the game is co-op." }, - { "display.shield_color", _config_string, "\"default\"", "HALO_SHIELD_COLOR", _environment_value, _platform_all, - "Your energy shield's color, as this machine draws it: \"default\" (the\n" - "shield's own) or a multiplayer armor color: white, black, red, blue,\n" - "gray, yellow, green, pink, purple, cyan, cobalt, orange, teal, sage,\n" - "brown, tan, maroon or salmon." }, + "it is \"players\" (each player's own)." }, { "game.unlock_all_levels", _config_boolean, "false", "HALO_UNLOCK_ALL_LEVELS", _environment_value, _platform_all, "true: a profile made from now on starts with every campaign level\n" @@ -626,6 +761,11 @@ static const struct config_setting config_settings[] = { "network.address", _config_string, "\"\"", "HALO_NET_ADDRESS", _environment_value, _platform_all, "This machine's IPv4 address for system link, for a machine on several\n" "networks; empty chooses one." }, + { "network.session_compatibility", _config_string, "\"opence_crossplay\"", "HALO_SESSION_COMPATIBILITY", _environment_value, _platform_all, + "Host session: opence_crossplay uses the shared OpenCE protocol with multiplayer shoulder cameras off; gulchce_third_person requires matching GulchCE camera clients. Fixed once the lobby opens." }, + { "network.camera_policy", _config_string, "\"player_choice\"", "HALO_CAMERA_POLICY", _environment_value, _platform_all, + "Host camera rule for new matches: player_choice, forced_on, or forced_off.\n" + "Applies to LAN, internet and co-op matches; scope and collision overrides remain." }, { "network.broadcast", _config_string, "\"\"", "HALO_NET_BROADCAST", _environment_value, _platform_all, "Comma-separated IPv4 addresses system link sends its announcements to\n" "instead of the local network's broadcast address (for VPNs); empty for\n" @@ -1266,7 +1406,8 @@ static const struct config_setting config_settings[] = { "debug.test_input", _config_string, "\"\"", "HALO_TEST_INPUT", _environment_value, _platform_all, "\"bot:\" plays controller 1 with a scripted pattern (automated\n" "network tests); \"look:\" stands still, only turning and looking\n" - "up and down; \"menu:\" presses menu buttons one a second (a,\n" + "up and down; \"legs:\" walks, strafes, crouches and jumps while\n" + "looking down; \"menu:\" presses menu buttons one a second (a,\n" "b, x, y, up, down, left, right, start, back or wait, separated by\n" "spaces or commas), for testing the menus; empty for none." }, { "debug.virtual_gamepads", _config_integer, "0", "HALO_VIRTUAL_GAMEPADS", _environment_value, _platform_desktop, @@ -2121,16 +2262,17 @@ static const struct { "display.hud_bumper_style", { "original", "modern", NULL }, NULL }, { "display.hud_button_style_ps", { "ps_classic", "ps_gems", "ps_dark_gems", "ps_modern", NULL }, NULL }, { "display.hud_button_style_switch", { "switch_classic", "switch_gems", "switch_modern", NULL }, NULL }, + { "display.shield_look", { "classic", "classic_with_sprinkles", "enhanced", "classic_honeycomb2", NULL }, NULL }, { "display.menus", { "pc", "xbox", NULL }, NULL }, + { "display.menu_frontend", { "off", "modern", "pc", "xbox", NULL }, NULL }, { "display.player_names", { "all", "allies", "enemies", "none", NULL }, NULL }, { "display.scoreboard_team_layout", { "teams", "score", NULL }, NULL }, { "display.chat_style", { "colors", "white", NULL }, NULL }, - { "display.shield_glow_intensity", { "default", "light_show", NULL }, NULL }, - { "display.shield_color", { "default", "white", "black", "red", "blue", "gray", "yellow", "green", "pink", - "purple", "cyan", "cobalt", "orange", "teal", "sage", "brown", "tan", "maroon", "salmon", NULL }, NULL }, { "audio.resampler", { "xbox", "sinc", "linear", NULL }, NULL }, { "audio.voice_chat", { "push_to_talk", "open_mic", "off", NULL }, NULL }, { "input.touch_controls", { "auto", "on", "off", NULL }, NULL }, + { "input.gyro_aim", { "legacy", "false", "true", "zoom", NULL }, NULL }, + { "bots.routes", { "direct", "lanes", "mixed", NULL }, NULL }, { "game.console_log", { "important", "all", "none", NULL }, NULL }, { "game.language", { "", "ja", "de", "fr", "es", "it", NULL }, NULL }, { "network.text_chat", { "on", "links", "off", NULL }, NULL }, @@ -2175,6 +2317,21 @@ static void config_check_words(void) if (index < 0 || !(config_settings[index].platforms & CONFIG_PLATFORM)) continue; value = &config_values[index]; + /* Preserve the approved shield profile from the earlier playtest. */ + if (!strcmp(config_words[word_index].name, "display.shield_look") && + config_word_is(value->string, strlen(value->string), "enhanced2")) + { + free(value->string); + value->string = strdup("enhanced"); + } + /* Retired shield presets return to the stock selection. */ + if (!strcmp(config_words[word_index].name, "display.shield_look") && + (config_word_is(value->string, strlen(value->string), "honeycomb") || + config_word_is(value->string, strlen(value->string), "classic_honeycomb"))) + { + free(value->string); + value->string = strdup("classic"); + } for (word = 0; words[word] && !config_word_is(value->string, strlen(value->string), words[word]); word++) { } @@ -2366,6 +2523,8 @@ static void config_apply_server_mode(void) } #endif +#include "lighting_settings_migration.inl" + static void config_load(void) { char path[1024]; @@ -2434,8 +2593,27 @@ static void config_load(void) if (result.ok) { char *completed; + int reset_lighting = lighting_settings_legacy(result.toptab); + int lighting_migrated = !reset_lighting; + if (reset_lighting) + { + char *migrated = lighting_settings_migrate(text, result.toptab); + if (migrated) + { + toml_result_t checked = toml_parse(migrated, (int)strlen(migrated)); + if (checked.ok) + { + toml_free(result); result = checked; + free(text); text = migrated; + lighting_migrated = 1; + } + else { toml_free(checked); free(migrated); } + } + platform_log("settings: reset old dynamic-lighting preferences to off%s", + lighting_migrated ? "" : " in memory; the file could not be migrated"); + } - if (joined && !skipped && !config_answer_only) + if (joined && !skipped && !config_answer_only && lighting_migrated) { if (config_write_file(path, text)) platform_log("settings: joined the sections %s had twice", path); @@ -2443,7 +2621,12 @@ static void config_load(void) platform_log("settings: cannot write %s", path); } for (index = 0; index < NUMBER_OF_CONFIG_SETTINGS; index++) + { config_set_from_file(&config_values[index], &config_settings[index], result.toptab); + if (reset_lighting && lighting_settings_reset_key(config_settings[index].name)) + config_set_from_text(&config_values[index], config_settings[index].type, + config_settings[index].type == _config_string ? "default" : "false"); + } #if !defined(HALO_ANDROID) && !defined(HALO_WEB) if (config_values[config_setting_index("server.enabled")].boolean && !config_probe_mode) config_server_mode = 1; @@ -2457,10 +2640,10 @@ static void config_load(void) platform_log("settings: %d line%s of config.toml skipped; every other setting in it is used", skipped, skipped == 1 ? "" : "s"); } - else if (!config_answer_only) + else if (!config_answer_only && lighting_migrated) { completed = config_add_missing(text, result.toptab); - if (completed && !config_write_file(path, completed)) + if ((completed || reset_lighting) && !config_write_file(path, completed ? completed : text)) platform_log("settings: cannot write %s", path); free(completed); } diff --git a/port/linux/src/sdl_platform.c b/port/linux/src/sdl_platform.c index fdd18dab0e..3772a6bdfb 100644 --- a/port/linux/src/sdl_platform.c +++ b/port/linux/src/sdl_platform.c @@ -20,6 +20,7 @@ and the debug keyboard that the game's console reads. #include "player_link.h" #include "xiso.h" #include "touch_input.h" +#include "dualsense.h" #include "../game/text_filter.h" #include @@ -2563,6 +2564,8 @@ void platform_pump_events(void) { SDL_Gamepad *gamepad = SDL_GetGamepadFromID(event.gdevice.which); + /* (a DualSense's triggers let go first) */ + dualsense_removed(gamepad); if (gamepad) SDL_CloseGamepad(gamepad); } @@ -2587,6 +2590,9 @@ void platform_pump_events(void) } #endif pthread_mutex_unlock(&input_lock); + /* a DualSense's adaptive triggers, lightbar and player lights: what + changed since the last frame (dualsense.c) */ + dualsense_frame(); looked_at_clipboard = TRUE; platform_invite_clipboard(look_at_clipboard); } diff --git a/port/linux/src/shader_prepare.c b/port/linux/src/shader_prepare.c new file mode 100644 index 0000000000..a00fcc9d8f --- /dev/null +++ b/port/linux/src/shader_prepare.c @@ -0,0 +1,276 @@ +/* Map-scoped shader recipes. Only observed pairs are retained; unused prepared + * programs are released at the next map boundary. The normal renderer owns + * programs transferred by shader_prepare_take. Recording performs no file I/O. */ +#include "shader_prepare.h" +#include "xgpu.h" +#include "port_config.h" +#include "sdl_platform.h" +#include "posix.h" +#include +#include +#include +#include + +#ifndef HALO_GLES +#include +#define PREPARE_MAGIC 0x31525053u +#define PREPARE_COUNT 512 +#define PREPARE_SOURCE 65536u +#define PREPARE_BYTES (16u * 1024u * 1024u) +#define PREPARE_COMPLETION 0x91B1 + +struct prepare_header { uint32_t magic, count; uint64_t map; }; +struct prepare_pair { + uint64_t vertex, fragment; + uint32_t vertex_bytes, fragment_bytes; +}; +struct prepare_entry { + struct prepare_pair pair; + char *vertex, *fragment; + GLuint program; + GLuint vertex_shader, fragment_shader; + int linked; + unsigned next; +}; +static struct { + struct prepare_entry entries[PREPARE_COUNT]; + unsigned buckets[PREPARE_COUNT]; + unsigned count, bytes; + uint64_t map; + int active; + char path[512]; + PFNGLGETSHADERSOURCEPROC source; + PFNGLDETACHSHADERPROC detach; +} prepare; + +static unsigned prepare_bucket(uint64_t vertex, uint64_t fragment) +{ + return (unsigned)(vertex ^ fragment ^ (vertex >> 32) ^ (fragment >> 32)) % PREPARE_COUNT; +} + +static struct prepare_entry *prepare_find(uint64_t vertex, uint64_t fragment) +{ + unsigned i; + for (i = prepare.buckets[prepare_bucket(vertex, fragment)]; i; i = prepare.entries[i - 1].next) { + struct prepare_entry *entry = &prepare.entries[i - 1]; + if (entry->pair.vertex == vertex && entry->pair.fragment == fragment) return entry; + } + return NULL; +} + +static void prepare_index(unsigned index) +{ + struct prepare_entry *entry = &prepare.entries[index]; + unsigned bucket = prepare_bucket(entry->pair.vertex, entry->pair.fragment); + entry->next = prepare.buckets[bucket]; + prepare.buckets[bucket] = index + 1; +} + +static uint64_t prepare_hash(char const *text) +{ + uint64_t hash = 14695981039346656037ULL; + while (*text) hash = (hash ^ (unsigned char)*text++) * 1099511628211ULL; + return hash; +} + +static void prepare_clear(void) +{ + unsigned i; + for (i = 0; i < prepare.count; i++) { + struct prepare_entry *entry = &prepare.entries[i]; + if (entry->program) glDeleteProgram(entry->program); + free(entry->vertex); + free(entry->fragment); + } + memset(prepare.entries, 0, sizeof(prepare.entries)); + memset(prepare.buckets, 0, sizeof(prepare.buckets)); + prepare.count = prepare.bytes = 0; +} + +/* SDL's quit/exit-after paths can exit without unloading the map. Save only + * CPU data at exit: a context need not still be current on that thread. */ +static void prepare_save(void) +{ + FILE *file; + struct prepare_header header; + unsigned i; + header.magic = PREPARE_MAGIC; header.count = prepare.count; header.map = prepare.map; + if (prepare.active && header.count && (file = fopen(prepare.path, "wb")) != NULL) { + int good = fwrite(&header, sizeof(header), 1, file) == 1; + for (i = 0; good && i < prepare.count; i++) { + struct prepare_entry *entry = &prepare.entries[i]; + good = fwrite(&entry->pair, sizeof(entry->pair), 1, file) == 1 && + fwrite(entry->vertex, entry->pair.vertex_bytes, 1, file) == 1 && + fwrite(entry->fragment, entry->pair.fragment_bytes, 1, file) == 1; + } + if (fclose(file)) good = 0; + if (!good) platform_log("shader preparation: could not save all recipes"); + } +} + +void shader_prepare_end(void) +{ + prepare_save(); + prepare_clear(); + memset(&prepare, 0, sizeof(prepare)); +} + +/* Validate every bounded record before submitting any source to the driver. */ +static int prepare_read(FILE *file) +{ + struct prepare_header header; + unsigned i; + if (fread(&header, sizeof(header), 1, file) != 1 || header.magic != PREPARE_MAGIC || + header.map != prepare.map || header.count > PREPARE_COUNT) return 0; + for (i = 0; i < header.count; i++) { + struct prepare_entry *entry = &prepare.entries[prepare.count++]; + if (fread(&entry->pair, sizeof(entry->pair), 1, file) != 1 || + entry->pair.vertex_bytes < 2 || entry->pair.vertex_bytes > PREPARE_SOURCE || + entry->pair.fragment_bytes < 2 || entry->pair.fragment_bytes > PREPARE_SOURCE || + entry->pair.vertex_bytes + entry->pair.fragment_bytes > PREPARE_BYTES - prepare.bytes) return 0; + entry->vertex = malloc(entry->pair.vertex_bytes); + entry->fragment = malloc(entry->pair.fragment_bytes); + if (!entry->vertex || !entry->fragment || + fread(entry->vertex, entry->pair.vertex_bytes, 1, file) != 1 || + fread(entry->fragment, entry->pair.fragment_bytes, 1, file) != 1 || + entry->vertex[entry->pair.vertex_bytes - 1] || entry->fragment[entry->pair.fragment_bytes - 1] || + strlen(entry->vertex) != entry->pair.vertex_bytes - 1 || + strlen(entry->fragment) != entry->pair.fragment_bytes - 1 || + prepare_hash(entry->vertex) != entry->pair.vertex || + prepare_hash(entry->fragment) != entry->pair.fragment) return 0; + if (prepare_find(entry->pair.vertex, entry->pair.fragment)) return 0; + prepare.bytes += entry->pair.vertex_bytes + entry->pair.fragment_bytes; + prepare_index(i); + } + return fgetc(file) == EOF && !ferror(file); +} + +void shader_prepare_begin(char const *map, shader_prepare_load_fn load, shader_prepare_store_fn store) +{ + static int exit_registered; + FILE *file; + unsigned i, loaded = 0, linked = 0; + int parallel; + Uint64 started; + shader_prepare_end(); + if (!map || !*map || !config_boolean("display.shader_prepare")) return; + prepare.source = (PFNGLGETSHADERSOURCEPROC)SDL_GL_GetProcAddress("glGetShaderSource"); + prepare.detach = (PFNGLDETACHSHADERPROC)SDL_GL_GetProcAddress("glDetachShader"); + if (!prepare.source || !prepare.detach) return; + prepare.map = prepare_hash(map); + if (snprintf(prepare.path, sizeof(prepare.path), "%s/shader_cache", platform_save_root()) >= sizeof(prepare.path)) return; + posix_make_directory(prepare.path); + if (snprintf(prepare.path, sizeof(prepare.path), "%s/shader_cache/recipes-%016llx.bin", + platform_save_root(), (unsigned long long)prepare.map) >= sizeof(prepare.path)) return; + file = fopen(prepare.path, "rb"); + if (file) { + int valid = prepare_read(file); + fclose(file); + if (!valid) { + platform_log("shader preparation: invalid recipe file ignored"); + prepare_clear(); + } + } + prepare.active = 1; + if (!exit_registered) { atexit(prepare_save); exit_registered = 1; } + started = SDL_GetTicksNS(); + parallel = SDL_GL_ExtensionSupported("GL_ARB_parallel_shader_compile") || + SDL_GL_ExtensionSupported("GL_KHR_parallel_shader_compile"); + /* Submit all missing pairs before waiting. Deleted attached shaders remain + * alive through linking. A refused recipe falls back to normal translation. */ + for (i = 0; i < prepare.count; i++) { + struct prepare_entry *entry = &prepare.entries[i]; + GLuint vertex, fragment; + entry->program = load ? load(entry->pair.vertex, entry->pair.fragment) : 0; + if (entry->program) { loaded++; continue; } + vertex = glCreateShader(GL_VERTEX_SHADER); + fragment = glCreateShader(GL_FRAGMENT_SHADER); + entry->program = glCreateProgram(); + if (vertex && fragment && entry->program) { + glShaderSource(vertex, 1, (char const *const *)&entry->vertex, NULL); + glShaderSource(fragment, 1, (char const *const *)&entry->fragment, NULL); + glCompileShader(vertex); glCompileShader(fragment); + glAttachShader(entry->program, vertex); glAttachShader(entry->program, fragment); + entry->vertex_shader = vertex; entry->fragment_shader = fragment; + glProgramParameteri(entry->program, GL_PROGRAM_BINARY_RETRIEVABLE_HINT, GL_TRUE); + glLinkProgram(entry->program); + entry->linked = 1; + linked++; + } + else if (entry->program) { + glDeleteProgram(entry->program); + entry->program = 0; + } + if (vertex) glDeleteShader(vertex); + if (fragment) glDeleteShader(fragment); + } + for (i = 0; i < prepare.count; i++) { + struct prepare_entry *entry = &prepare.entries[i]; + GLint ready = 0, status = 0; + if (!entry->program) continue; + if (parallel) { + do { + glGetProgramiv(entry->program, PREPARE_COMPLETION, &ready); + if (!ready) SDL_Delay(1); + } while (!ready); + } + glGetProgramiv(entry->program, GL_LINK_STATUS, &status); + /* These temporary compiler objects must not acquire the transferred + * program's context lifetime. They were marked for deletion above. */ + if (entry->vertex_shader) prepare.detach(entry->program, entry->vertex_shader); + if (entry->fragment_shader) prepare.detach(entry->program, entry->fragment_shader); + entry->vertex_shader = entry->fragment_shader = 0; + if (!status) { glDeleteProgram(entry->program); entry->program = 0; } + else if (store && entry->linked) store(entry->program, entry->pair.vertex, entry->pair.fragment); + } + platform_log("shader preparation: %u recipes, %u cached, %u linked in %.1f ms", + prepare.count, loaded, linked, (SDL_GetTicksNS() - started) / 1e6); +} + +unsigned int shader_prepare_take(shader_prepare_hash vertex, shader_prepare_hash fragment) +{ + struct prepare_entry *entry; + if (!prepare.active) return 0; + entry = prepare_find(vertex, fragment); + if (entry) { + GLuint program = entry->program; + entry->program = 0; + return program; + } + return 0; +} + +void shader_prepare_record(unsigned int vertex, unsigned int fragment, + shader_prepare_hash vertex_hash, shader_prepare_hash fragment_hash) +{ + struct prepare_entry entry; + GLint vertex_bytes = 0, fragment_bytes = 0; + if (!prepare.active || !vertex || !fragment || + prepare_find(vertex_hash, fragment_hash)) return; + glGetShaderiv(vertex, GL_SHADER_SOURCE_LENGTH, &vertex_bytes); + glGetShaderiv(fragment, GL_SHADER_SOURCE_LENGTH, &fragment_bytes); + if (vertex_bytes < 2 || fragment_bytes < 2 || vertex_bytes > PREPARE_SOURCE || fragment_bytes > PREPARE_SOURCE || + (unsigned)(vertex_bytes + fragment_bytes) > PREPARE_BYTES - prepare.bytes || prepare.count == PREPARE_COUNT) return; + memset(&entry, 0, sizeof(entry)); + entry.vertex = calloc(vertex_bytes, 1); entry.fragment = calloc(fragment_bytes, 1); + if (!entry.vertex || !entry.fragment) { free(entry.vertex); free(entry.fragment); return; } + prepare.source(vertex, vertex_bytes, NULL, entry.vertex); + prepare.source(fragment, fragment_bytes, NULL, entry.fragment); + entry.pair.vertex = prepare_hash(entry.vertex); entry.pair.fragment = prepare_hash(entry.fragment); + if (entry.pair.vertex != vertex_hash || entry.pair.fragment != fragment_hash) { + free(entry.vertex); free(entry.fragment); return; + } + entry.pair.vertex_bytes = (uint32_t)strlen(entry.vertex) + 1; + entry.pair.fragment_bytes = (uint32_t)strlen(entry.fragment) + 1; + prepare.bytes += entry.pair.vertex_bytes + entry.pair.fragment_bytes; + prepare.entries[prepare.count++] = entry; + prepare_index(prepare.count - 1); +} +#else +void shader_prepare_begin(char const *map, shader_prepare_load_fn load, shader_prepare_store_fn store) {(void)map;(void)load;(void)store;} +void shader_prepare_end(void) {} +void shader_prepare_record(unsigned int vertex, unsigned int fragment, + shader_prepare_hash vertex_hash, shader_prepare_hash fragment_hash) +{(void)vertex;(void)fragment;(void)vertex_hash;(void)fragment_hash;} +unsigned int shader_prepare_take(shader_prepare_hash vertex, shader_prepare_hash fragment) {(void)vertex;(void)fragment;return 0;} +#endif diff --git a/port/linux/src/shader_prepare.h b/port/linux/src/shader_prepare.h new file mode 100644 index 0000000000..b2f417de02 --- /dev/null +++ b/port/linux/src/shader_prepare.h @@ -0,0 +1,15 @@ +/* Optional map-scoped preparation of previously observed shader pairs. */ +#ifndef SHADER_PREPARE_H +#define SHADER_PREPARE_H + +typedef unsigned long long shader_prepare_hash; +typedef unsigned int (*shader_prepare_load_fn)(shader_prepare_hash, shader_prepare_hash); +typedef void (*shader_prepare_store_fn)(unsigned int, shader_prepare_hash, shader_prepare_hash); + +void shader_prepare_begin(char const *map, shader_prepare_load_fn load, shader_prepare_store_fn store); +void shader_prepare_end(void); +void shader_prepare_record(unsigned int vertex, unsigned int fragment, + shader_prepare_hash vertex_hash, shader_prepare_hash fragment_hash); +unsigned int shader_prepare_take(shader_prepare_hash vertex, shader_prepare_hash fragment); + +#endif diff --git a/port/linux/src/shield_honeycomb_gl.h b/port/linux/src/shield_honeycomb_gl.h new file mode 100644 index 0000000000..b0d10f53c5 --- /dev/null +++ b/port/linux/src/shield_honeycomb_gl.h @@ -0,0 +1,50 @@ +/* Procedural shield surface. Included by the pixel shader translator; a zero +scale leaves the original fragment untouched. One grid follows the model UVs, +without blending overlapping projections. Filter from the unfolded coordinates: +the distance field folds at shared edges, where its derivatives can cancel. +Pulse continuously across shared links, with a faint persistent core. No extracted +Infinite textures or shader code. */ +#ifndef SHIELD_HONEYCOMB_GL_H +#define SHIELD_HONEYCOMB_GL_H + +static const char shield_honeycomb_glsl[] = + "in vec2 shield_uv;\n" + "uniform vec4 shield_honeycomb[3];\n" + "float shield_hex(vec2 p, float time)\n" + "{\n" + " vec2 period = vec2(1.7320508, 3.0);\n" + " vec2 a = mod(p, period) - period * 0.5;\n" + " vec2 b = mod(p - period * 0.5, period) - period * 0.5;\n" + " vec2 q = dot(a,a) < dot(b,b) ? a : b;\n" + " q = abs(q);\n" + " float edge = 0.8660254 - max(q.x, dot(q, vec2(0.5,0.8660254)));\n" + " float footprint = max(length(dFdx(p)),length(dFdy(p)));\n" + " float aa = clamp(footprint*0.5,0.002,0.25);\n" + " float line = 1.0 - smoothstep(0.07-aa,0.07+aa,edge);\n" + " float glow = exp(-max(edge,0.0)*9.0);\n" + " float pulse = pow(0.5+0.5*sin(dot(p,vec2(1.7,2.3))+time*2.2),4.0);\n" + " float pattern = 0.015+line*(0.28+0.37*pulse)+glow*(0.10+0.20*pulse);\n" + " return mix(pattern,0.13,smoothstep(0.5,1.5,footprint));\n" + "}\n" + "vec4 shield_honeycomb_surface(vec4 original)\n" + "{\n" + " if (shield_honeycomb[0].w == 0.0) return original;\n" + " float time = shield_honeycomb[1].w;\n" + " float pattern = shield_hex(shield_uv * shield_honeycomb[0].w, time);\n" + " float energy = shield_honeycomb[2].a*xD0.a;\n" + /* Body links take their light from the same resolved flowing plasma as + the approved arm composite, including Classic's moving white highlights. + Only a faint palette-coloured core remains between waves. */ + " if (shield_honeycomb[0].x == 3.0)\n" + " {\n" + " vec3 colour = clamp(xD1.rgb,0.0,1.0);\n" + " return vec4(original.rgb*(0.45+pattern*1.5)+colour*pattern*0.08,original.a);\n" + " }\n" + /* Classic owns the fully resolved RGB, including its view-angle blend. + Only opacity combines here; neither layer introduces a second palette. */ + " float plasma = max(original.a,0.0)*0.65;\n" + " float links = energy*pattern*0.65;\n" + " return vec4(original.rgb,plasma+links);\n" + "}\n"; + +#endif diff --git a/port/linux/src/touch_gyro.c b/port/linux/src/touch_gyro.c new file mode 100644 index 0000000000..e967caf8ef --- /dev/null +++ b/port/linux/src/touch_gyro.c @@ -0,0 +1,53 @@ +/* Android's optional gyro settings. Only input changes; player actions and +the network's simulation contract are unchanged. */ +#include "touch_gyro.h" +#include "port_config.h" +#include + +int touch_gyro_mode(void) +{ +#ifdef HALO_ANDROID + const char *mode = config_string("input.gyro_aim"); + if (!strcmp(mode, "false")) return _touch_gyro_off; + if (!strcmp(mode, "true")) return _touch_gyro_on; + if (!strcmp(mode, "zoom")) return _touch_gyro_zoom; + return _touch_gyro_legacy; +#else + return _touch_gyro_legacy; +#endif +} + +#ifdef HALO_ANDROID +static float gyro_scale(const char *setting, const char *invert) +{ + double value = config_real(setting); + /* The comparisons reject NaN as well as out-of-range settings. */ + if (!(value >= 0.25 && value <= 10.0)) value = 1.0; + return (float)(config_boolean(invert) ? -value : value); +} +#endif + +void touch_gyro_apply(float *yaw, float *pitch) +{ +#ifdef HALO_ANDROID + int mode = touch_gyro_mode(); + if (mode == _touch_gyro_off) + { + *yaw = *pitch = 0.0f; + } + else if (mode != _touch_gyro_legacy) + { + *yaw *= gyro_scale("input.gyro_sensitivity_horizontal", "input.gyro_invert_horizontal"); + *pitch *= gyro_scale("input.gyro_sensitivity_vertical", "input.gyro_invert_vertical"); + } +#else + (void)yaw; + (void)pitch; +#endif +} + +void halo_linux_gyro_filter(int zoomed, float *yaw, float *pitch) +{ + if (!zoomed && touch_gyro_mode() == _touch_gyro_zoom) + *yaw = *pitch = 0.0f; +} diff --git a/port/linux/src/touch_gyro.h b/port/linux/src/touch_gyro.h new file mode 100644 index 0000000000..d74d62b315 --- /dev/null +++ b/port/linux/src/touch_gyro.h @@ -0,0 +1,17 @@ +/* Android gyro settings; the default keeps the saved touch layout's behavior. */ +#ifndef HALO_TOUCH_GYRO_H +#define HALO_TOUCH_GYRO_H + +enum +{ + _touch_gyro_legacy = -1, + _touch_gyro_off, + _touch_gyro_on, + _touch_gyro_zoom +}; + +int touch_gyro_mode(void); +void touch_gyro_apply(float *yaw, float *pitch); +void halo_linux_gyro_filter(int zoomed, float *yaw, float *pitch); + +#endif diff --git a/port/linux/src/touch_input.c b/port/linux/src/touch_input.c index 3154c34115..8e739878c8 100644 --- a/port/linux/src/touch_input.c +++ b/port/linux/src/touch_input.c @@ -10,9 +10,11 @@ finger down (host_gesture_insets). */ #include "touch_input.h" +#include "touch_gyro.h" #include "keyboard_prompts.h" #include "touch_menu.h" #include "port_config.h" +#include "keyboard_prompts.h" #include #include @@ -26,6 +28,7 @@ void host_touch_read(int *state); void host_touch_look_read(float *delta); void host_touch_rumble(unsigned int low, unsigned int high); void host_touch_scene(int scene); +void host_touch_gyro_mode(int mode); void host_touch_bindings(const int *controls); #endif #ifdef HALO_ANDROID @@ -37,6 +40,8 @@ int touch_game_cinematic_skippable(void); int touch_game_cinematic_playing(void); int touch_game_playing(void); void touch_game_button_controls(int *controls); +/* port/linux/game/android_cheats.c, called on the game thread. */ +void android_cheats_update(void); /* ... and its skip button during a cinematic (port/linux/game/touch_cinematic.c) */ int touch_cinematic_tap(float x, float y); @@ -321,6 +326,10 @@ void touch_input_controls(XINPUT_GAMEPAD *pad, int menus) /* (the controls show only in a game: not while it starts, at the main menu, in a menu or during a cinematic; nor while the text chat's on-screen keyboard is up, whose keys the fingers then tap) */ +#ifdef HALO_ANDROID + host_touch_gyro_mode(touch_gyro_mode()); + android_cheats_update(); +#endif host_touch_scene(_touch_scene_known | touch_controls_setting() | (menus || !touch_game_playing() || touch_game_cinematic_playing() || (network_chat_controller() == 0) ? _touch_scene_menus : 0)); diff --git a/port/linux/src/updater.c b/port/linux/src/updater.c index 0e47b23a0e..343a67a6eb 100644 --- a/port/linux/src/updater.c +++ b/port/linux/src/updater.c @@ -46,7 +46,7 @@ update.h's: posix_update.c on Linux, win32_update.c on Windows. #define HALO_BUILD_FLAVOR "release" #endif -#define UPDATE_REPOSITORY "OpenCommunityEdition/OpenCE" +#define UPDATE_REPOSITORY "chestahh/GulchCE" #ifdef _WIN32 #define UPDATE_PLATFORM "windows" #define PATH_SEPARATOR "\\" @@ -473,7 +473,7 @@ static int updater_download_zip(const char *zip_path, char *error, size_t error_ snprintf(error, error_size, "could not start the download"); return 0; } - window = SDL_CreateWindow("Halo", 640, 150, 0); + window = SDL_CreateWindow("GulchCE", 640, 150, 0); if (window) renderer = SDL_CreateRenderer(window, SDL_SOFTWARE_RENDERER); while (!finished) @@ -667,7 +667,7 @@ static void updater_update(void) char message[800]; snprintf(message, sizeof(message), "The update failed:\n\n%s", error); - SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Halo", message, NULL); + SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "GulchCE", message, NULL); } } @@ -946,11 +946,11 @@ void updater_poll(SDL_Window *window) if (fullscreen) SDL_SetWindowFullscreen(window, false); snprintf(message, sizeof(message), - "A new version of Halo was detected (build %ld; this is build %d).\n\n" + "A new version of GulchCE was detected (build %ld; this is build %d).\n\n" "Do you want to update? The game will close and start the new version.", updater_latest_build, HALO_BUILD_NUMBER); { - SDL_MessageBoxData question = { SDL_MESSAGEBOX_INFORMATION, window, "Halo: new version", message, + SDL_MessageBoxData question = { SDL_MESSAGEBOX_INFORMATION, window, "GulchCE: new version", message, 3, question_buttons, NULL }; if (!SDL_ShowMessageBox(&question, &answer)) @@ -958,7 +958,7 @@ void updater_poll(SDL_Window *window) } if (answer == 2) { - SDL_MessageBoxData confirm = { SDL_MESSAGEBOX_WARNING, window, "Halo: new version", + SDL_MessageBoxData confirm = { SDL_MESSAGEBOX_WARNING, window, "GulchCE: new version", "Stop asking about new versions?\n\n" "To ask again, set auto = true in the [update] section of config.toml.", 2, confirm_buttons, NULL }; diff --git a/port/linux/src/xbox_textures.c b/port/linux/src/xbox_textures.c index e8dd021f65..a9c84862b4 100644 --- a/port/linux/src/xbox_textures.c +++ b/port/linux/src/xbox_textures.c @@ -7,6 +7,8 @@ An Xbox texture is a Direct3D header - Common, Data (physical address), Lock, Format and Size - over texels in guest memory. Power-of-two textures are swizzled (Morton order, one level after another); textures with a Size field are linear, with a pitch, and are addressed with texel coordinates. +The port also uses Size for bounded CE non-power-of-two DXT textures; +these retain normalized coordinates and tightly packed compressed blocks. DXT textures are stored as plain 4x4 blocks. Everything except DXT is converted to 32-bit BGRA on upload. @@ -170,7 +172,7 @@ void xgpu_texture_describe(DWORD format_word, DWORD size_word, struct xgpu_textu linear DXT formats), so a Size word on one only gives the true sides of a Custom Edition bitmap that is not a power of two; it is addressed with normalized coordinates like any compressed texture */ - description->linear = !description->compressed; + description->linear = !description->compressed; } else { @@ -1361,6 +1363,7 @@ static BOOL texture_entry_pixels_valid(const struct texture_entry *entry) return platform_is_contiguous((void *)entry->address) && platform_is_contiguous((void *)(entry->address + entry->size - 1)); } + /* display.high_res_hud, read again only when a setting changes: it is asked at every bind, and config_boolean takes the settings' lock and looks the name up among them all */ @@ -1385,7 +1388,7 @@ static GLuint texture_entry_result(struct texture_entry *entry, GLenum *target, *target = entry->target; *description = entry->description; - /* port: a Custom Edition bitmap whose Size word gives sides that are + /* port: a Custom Edition bitmap whose Size word gives sides that are any uncompressed linear bitmap: sampled with normalized coordinates like any other texture, not in texels as an Xbox's linear texture is. Decoding keeps the entry's own description (its pitch). */ @@ -1595,7 +1598,7 @@ GLuint xgpu_texture_get(const DWORD *resource, const D3DCOLOR *palette, GLenum * } entry->generation = 0; entry->override = -1; - glGenTextures(1, &entry->texture); + entry->texture = xgpu_texture_name_new(); entry->next = *bucket; *bucket = entry; } diff --git a/port/linux/src/xgpu.h b/port/linux/src/xgpu.h index 28571c3ae1..0f8c620d16 100644 --- a/port/linux/src/xgpu.h +++ b/port/linux/src/xgpu.h @@ -69,6 +69,10 @@ int xgpu_gl_ready(void); may give its name to a new texture (call before glDeleteTextures) */ void xgpu_gl_texture_deleted(unsigned int texture); +GLuint xgpu_texture_name_new(void); +void xgpu_texture_names_prepare(void); +void xgpu_texture_names_dispose(void); + /* a compiled shader, or a linked program of two, or 0 with the log written */ GLuint xgpu_compile_shader(GLenum type, const char *code, const char *what); @@ -115,9 +119,11 @@ header). Attributes whose bit is set in packed_attribute_mask are fed as NORMPACKED3 32-bit integers and unpacked in the shader. With lighting (else NULL), the normal and world position go to the pixel shader too, which lights the diffuse color for each pixel (nv2a_pixel_shader_key -per_pixel_lighting). Returns a malloc'd string. */ +per_pixel_lighting). plasma_model adds optional light falloff/occlusion; +FALSE emits the original translation. Android always omits the additions. +Returns a malloc'd string. */ char *nv2a_vertex_shader_to_glsl(const DWORD *instructions, unsigned long instruction_count, - unsigned long packed_attribute_mask, const struct nv2a_vertex_lighting *lighting); + unsigned long packed_attribute_mask, const struct nv2a_vertex_lighting *lighting, BOOL plasma_model); /* the fixed-function pipeline's vertex shader (the loading screen's draws): positions already in clip space. Returns a malloc'd string. */ char *nv2a_fixed_function_glsl(void); @@ -177,6 +183,10 @@ struct nv2a_pixel_shader_key unsigned char source_blend; /* MCC environment lightmap pass only; part of the compiled shader key. */ unsigned char mcc_bump_attenuation; + /* Optional model-light falloff/occlusion, only for selected point lights. */ + unsigned char plasma_model; + /* The procedural surface is needed only while a shield draw enables it. */ + unsigned char shield_honeycomb; }; char *nv2a_pixel_shader_to_glsl(const struct nv2a_pixel_shader_key *key); diff --git a/port/linux/src/xgpu_texture_names.c b/port/linux/src/xgpu_texture_names.c new file mode 100644 index 0000000000..c7ca51d711 --- /dev/null +++ b/port/linux/src/xgpu_texture_names.c @@ -0,0 +1,50 @@ +/* Texture names do not allocate image storage. Batch their creation: separate + * glGenTextures calls can synchronize the Windows driver on first-use draws. + * Once a name is handed out, its texture cache owns it and its deletion. */ +#include "xgpu.h" +#include + +#ifndef HALO_GLES +#define TEXTURE_NAMES_BATCH 64 +#define TEXTURE_NAMES_PREPARED 1024 +static GLuint texture_names[TEXTURE_NAMES_PREPARED]; +static unsigned texture_name_count; + +static void texture_names_fill(unsigned target) +{ + unsigned first = texture_name_count, index; + if (first >= target) return; + memset(texture_names + first, 0, (target - first) * sizeof(*texture_names)); + glGenTextures((GLsizei)(target - first), texture_names + first); + for (index = first; index < target; index++) { + if (texture_names[index]) texture_names[texture_name_count++] = texture_names[index]; + } +} +#endif + +GLuint xgpu_texture_name_new(void) +{ +#ifndef HALO_GLES + if (!texture_name_count) texture_names_fill(TEXTURE_NAMES_BATCH); + return texture_name_count ? texture_names[--texture_name_count] : 0; +#else + GLuint texture = 0; + glGenTextures(1, &texture); + return texture; +#endif +} + +void xgpu_texture_names_prepare(void) +{ +#ifndef HALO_GLES + texture_names_fill(TEXTURE_NAMES_PREPARED); +#endif +} + +void xgpu_texture_names_dispose(void) +{ +#ifndef HALO_GLES + if (texture_name_count) glDeleteTextures((GLsizei)texture_name_count, texture_names); + texture_name_count = 0; +#endif +} diff --git a/port/linux/src/xinput_sdl.c b/port/linux/src/xinput_sdl.c index d708a52cdc..b5f78ebba0 100644 --- a/port/linux/src/xinput_sdl.c +++ b/port/linux/src/xinput_sdl.c @@ -41,12 +41,16 @@ drive the controller. #include "sdl_platform.h" #include "port_config.h" #include "touch_input.h" +#include "dualsense.h" /* port/linux/game/network_aim_assist.c */ extern unsigned char network_aim_assist_block_mouse(void); #include "halo_keyboard.h" #include "keyboard_prompts.h" #include "controller_buttons.h" #include "controller_remap.h" +#include "frontend_input.h" +#include "keyboard_prompts.h" +#include "touch_gyro.h" #include #include @@ -403,6 +407,7 @@ int halo_linux_touch_look(short gamepad_index, float *yaw, float *pitch, float * return FALSE; #if defined(HALO_ANDROID) || defined(HALO_WEB) touch_input_look(0.0022f, yaw, pitch, gyro_yaw, gyro_pitch); + touch_gyro_apply(gyro_yaw, gyro_pitch); /* (none while the chat's on-screen keyboard is up: what was swiped is dropped, not saved for after) */ if (network_chat_keyboard_open() && network_chat_controller() == 0) @@ -650,7 +655,10 @@ static const char *const binding_settings[NUMBER_OF_HALO_KEYBOARD_ACTIONS] = "controls.jump", "controls.crouch", "controls.fire", "controls.throw_grenade", "controls.melee", "controls.reload", "controls.zoom", "controls.switch_weapon", "controls.switch_grenade", "controls.action", "controls.flashlight", "controls.scoreboard", "controls.pause", "controls.screenshot", - "controls.push_to_talk", "controls.chat", "controls.team_chat", "controls.vote_yes", "controls.vote_no", + "controls.push_to_talk", "controls.swap_shoulder", + "controls.free_look", "controls.toggle_perspective", "controls.chat", "controls.team_chat", "controls.camera_distance", + "controls.vote_yes", "controls.vote_no", + "controls.camera_height", "controls.camera_offset", }; static const struct @@ -854,6 +862,25 @@ static unsigned long keyboard_bound_actions(const struct platform_input_state *i return held; } +/* Game-side camera eligibility and settings live in third_person_input.c. */ +int third_person_camera_scroll(float notches, unsigned long actions); + +static void camera_scroll_capture(struct platform_input_state *input) +{ + if (!input->menus && !input->mouse_released && !console_is_active() && !network_chat_typing() && + third_person_camera_scroll(input->mouse_wheel, keyboard_bound_actions(input))) + { + input->mouse_wheel = 0.0f; + /* A captured scroll cannot feed the wheel's synthetic weapon button. */ + pthread_mutex_lock(&mouse_lock); + mouse_wheel_accumulated = 0.0f; + wheel_press_until_ms = wheel_moved_ms = 0; + wheel_scrolling = FALSE; + wheel_direction = 0; + pthread_mutex_unlock(&mouse_lock); + } +} + /* One capture per press, regardless of how long the binding is held. */ static void keyboard_screenshot(unsigned long held) { @@ -1023,6 +1050,7 @@ static void test_input_gamepad(XINPUT_GAMEPAD *pad) static int checked; static int seed = -1; static int looking; + static int legs; double t; int index; @@ -1060,6 +1088,11 @@ static void test_input_gamepad(XINPUT_GAMEPAD *pad) seed = atoi(setting + 4); else if (!strcmp(setting, "bot")) seed = 0; + else if (!strncmp(setting, "legs:", 5)) + { + seed = atoi(setting + 5); + legs = 1; + } else if (!strncmp(setting, "look:", 5)) { seed = atoi(setting + 5); @@ -1081,6 +1114,31 @@ static void test_input_gamepad(XINPUT_GAMEPAD *pad) return; } t = test_input_seconds() + seed * 1.7; + if (legs) + { + /* Repeatable first-person waist inspection: stand, walk forward/ + back, strafe, crouch-walk, then jump and turn, always looking down. */ + double phase = fmod(t, 32.0); + pad->sThumbRY = -32000; + if (phase >= 4.0 && phase < 12.0) + pad->sThumbLY = phase < 8.0 ? 32000 : -32000; + else if (phase >= 12.0 && phase < 20.0) + pad->sThumbLX = phase < 16.0 ? 32000 : -32000; + else if (phase >= 20.0 && phase < 26.0) + { + pad->wButtons |= XINPUT_GAMEPAD_LEFT_THUMB; + pad->sThumbLY = phase < 23.0 ? 24000 : -24000; + } + else if (phase >= 26.0) + { + pad->sThumbRX = 12000; + pad->sThumbLY = 24000; + if (fmod(phase, 2.0) < 0.15) + pad->bAnalogButtons[XINPUT_GAMEPAD_A] = 255; + } + return; + } + if (looking) { pad->sThumbRX = (SHORT)(sin(t * 0.5) * 14000.0); @@ -1684,6 +1742,7 @@ DWORD WINAPI XInputGetState(HANDLE device, PXINPUT_STATE state) /* Keep the opening chat press so even B can open it without immediately closing it. */ chat_pad_record((short)port, &physical); chat_physical_pad[port] = chat_pad[port]; + frontend_input_pad((short)port, chat_physical_pad[port], port_gamepad(gamepads, count, port) != NULL); /* Observe physical input before keyboard/touch merging or remapping. */ prompt_buttons = physical.wButtons; for (prompt_index = 0; prompt_index < 8; prompt_index++) @@ -1709,10 +1768,12 @@ DWORD WINAPI XInputGetState(HANDLE device, PXINPUT_STATE state) if (input.mouse_dx || input.mouse_dy || input.mouse_wheel) mouse |= 0x100; keyboard_prompt_keys(input.keys, sizeof(input.keys), mouse); } + keys_held_over_switch(&input); + if (input.focused) frontend_input_keys(input.keys, sizeof(input.keys)); + camera_scroll_capture(&input); mouse_poll(&input); wheel_update(); keyboard_actions_held = 0; - keys_held_over_switch(&input); /* (a chat line typed takes the keyboard as the console does) */ console_active = console_is_active() || network_chat_typing(); debug_camera_update(&input, console_active); @@ -1801,6 +1862,10 @@ DWORD WINAPI XInputSetState(HANDLE device, PXINPUT_FEEDBACK feedback) touch_input_rumble(feedback->Rumble.wLeftMotorSpeed, feedback->Rumble.wRightMotorSpeed); #endif count = sdl_gamepads(gamepads); + /* (a DualSense's adaptive triggers: which pad this port has, and the + motors, after which the triggers are sent again: dualsense.c) */ + dualsense_port(port, port_gamepad(gamepads, count, port), feedback->Rumble.wLeftMotorSpeed, + feedback->Rumble.wRightMotorSpeed); if (port_gamepad(gamepads, count, port)) { /* the game refreshes the motors every frame; rumble a little longer diff --git a/port/third_party/dualsense/README.md b/port/third_party/dualsense/README.md new file mode 100644 index 0000000000..1d0d672ae5 --- /dev/null +++ b/port/third_party/dualsense/README.md @@ -0,0 +1,34 @@ +# DualSense format references and notices + +The feature was imported from [OpenCE PR #549](https://github.com/OpenCommunityEdition/OpenCE/pull/549), +authored by PeterRichardsonGolf, with source commits +`80a1964`, `303a99f` and `2944896` recorded by `cherry-pick -x`. +The game profiles, scheduling and integration live in `port/linux/`, not here. +This folder retains notices for the public format references used by that code. + +## Trigger effects + +John "Nielk1" Klein's MIT-licensed TriggerEffectGenerator, revision 6: +[ExtendInput.DataTools.DualSense.TriggerEffectGenerator.cs](https://gist.githubusercontent.com/Nielk1/6d54cc2c00d2201ccb8c2720ad7538db/raw/74fc790e5fa3cd6ad278233a7636553eddca900d/ExtendInput.DataTools.DualSense.TriggerEffectGenerator.cs). +Gist revision: `f73a299fdc52f43be84d39e62734192ad82bb393`. +SHA-256 of the UTF-8 source: `7ad1cc12615f7cc4657c72a797b798857ec176ad32fd91e812e10fd1f454e56e`. +The complete copyright and permission notice is preserved in +[TriggerEffectGenerator-LICENSE.txt](TriggerEffectGenerator-LICENSE.txt), +with only the C comment delimiters removed. + +`port/linux/src/dualsense_rules.c` uses the Feedback, Weapon and Vibration +packing: the ten-zone mask and packed three-bit force values. No C# source +is compiled. The notice accompanies source and binary distributions. + +## SDL PS5 output + +[SDL release-3.4.16](https://github.com/libsdl-org/SDL/tree/release-3.4.16), +commit `fa2c02bb6e21974a89ea9824bc53c9932abe5f9c`, zlib licence. +Reference: `src/joystick/hidapi/SDL_hidapi_ps5.c`; +SHA-256 with LF line endings: `c535231bf9ec785e4e7dc1805c5d989d534ca5b9a3f47b1fe354b224faf22a16`. +Its output-body layout, player-light patterns and report framing inform +`dualsense_rules.c`; `dualsense.c` also reproduces the default player-index +lightbar palette. [SDL-LICENSE.txt](SDL-LICENSE.txt) is copied unchanged. +SDL's source is otherwise obtained by the existing platform build scripts. + +These are public third-party sources, not proprietary Xbox SDK or MCC material. diff --git a/port/third_party/dualsense/SDL-LICENSE.txt b/port/third_party/dualsense/SDL-LICENSE.txt new file mode 100644 index 0000000000..e9adee4484 --- /dev/null +++ b/port/third_party/dualsense/SDL-LICENSE.txt @@ -0,0 +1,18 @@ +Copyright (C) 1997-2026 Sam Lantinga + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. + diff --git a/port/third_party/dualsense/TriggerEffectGenerator-LICENSE.txt b/port/third_party/dualsense/TriggerEffectGenerator-LICENSE.txt new file mode 100644 index 0000000000..bdedc4cfb2 --- /dev/null +++ b/port/third_party/dualsense/TriggerEffectGenerator-LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-2022 John "Nielk1" Klein + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/port/web/README.md b/port/web/README.md index 74070cd18d..051e305487 100644 --- a/port/web/README.md +++ b/port/web/README.md @@ -196,7 +196,9 @@ reloads. networks block WebRTC) cannot play together. - Custom Edition and MCC maps retain their native format limits and unsupported-feature checks. Import storage tests do not substitute for - gameplay and networking tests. + gameplay and networking validation; current Milestone 14 runtime evidence + and outstanding checks are recorded in + [the validation ledger](../../docs/mcc_refactor_validation.md). - No Bink videos (as on the other ports). - The browser's WebGL 2 is OpenGL ES 3.0 without its 3.1 and 3.2 additions: the visibility tests (lens flares) report whether anything was drawn, a diff --git a/port/web/licenses.py b/port/web/licenses.py index a1d2e1f32a..c6069c2d39 100644 --- a/port/web/licenses.py +++ b/port/web/licenses.py @@ -13,6 +13,9 @@ # what each notice is for, and its file NOTICES = [ + ("DualSense trigger effect packing (John Nielk1 Klein)", "port/third_party/dualsense/TriggerEffectGenerator-LICENSE.txt"), + ("Enhanced bot tactics: BirchWoodGod, adapted by thelinkin3000 and GulchCE", "LICENSES/GPL-3.0-only.txt"), + ("Bot and Android feature provenance", "docs/reading/bots_and_android_features.md"), ("Expat (the menus' XML)", "port/third_party/expat/COPYING"), ("Opus (voice chat's codec)", "port/third_party/opus/COPYING"), ("zlib", "port/third_party/zlib/LICENSE"), diff --git a/port/web/tests/map-import-ui.test.js b/port/web/tests/map-import-ui.test.js new file mode 100644 index 0000000000..b43935654c --- /dev/null +++ b/port/web/tests/map-import-ui.test.js @@ -0,0 +1,82 @@ +'use strict'; +const test=require('node:test'); +const assert=require('node:assert/strict'); +const fs=require('node:fs'); +const vm=require('node:vm'); +const source=fs.readFileSync(require.resolve('../site/app.js'),'utf8'); + +function launcher() { + const elements=new Map(),workers=[],deleted=[]; + function element(id) { + if(!elements.has(id))elements.set(id,{value:'',hidden:false,disabled:false,textContent:'',style:{},events:{}, + classList:{toggle(){},add(){},remove(){}},append(){},replaceChildren(){}, + addEventListener(name,callback){this.events[name]=callback;}}); + return elements.get(id); + } + let busy=false,releases=0,workerFailure=false; + const storage={GUARD:'opence-game-data',async lock(){if(busy)throw new Error('Map storage is busy in another tab.');busy=true;return()=>{busy=false;releases++;};}, + async startGame(){if(busy)throw new Error('Map storage is busy in another tab.');},async dispatch(){return {visible:true};}}; + const drive={async *entries(){yield ['cache000.map'];yield ['savegame.bin'];yield ['profile.bin'];}, + async removeEntry(name){deleted.push('save/z/'+name);}}; + const save={async getDirectoryHandle(){return drive;}}; + const root={async removeEntry(name){deleted.push(name);},async getDirectoryHandle(){return save;}}; + const context=vm.createContext({console,Blob,TextEncoder,TextDecoder,Uint8Array,Uint32Array,DataView,ArrayBuffer,URLSearchParams, + location:{search:''},navigator:{storage:{persist:async()=>true,getDirectory:async()=>root},locks:{request(){},query(){}}}, + document:{getElementById:element,createElement:()=>element('generated'),addEventListener(){}}, + window:{isSecureContext:true,crossOriginIsolated:true,addEventListener(){},HaloMapStorage:storage,HaloNet:{onChange(){}}}, + OffscreenCanvas:class{},confirm:()=>true, + Worker:class {constructor(path){if(workerFailure)throw new Error('Worker unavailable');this.path=path;workers.push(this);}terminate(){this.stopped=true;}postMessage(message){this.message=message;}} + }); + // Evaluate the actual launcher and its handlers, without starting the page's + // asynchronous browser/game bootstrap. No implementation functions copied. + vm.runInContext(source.slice(0,source.indexOf('// ---------- start')),context); + vm.runInContext('checksPassed=true; dataReady=true; refreshData=async()=>{}; refreshMods=async()=>{}; refreshCustomMaps=async()=>{}; refreshStorage=async()=>{};',context); + return {elements,element,workers,deleted,storage,context,run:code=>vm.runInContext(code,context), + busy:value=>{busy=value;},failWorker:()=>{workerFailure=true;},releases:()=>releases}; +} +test('Xbox import keeps its worker and message, blocks new imports and restores Play',async()=>{ + const l=launcher();await l.run('importData({type:"folder",files:[]})'); + assert.equal(l.workers[0].path,'xiso-worker.js');assert.equal(l.workers[0].message.type,'folder'); + assert.equal(l.element('ce-files-input').disabled,true);assert.equal(l.run('canPlay()'),false); + l.run('mapImport("mcc",[{}])');assert.equal(l.workers.length,1); + await l.workers[0].onmessage({data:{type:'done',files:2,bytes:10}}); + assert.equal(l.releases(),1);assert.equal(l.run('canPlay()'),true);assert.equal(l.element('ce-files-input').disabled,false); +}); +test('CE/MCC cancel waits for cleanup acknowledgement and keeps Xbox import disabled',async()=>{ + for(const family of ['ce','mcc']){ + const l=launcher();l.run(`mapImport('${family}',[{}])`); + assert.equal(l.workers[0].path,family+'-import-worker.js');assert.equal(l.element('image-input').disabled,true); + await l.run('importData({type:"folder",files:[]})');assert.equal(l.workers.length,1); + l.element('map-import-cancel').events.click();assert.equal(l.workers[0].message.type,'cancel'); + assert.equal(l.workers[0].stopped,undefined);assert.equal(l.run('canPlay()'),false); + l.workers[0].onmessage({data:{type:'error',message:'Import cancelled.'}}); + await new Promise(resolve=>setImmediate(resolve)); + assert.equal(l.workers[0].stopped,true);assert.equal(l.run('canPlay()'),true); + } +}); +test('busy cross-tab guard refuses Xbox/mod imports and delete without changing data',async()=>{ + const l=launcher();l.busy(true); + await l.run('importData({type:"folder",files:[]})');await l.run('modTask({type:"remove",name:"test"})'); + await l.element('delete-data').events.click(); + assert.equal(l.workers.length,0);assert.deepEqual(l.deleted,[]); + assert.match(l.element('data-status').textContent,/busy/);assert.equal(l.run('canPlay()'),true); +}); +test('uncontended Xbox deletion retains saves and mods retain their original worker',async()=>{ + const l=launcher();await l.element('delete-data').events.click(); + assert.deepEqual(l.deleted,['maps','save/z/cache000.map']);assert.equal(l.releases(),1); + await l.run('modTask({type:"add",files:[]})');assert.equal(l.workers[0].path,'mods-worker.js'); + assert.equal(l.run('canPlay()'),false); + await l.workers[0].onmessage({data:{type:'done',name:'test',files:1,bytes:1}}); + assert.equal(l.run('canPlay()'),true);assert.equal(l.releases(),2); +}); +test('worker construction failure releases guard; rejected game startup does not hang Play',async()=>{ + const l=launcher();l.failWorker();await l.run('importData({type:"folder",files:[]})'); + assert.equal(l.releases(),1);assert.equal(l.run('canPlay()'),true); + l.busy(true);await l.run('play()');assert.equal(l.run('gameStarted'),false); + assert.equal(l.run('canPlay()'),true);assert.match(l.element('play-note').textContent,/busy/); +}); +test('unsupported Web Locks fail the existing browser capability check',async()=>{ + const l=launcher();l.context.navigator.locks=null; + l.run('workerWebGL2=async()=>true; memoryAvailable=()=>true;'); + assert.equal(await l.run('runChecks()'),false);assert.equal(l.run('results.locks'),'bad'); +}); diff --git a/port/web/tests/map-import.test.js b/port/web/tests/map-import.test.js new file mode 100644 index 0000000000..c5b179ace7 --- /dev/null +++ b/port/web/tests/map-import.test.js @@ -0,0 +1,137 @@ +'use strict'; +const test = require('node:test'); +const assert = require('node:assert/strict'); +const zlib = require('node:zlib'); +const ce = require('../site/ce-import-worker.js'); +const mcc = require('../site/mcc-import-worker.js'); +const paths = require('../site/map-import-files.js'); + +function file(path, bytes) { + const result = new Blob([bytes]); + result.name = path.split('/').pop(); + result.webkitRelativePath = path.includes('/') ? path : ''; + return result; +} +function cache(version = 13, type = 0) { + const b = Buffer.alloc(2088); + b.writeUInt32LE(0x68656164, 0); b.writeUInt32LE(version, 4); + b.writeUInt32LE(b.length, 8); b.writeUInt32LE(2048, 16); + b.writeUInt32LE(40, 20); b.writeUInt16LE(type, 0x60); + b.writeUInt32LE(0x666f6f74, 0x7fc); + return b; +} +function resource(type) { + const b = Buffer.alloc(28); b.writeUInt32LE(type); + b.writeUInt32LE(16, 4); b.writeUInt32LE(16, 8); b.writeUInt32LE(1, 12); + return b; +} +function crc(b) { + let n = 0xffffffff; + for (const value of b) { + n ^= value; + for (let i = 0; i < 8; i++) n = n & 1 ? 0xedb88320 ^ (n >>> 1) : n >>> 1; + } + return (n ^ 0xffffffff) >>> 0; +} +function image(raw = Buffer.from([0, 1, 2, 3, 4])) { + function chunk(kind, data) { + const b = Buffer.alloc(data.length + 12); + b.writeUInt32BE(data.length); b.write(kind, 4); data.copy(b, 8); + b.writeUInt32BE(crc(b.subarray(4, -4)), b.length - 4); return b; + } + const header = Buffer.alloc(13); header.writeUInt32BE(1); header.writeUInt32BE(1, 4); + header[8] = 8; header[9] = 6; + return Buffer.concat([Buffer.from([137,80,78,71,13,10,26,10]), chunk('IHDR', header), + chunk('IDAT', zlib.deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]); +} +function metadata(info = {}, extras = []) { + return [file('pkg/ModInfo.json', JSON.stringify({ Engine: 'Halo1', ...info })), + file('pkg/maps/first.map', cache()), ...extras]; +} +const names = plan => plan.entries.map(e => e.path).sort(); + +test('CE cache and resource headers stay separate from MCC and Xbox', async () => { + const plan = await ce.plan([file('ce/arena.map', cache(609, 1)), ...['bitmaps','sounds','loc'].map((n,i) => file('ce/' + n + '.map', resource(i + 1)))]); + assert.equal(plan.family, 'ce'); assert.equal(plan.folder, ''); + assert.deepEqual(names(plan), ['arena.map','bitmaps.map','loc.map','sounds.map']); + for (const version of [5, 7, 13]) await assert.rejects(ce.plan([file('a.map', cache(version))]), /header/); + await assert.rejects(mcc.plan([file('pkg/a.map', cache(609))]), /header/); + await assert.rejects(ce.plan([file('bitmaps.map', resource(2))]), /resource/); +}); +test('CE accepts inert OpenSauce marker but refuses required features and compression', async () => { + const b = cache(609, 1); b.writeUInt32LE(0x79656c6f, 0x70); + await ce.plan([file('a.map', b)]); + b.writeUInt16LE(1, 0x76); await assert.rejects(ce.plan([file('a.map', b)]), /OpenSauce/); + b.writeUInt16LE(0, 0x76); b.writeUInt32LE(1, 12); + await assert.rejects(ce.plan([file('a.map', b)]), /Compressed/); +}); +test('bounded headers reject corrupt offsets, sizes, strings and resource tables', async () => { + for (const mutate of [b => b.writeUInt32LE(0, 16), b => b.writeUInt32LE(41,20), + b => b.writeUInt32LE(4096,8), b => b.fill(65,0x20,0x40), b => b.writeUInt16LE(2,0x60), b => b.writeUInt32LE(0,0x7fc)]) { + const b = cache(); mutate(b); await assert.rejects(mcc.plan([file('pkg/a.map',b)]), /header/); + } + const r = resource(1); r.writeUInt32LE(0xffffffff,12); + await assert.rejects(ce.plan([file('bitmaps.map',r)]), /resource/); + await assert.rejects(ce.plan([file('a.map',Buffer.alloc(100))]), /Truncated/); +}); +test('map-only local MCC packages need neither JSON nor Workshop attribution', async () => { + const plan = await mcc.plan([file('Local/halo1/maps/first.map',cache()),file('Local/readme.txt','ignored')]); + assert.equal(plan.folder,'local'); assert.deepEqual(names(plan),['first.map']); +}); +test('Workshop flattening preserves required JSON bytes and long numeric identity', async () => { + const raw = '{"Engine":"Halo1","ModIdentifier":{"HostedModIds":{"SteamWorkshopId":12345678901234567890}},"Title":{"Neutral":"Title"}}'; + const plan = await mcc.plan([file('pkg/ModInfo.json',raw),file('pkg/halo1/maps/first.map',cache())]); + assert.equal(plan.folder,'12345678901234567890'); + assert.equal(await plan.entries.find(e=>e.path==='modinfo.json').file.text(),raw); + assert.equal(await plan.entries.find(e=>e.path==='workshop_id.txt').file.text(),'12345678901234567890\nTitle\n'); +}); +test('all campaign metadata and selected folder mission files coexist with MP metadata', async () => { + const inputs = metadata({ GameModContents:{HasCampaign:true,MultiplayerMaps:['Meta/arena.json']} },[ + file('pkg/CampaignInfo.json','{"CampaignMaps":["Meta/first.json","Meta/second.json"]}'), + file('pkg/Meta/first.json','{"ScenarioFile":"levels/first","Images":{"Thumbnail":"previews/first.png"}}'), + file('pkg/Meta/second.json','{"ScenarioFile":"second.map"}'), + file('pkg/Meta/arena.json','{"ScenarioFile":"arena"}'), + file('pkg/maps/second.map',cache()), file('pkg/maps/arena.map',cache(13,1)), + file('pkg/previews/first.png',image()), file('pkg/unreferenced.json','invalid'),file('pkg/unused.png',image())]); + const plan = await mcc.plan(inputs); + assert.deepEqual(names(plan),['arena.map','campaigninfo.json','first.map','meta/arena.json','meta/first.json','meta/second.json','modinfo.json','previews/first.png','second.map']); +}); +test('required malformed, missing, unsafe and wrong-type mission metadata refuses import', async () => { + for (const record of ['{','{"ScenarioFile":"missing"}','{"ScenarioFile":"../first"}','{"ScenarioFile":"first","CampaignMapKind":"Cutscene"}']) { + await assert.rejects(mcc.plan(metadata({GameModContents:{HasCampaign:true}},[ + file('pkg/CampaignInfo.json','{"CampaignMaps":["first.json"]}'),file('pkg/first.json',record)]))); + } + await assert.rejects(mcc.plan(metadata({GameModContents:{HasCampaign:true}})), /required JSON/); + await assert.rejects(mcc.plan(metadata({GameModContents:{MultiplayerMaps:['first.json']}},[ + file('pkg/first.json','{"ScenarioFile":"first"}') ])), /mission type/); + await assert.rejects(mcc.plan(metadata({GameModContents:{MultiplayerMaps:['méta.json']}},[ + file('pkg/méta.json','{}') ])), /Unsafe/); +}); +test('optional invalid, nonportable and missing PNGs leave placeholders', async () => { + for (const [path,data] of [['bad.png',Buffer.from('bad')],['é.png',image()],['missing.png',null],['con.png',image()]]) { + const plan = await mcc.plan(metadata({Images:{Thumbnail:path}},data ? [file('pkg/'+path,data)] : [])); + assert.deepEqual(names(plan),['first.map','modinfo.json']); + } + assert.equal(await mcc.png(file('good.png',image())),true); + for (const raw of [Buffer.from([5,1,2,3,4]),Buffer.alloc(100),Buffer.alloc(4)]) assert.equal(await mcc.png(file('bad.png',image(raw))),false); + const corrupt=image();corrupt[30]^=1;assert.equal(await mcc.png(file('bad.png',corrupt)),false); +}); +test('portable aliases, reserved downloaded names and flatten collisions are refused', async () => { + for (const name of ['DL_0123456789abcdef0123','con','a/b','../foo','é']) assert.throws(()=>mcc.packageName(name)); + for (const path of ['../x','a//x','a/COM1.json','a/b.','a/b:ads','/a']) assert.throws(()=>paths.path(path)); + await assert.rejects(mcc.plan([file('pkg/maps/a.map',cache()),file('pkg/a.map',cache())]),/Conflicting/); + await assert.rejects(ce.plan([file('one/A.map',cache(609)),file('two/a.map',cache(609))]),/Conflicting/); + await assert.rejects(mcc.plan(metadata({},[file('pkg/MODINFO.JSON','{}')])),/case-conflicting/); +}); +test('strict bounded JSON rejects ambiguous keys, invalid UTF8 and deep or malformed input', async () => { + for (const raw of ['{"a":1,"a":2}','{"a":1,}','{"a":[1,]}','{"a":"\\u0000"}','{}x','[]','123', + '{"a":'+ '['.repeat(18)+'0'+']'.repeat(18)+'}', '{"a":01}', '{"a":"\\z"}']) assert.throws(()=>mcc.parseJson(raw)); + await assert.rejects(mcc.plan([file('pkg/modinfo.json',Buffer.from([0xff])),file('pkg/a.map',cache())])); + await assert.rejects(mcc.plan([file('pkg/modinfo.json',' '.repeat(256*1024+1)),file('pkg/a.map',cache())]),/oversized/); + assert.throws(()=>mcc.parseJson('{'+Array.from({length:16384},(_,i)=>'"'+i+'":0').join(',')+'}'),/token limit/); + for(const content of [null,[],true,1,{HasCampaign:'true'}]) await assert.rejects(mcc.plan(metadata({GameModContents:content})),/Invalid/); + for (let i=0;i<128;i++) { + const raw='{"Engine":"Halo1","a":[true,false,null]}'; + assert.throws(()=>mcc.parseJson(raw.slice(0,i%raw.length)+'\0'+raw.slice(i%raw.length))); + } +}); diff --git a/port/web/tests/map_import.mjs b/port/web/tests/map_import.mjs new file mode 100644 index 0000000000..540f1f6aca --- /dev/null +++ b/port/web/tests/map_import.mjs @@ -0,0 +1,101 @@ +// Real File selection, import workers, Web Locks and persistent OPFS. Synthetic +// cache headers prove import/storage behavior; they are not playable maps. +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import http from 'node:http'; +import os from 'node:os'; +import path from 'node:path'; +import { createRequire } from 'node:module'; +import { fileURLToPath } from 'node:url'; +const require=createRequire(import.meta.url),playwright=require('playwright'); +const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'../../..'); +const work=await fs.mkdtemp(path.join(os.tmpdir(),'halo-map-import-')); +const engines=process.argv.slice(2);if(!engines.length)engines.push('chromium','firefox'); +assert(engines.every(e=>['chromium','firefox'].includes(e))); +const reports=[];let server,browser; +function cache(version,type=0,size=2088){ + const b=Buffer.alloc(size);b.writeUInt32LE(0x68656164,0);b.writeUInt32LE(version,4); + b.writeUInt32LE(size,8);b.writeUInt32LE(2048,16);b.writeUInt32LE(40,20); + b.writeUInt16LE(type,0x60);b.writeUInt32LE(0x666f6f74,0x7fc);return b; +} +const pageText=` + +`; +try{ + await fs.mkdir(path.join(work,'package','maps'),{recursive:true}); + await fs.writeFile(path.join(work,'arena.map'),cache(609,1)); + await fs.writeFile(path.join(work,'package','maps','first.map'),cache(13)); + await fs.writeFile(path.join(work,'package','ModInfo.json'),JSON.stringify({Engine:'Halo1',GameModContents:{HasCampaign:true}})); + await fs.writeFile(path.join(work,'package','CampaignInfo.json'),' {"CampaignMaps":["first.json"]}\n'); + await fs.writeFile(path.join(work,'package','first.json'),'{"ScenarioFile":"first","Images":{"Thumbnail":"invalid.png"}}'); + await fs.writeFile(path.join(work,'package','invalid.png'),'not a PNG'); + await fs.mkdir(path.join(work,'cancel'));await fs.writeFile(path.join(work,'cancel','large.map'),cache(13,0,4*1024*1024)); + const assets=new Set(['map-import-storage.js','map-import-files.js','map-storage-worker.js','ce-import-worker.js','mcc-import-worker.js']); + server=http.createServer(async(request,response)=>{ + const name=new URL(request.url,'http://localhost').pathname.slice(1); + if(name==='index.html')response.writeHead(200,{'Content-Type':'text/html'}).end(pageText); + else if(assets.has(name))response.writeHead(200,{'Content-Type':'text/javascript'}).end(await fs.readFile(path.join(root,'port/web/site',name))); + else response.writeHead(404).end(); + }); + await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve)); + const url=`http://127.0.0.1:${server.address().port}/index.html`; + for(const engine of engines){ + browser=await playwright[engine].launch({headless:true});const context=await browser.newContext(); + const page=await context.newPage(),errors=[];page.on('pageerror',e=>errors.push(String(e))); + await page.goto(url);await page.locator('#ce').setInputFiles(path.join(work,'arena.map')); + let result=await page.evaluate(()=>runImport('ce'));assert.equal(result.type,'done',JSON.stringify(result)); + await page.locator('#mcc').setInputFiles(path.join(work,'package')); + result=await page.evaluate(()=>runImport('mcc','campaign'));assert.equal(result.type,'done',JSON.stringify(result)); + const installed=await page.evaluate(()=>contents()); + assert.deepEqual(Object.keys(installed).sort(),['custom_maps/arena.map','mcc_maps/campaign/campaigninfo.json','mcc_maps/campaign/first.json','mcc_maps/campaign/first.map','mcc_maps/campaign/modinfo.json','mcc_transactions/campaign.commit']); + for(const[destination,relative]of [['custom_maps/arena.map','arena.map'],['mcc_maps/campaign/first.map','package/maps/first.map'],['mcc_maps/campaign/campaigninfo.json','package/CampaignInfo.json'],['mcc_maps/campaign/first.json','package/first.json'],['mcc_maps/campaign/modinfo.json','package/ModInfo.json']]){ + const bytes=await fs.readFile(path.join(work,relative)); + assert.equal(installed[destination].sha,require('node:crypto').createHash('sha256').update(bytes).digest('hex')); + } + result=await page.evaluate(()=>runImport('mcc','campaign'));assert.equal(result.type,'error');assert.match(result.message,/already exists/); + assert.deepEqual(await page.evaluate(()=>contents()),installed); + await page.reload();assert.deepEqual(await page.evaluate(()=>contents()),installed); + await page.locator('#mcc').setInputFiles(path.join(work,'cancel')); + result=await page.evaluate(()=>runImport('mcc','cancelled',true));assert.equal(result.type,'error',JSON.stringify(result));assert.match(result.message,/cancelled/); + assert.deepEqual(await page.evaluate(()=>contents()),installed); + await page.evaluate(()=>HaloMapStorage.startGame()); + const other=await context.newPage();await other.goto(url);await other.evaluate(()=>HaloMapStorage.startGame()); + await other.locator('#ce').setInputFiles(path.join(work,'arena.map')); + result=await other.evaluate(()=>runImport('ce'));assert.equal(result.type,'error');assert.match(result.message,/busy/); + assert.deepEqual(await other.evaluate(()=>contents()),installed); + assert.deepEqual(errors,[]); + reports.push({engine,version:browser.version(),cases:['ce-import','mcc-campaign-import-raw-byte-hashes','invalid-preview-placeholder','no-overwrite','reload-preserved','cancel-cleanup','two-shared-games-import-refused'],files:installed,errors}); + console.log(engine+': manual CE/MCC import, persistence, cancellation and shared guards passed'); + await context.close();await browser.close();browser=null; + } +}finally{ + if(browser)await browser.close();if(server)await new Promise(resolve=>server.close(resolve)); + if(process.env.WEB_MAP_IMPORT_RESULTS)await fs.writeFile(process.env.WEB_MAP_IMPORT_RESULTS,JSON.stringify({cases:reports},null,2)+'\n'); + assert.equal(await fs.realpath(work),path.resolve(work));await fs.rm(work,{recursive:true,force:true}); +} diff --git a/port/web/tests/map_memory.mjs b/port/web/tests/map_memory.mjs new file mode 100644 index 0000000000..0d4d7a3691 --- /dev/null +++ b/port/web/tests/map_memory.mjs @@ -0,0 +1,93 @@ +// Run the same production allocator fixture in real browser workers and Node +// (tools/test_web_map_memory.py). No game data or game process is involved. +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import fs from 'node:fs/promises'; +import http from 'node:http'; +import { createRequire } from 'node:module'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const require = createRequire(import.meta.url); +const playwright = require('playwright'); +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../..'); +const engines = process.argv.slice(2); +if (!engines.length) engines.push('chromium', 'firefox'); +assert(engines.every(name => name === 'chromium' || name === 'firefox'), 'expected chromium or firefox'); +const work = await fs.mkdtemp(path.join(os.tmpdir(), 'halo-map-memory-')); +const cases = [ + { name: 'small', bytes: 0x01000000, expected: 'insufficient map-window memory refused' }, + { name: 'full', bytes: 0x88000000, expected: 'map windows preserved' }, +]; +const reports = []; +let server; +let browser; +try { + for (const item of cases) { + const folder = path.join(work, item.name); + await fs.mkdir(folder); + const compiled = spawnSync(process.env.WEB_EMCC || 'emcc', [ + 'port/web/tests/map_memory_test.c', 'port/web/src/web_memory.c', + '-Iport/web/src', '-Iport/linux/src', '-DHALO_WEB=1', '-std=gnu89', '-O2', '-pthread', + '-sPROXY_TO_PTHREAD=1', '-sPTHREAD_POOL_SIZE=5', '-sALLOW_MEMORY_GROWTH=0', '-sABORTING_MALLOC=0', + '-sEXIT_RUNTIME=1', '-sENVIRONMENT=web,worker', `-sINITIAL_MEMORY=${item.bytes}`, + '-o', path.join(folder, 'memory.js'), + ], { cwd: root, encoding: 'utf8', timeout: 120000 }); + assert.equal(compiled.status, 0, String(compiled.error || '') + compiled.stdout + compiled.stderr); + await fs.writeFile(path.join(folder, 'index.html'), ` +`); + } + server = http.createServer(async (request, response) => { + const match = /^\/(small|full)\/(index\.html|memory\.(?:js|wasm))$/.exec(request.url); + if (!match) { response.writeHead(404).end(); return; } + try { + const data = await fs.readFile(path.join(work, match[1], match[2])); + response.writeHead(200, { + 'Content-Type': match[2].endsWith('.wasm') ? 'application/wasm' : + match[2].endsWith('.js') ? 'text/javascript' : 'text/html', + 'Cross-Origin-Opener-Policy': 'same-origin', + 'Cross-Origin-Embedder-Policy': 'require-corp', + }).end(data); + } catch { response.writeHead(404).end(); } + }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + for (const name of engines) { + browser = await playwright[name].launch({ headless: true }); + for (const item of cases) { + const page = await browser.newPage(); + const pageErrors = []; + page.on('pageerror', error => pageErrors.push(String(error))); + await page.goto(`http://127.0.0.1:${server.address().port}/${item.name}/index.html`); + await page.waitForFunction(() => window.result?.exit !== null, null, { timeout: 90000 }); + const result = await page.evaluate(() => ({ ...window.result, isolated: crossOriginIsolated, + userAgent: navigator.userAgent })); + reports.push({ engine: name, version: browser.version(), memory: item.bytes, ...result, pageErrors }); + assert.equal(result.isolated, true); + assert.equal(result.exit, 0, JSON.stringify(reports.at(-1))); + assert(result.output.some(line => line.includes(item.expected)), JSON.stringify(reports.at(-1))); + assert.deepEqual(result.errors, []); + assert.deepEqual(pageErrors, []); + console.log(`${name} ${browser.version()}: ${result.output.join('; ')}`); + await page.close(); + } + await browser.close(); + browser = null; + } +} finally { + if (browser) await browser.close(); + if (server) await new Promise(resolve => server.close(resolve)); + if (process.env.WEB_MEMORY_RESULTS) await fs.writeFile(process.env.WEB_MEMORY_RESULTS, + JSON.stringify({ cases: reports }, null, 2) + '\n'); + // Only this process's newly created fixture directory is removed. + assert.equal(await fs.realpath(work), path.resolve(work)); + await fs.rm(work, { recursive: true, force: true }); +} diff --git a/port/web/tests/map_memory_test.c b/port/web/tests/map_memory_test.c new file mode 100644 index 0000000000..a8c497e726 --- /dev/null +++ b/port/web/tests/map_memory_test.c @@ -0,0 +1,122 @@ +/* Exercise the real Wasm allocator and map-window implementation. */ +#include +#include +#include +#include +#include +#include +#include +#include "web_memory.h" + +/* mcc_memory only needs platform declarations on native builds. */ +#define __HALO_LINUX_PLATFORM_H +#include "../../linux/src/mcc_memory.c" + +static int ce_enabled; +static unsigned settings_reads; +int config_boolean(const char *name) +{ + if (strcmp(name, "game.custom_edition")) abort(); + ++settings_reads; + return ce_enabled; +} + +#define CHECK(c) do { if (!(c)) { fprintf(stderr, "memory check failed at %d\n", __LINE__); return 1; } } while (0) +#define WORKERS 4 +#define BLOCKS 40 +#define BLOCK_BYTES (32u * 1024u * 1024u) +static void *blocks[WORKERS][BLOCKS]; +static unsigned counts[WORKERS]; +/* Keep the deliberate failed allocation observable even when LLVM can elide + * an unused malloc/free pair. */ +static void *(*volatile allocate_bytes)(size_t) = malloc; + +static void *allocate(void *argument) +{ + unsigned worker = (unsigned)(uintptr_t)argument; + unsigned i; + for (i = 0; i < BLOCKS; ++i) { + unsigned char *p = malloc(BLOCK_BYTES); + if (!p) break; + blocks[worker][i] = p; + ++counts[worker]; + p[0] = (unsigned char)worker; + p[BLOCK_BYTES - 1] = (unsigned char)i; + } + return NULL; +} + +int main(void) +{ + unsigned char *ce = (void *)CUSTOM_EDITION_TAG_CACHE_ADDRESS; + unsigned char *xbox = (void *)0x80000000u; + unsigned char *tags; + pthread_t workers[WORKERS]; + unsigned i, j, count = 0; + void *before; + + CHECK(!settings_reads && !web_custom_edition_tag_cache()); + ce_enabled = 1; + web_memory_initialize(); + CHECK(settings_reads == 1); + if (web_memory_bytes() < 0x88000000u) { + CHECK(!web_custom_edition_tag_cache()); + CHECK(!mcc_memory_reserve(0x50000000u, 0x04000000u) && errno == ENOMEM); + puts("PASS: insufficient map-window memory refused"); + return 0; + } + CHECK(web_custom_edition_tag_cache() == ce); + ce_enabled = 0; + web_memory_initialize(); + CHECK(!web_custom_edition_tag_cache()); + ce_enabled = 1; + web_memory_initialize(); + CHECK(web_custom_edition_tag_cache() == ce); + ce[0] = 0xA5; + ce[CUSTOM_EDITION_TAG_CACHE_BYTES - 1] = 0x5A; + xbox[0] = 0x3C; + xbox[0x08000000u - 1] = 0xC3; + CHECK(!mcc_memory_reserve(0x40440000u, 0x04000000u) && errno == EINVAL); + CHECK(!mcc_memory_reserve(0x50000001u, 0x04000000u) && errno == EINVAL); + CHECK(!mcc_memory_reserve(0x50000000u, 0x04000001u) && errno == EINVAL); + CHECK(!mcc_memory_reserve(0x71000000u, 0x04000000u) && errno == EINVAL); + tags = mcc_memory_reserve(0x50000000u, 0x04000000u); + CHECK(tags == (void *)0x50000000u && !tags[0] && !tags[0x03FFFFFF]); + tags[0] = 77; + tags[0x03FFFFFF] = 88; + CHECK(!mcc_memory_reserve(0x60000000u, 0x04000000u) && errno == EBUSY); + mcc_memory_release(tags, 1); + mcc_memory_release((void *)0x60000000u, 0x04000000u); + mcc_memory_release(NULL, 0); + CHECK(!mcc_memory_reserve(0x50000000u, 0x04000000u) && errno == EBUSY); + mcc_memory_release(tags, 0x04000000u); + tags = mcc_memory_reserve(0x50000000u, 0x04000000u); + CHECK(tags && !tags[0] && !tags[0x03FFFFFF]); + mcc_memory_release(tags, 0x04000000u); + tags = mcc_memory_reserve(0x70000000u, 0x04000000u); + CHECK(tags == (void *)0x70000000u); + mcc_memory_release(tags, 0x04000000u); + + before = sbrk(0); + CHECK(sbrk((intptr_t)(WEB_HEAP_LIMIT - (uintptr_t)before + 65536u)) == (void *)-1); + CHECK(sbrk(0) == before); + CHECK(!allocate_bytes(0x50000000u)); + for (i = 0; i < WORKERS; ++i) + CHECK(!pthread_create(&workers[i], NULL, allocate, (void *)(uintptr_t)i)); + for (i = 0; i < WORKERS; ++i) CHECK(!pthread_join(workers[i], NULL)); + for (i = 0; i < WORKERS; ++i) { + CHECK(counts[i] < BLOCKS); + for (j = 0; j < counts[i]; ++j) { + unsigned char *p = blocks[i][j]; + CHECK((uintptr_t)p < WEB_HEAP_LIMIT && BLOCK_BYTES <= WEB_HEAP_LIMIT - (uintptr_t)p); + CHECK(p[0] == i && p[BLOCK_BYTES - 1] == j); + free(p); + ++count; + } + } + CHECK(count >= 4); + CHECK(ce[0] == 0xA5 && ce[CUSTOM_EDITION_TAG_CACHE_BYTES - 1] == 0x5A); + CHECK(xbox[0] == 0x3C && xbox[0x08000000u - 1] == 0xC3); + printf("PASS: map windows preserved across %u concurrent heap blocks and exhaustion\n", count); + return 0; +} diff --git a/port/web/tests/smoke.mjs b/port/web/tests/smoke.mjs index c45551b8c0..8b18500fa4 100644 --- a/port/web/tests/smoke.mjs +++ b/port/web/tests/smoke.mjs @@ -43,6 +43,19 @@ try { route.fulfill({ contentType: 'text/javascript', body: '', headers: { 'Access-Control-Allow-Origin': '*' } })); page.on('console', (message) => log.push(message.text())); page.on('pageerror', (error) => log.push('page error: ' + error)); + // Connected controllers are polled before the game clock is initialized. + // Keep both neutral: this checks real startup, without changing bindings. + await page.addInitScript(() => { + const pads = [0, 1].map((index) => ({ + id: `Startup test controller ${index}`, index, connected: true, + mapping: 'standard', timestamp: 0, axes: [0, 0, 0, 0], + buttons: Array.from({ length: 17 }, () => ({ pressed: false, touched: false, value: 0 })), + })); + Object.defineProperty(navigator, 'getGamepads', { value: () => { + for (const pad of pads) pad.timestamp = performance.now(); + return pads; + } }); + }); await page.goto(url); await page.waitForFunction(() => window.crossOriginIsolated && document.querySelectorAll('#checks li').length >= 5, @@ -73,6 +86,10 @@ try { if (!log.some((line) => /data root: \/data/.test(line))) fail('the game did not mount the storage at /data'); if (!log.some((line) => /OpenGL ES 3\.0 \(WebGL 2/.test(line))) fail('the game did not set up WebGL 2'); if (!log.some((line) => /couldn't find map 'ui'/.test(line))) fail('the game did not get as far as the maps'); + for (const index of [0, 1]) { + if (!log.some((line) => line.includes(`gamepad: Startup test controller ${index}`))) + fail(`the game did not poll controller ${index}`); + } if (!(await page.isHidden('#fatal'))) fail('the game stopped: ' + (await page.textContent('#fatal-text'))); console.log('the game started and looked for its maps'); } catch (error) { diff --git a/port/windows/src/win32_memory_watch.c b/port/windows/src/win32_memory_watch.c index 7b8376b0d3..c31b7c9b94 100644 --- a/port/windows/src/win32_memory_watch.c +++ b/port/windows/src/win32_memory_watch.c @@ -83,18 +83,32 @@ void memory_watch_protect(unsigned long address, unsigned long size) if (!watch_active || !size || !in_window(address)) return; first = page_index(address); + /* Clamp before adding: the caller's range must not wrap around. */ + if (size > PLATFORM_CONTIGUOUS_SIZE - (address - PLATFORM_CONTIGUOUS_BASE)) + size = PLATFORM_CONTIGUOUS_SIZE - (address - PLATFORM_CONTIGUOUS_BASE); last = page_index(address + size - 1); - if (last >= WATCH_PAGE_COUNT) - last = WATCH_PAGE_COUNT - 1; for (page = first; page <= last; page++) { if (page_protected[page] != 1) { + unsigned long begin = page, retry; DWORD previous; - page_protected[page] = 1; - VirtualProtect((void *)(PLATFORM_CONTIGUOUS_BASE + page * WATCH_PAGE_SIZE), WATCH_PAGE_SIZE, - PAGE_READONLY, &previous); + /* A texture commonly spans hundreds of adjacent pages. One + * protection change avoids a kernel call and TLB update per page. + * Publish the watch first so a concurrent write is still caught. + * Separate reservations cannot be protected together on Windows; + * retain the per-page path if the combined request fails. */ + while (page <= last && page_protected[page] != 1) + page_protected[page++] = 1; + if (!VirtualProtect((void *)(PLATFORM_CONTIGUOUS_BASE + begin * WATCH_PAGE_SIZE), + (page - begin) * WATCH_PAGE_SIZE, PAGE_READONLY, &previous)) + { + for (retry = begin; retry < page; retry++) + VirtualProtect((void *)(PLATFORM_CONTIGUOUS_BASE + retry * WATCH_PAGE_SIZE), + WATCH_PAGE_SIZE, PAGE_READONLY, &previous); + } + page--; } } } diff --git a/source/ai/path.c b/source/ai/path.c index fd2e78cfb6..a1df3a9d89 100644 --- a/source/ai/path.c +++ b/source/ai/path.c @@ -1855,4 +1855,15 @@ boolean path_state_find( return result; } +/* port: A bot worker supplies a private graph snapshot, with breakage +already applied and no debug storage. Keep profiling and live-world debug +queries on the game thread; the established path_state_find is unchanged. +Used by port/linux/game/bots_worker.inl. */ +void bots_path_find_snapshot(struct path_state *state) +{ + path_state_reset(state); + if (path_state_begin(state)) + path_state_traverse(state); +} + /* ---------- private code */ diff --git a/source/cache/cache_files.c b/source/cache/cache_files.c index c0adae17b2..c981f60061 100644 --- a/source/cache/cache_files.c +++ b/source/cache/cache_files.c @@ -609,6 +609,11 @@ char const *cache_files_map_directory( void scenario_tags_unload( void) { + /* port: forget draw-only shield copies before any map tags go away. */ + { + extern void shield_look_reset(void); /* port/linux/game/shield_look.c */ + shield_look_reset(); + } /* port: the high-res HUD forgets this map's bitmaps (port/linux/game/hud_hires_tags.c) */ { extern void hud_hires_tags_unloaded(void); @@ -617,6 +622,11 @@ void scenario_tags_unload( } sound_cache_close(); texture_cache_close(); + /* port: shield sprite assets unwind before other appended tag tables. */ + { + extern void shield_arcs_unload(void); /* port/linux/game/shield_arcs.inl */ + shield_arcs_unload(); + } /* port: the mods' tags go, after the sound and texture caches that held their sounds and bitmaps (port/linux/game/mods.c) */ { @@ -1226,7 +1236,11 @@ boolean cache_files_give_time_to_precache( short status = cache_files_precache_map_status(&progress); if (status == 2) - display_error_damaged_media(); + { + /* port: CE explains its refusal without changing the fatal path. */ + if (!custom_edition_cache_display_error(map_name)) + display_error_damaged_media(); + } else if (status == 1) cache_files_precache_map_end(); } @@ -1234,7 +1248,11 @@ boolean cache_files_give_time_to_precache( { cache_files_precache_set_priority(0); if (!cache_files_precache_map_begin(map_name, FALSE)) - display_error_damaged_media(); + { + /* port: Xbox retains its fixed error; CE supplies its own text. */ + if (!custom_edition_cache_display_error(map_name)) + display_error_damaged_media(); + } } } @@ -1249,6 +1267,11 @@ long scenario_tags_load( void *tag_cache_base_address; boolean read_complete; + /* port: a failed or different map load must not inherit shield eligibility. */ + { + extern void shield_look_reset(void); /* port/linux/game/shield_look.c */ + shield_look_reset(); + } stripped_scenario_name = tag_name_strip_path(scenario_name); result = NONE; /* port: the map being loaded, by its name (cache_file_loaded_map_name) */ @@ -1282,6 +1305,11 @@ long scenario_tags_load( { sound_cache_close(); texture_cache_close(); + /* port: shield sprite assets unwind before other appended tag tables. */ + { + extern void shield_arcs_unload(void); /* port/linux/game/shield_arcs.inl */ + shield_arcs_unload(); + } } return result; } diff --git a/source/cache/cache_files_windows.c b/source/cache/cache_files_windows.c index 4933bb1fc0..de367c67cd 100644 --- a/source/cache/cache_files_windows.c +++ b/source/cache/cache_files_windows.c @@ -621,7 +621,8 @@ boolean cache_files_precache_map_begin( error(_error_silent, "couldn't find the Custom Edition map '%s' in custom_maps", map_name); if (copy_map) { - display_error_damaged_media(); + /* port: same fatal screen, with the CE refusal explained. */ + custom_edition_cache_display_error(map_name); } return FALSE; diff --git a/source/cache/xbox_texture_cache.c b/source/cache/xbox_texture_cache.c index 89530c425f..263a244dda 100644 --- a/source/cache/xbox_texture_cache.c +++ b/source/cache/xbox_texture_cache.c @@ -695,6 +695,15 @@ static void texture_cache_initialize_hardware_format( return; } +/* port: loading-only preparation reuses the native descriptor contract without + * fetching pixels. MCC descriptors remain owned by mcc_texture_cache_get. */ +int texture_cache_prepare_descriptor(struct bitmap_data *bitmap, void *header) +{ + if (!texture_cache_bitmap_valid(bitmap)) return FALSE; + texture_cache_initialize_hardware_format(bitmap, (D3DBaseTexture *)header); + return TRUE; +} + static void render_inverse_transform_screen_point( real_point2d const *screen_position, real_point3d *world_position, @@ -1090,6 +1099,8 @@ void *_texture_cache_bitmap_get_hardware_format( "c:\\halo\\SOURCE\\cache\\xbox_texture_cache.c", 210, load || !block); + /* port: metadata only during the optional loading pass, never gameplay. */ + if (material_prepare_bitmap(bitmap, &hardware_format)) return hardware_format; #ifdef HALO_ANDROID /* port: CE's frame working set is not bounded by the Xbox texture arena. * Keep dynamic textures and both other map families on their own paths. */ diff --git a/source/camera/director.c b/source/camera/director.c index 4246d0c117..d1682da8b8 100644 --- a/source/camera/director.c +++ b/source/camera/director.c @@ -148,6 +148,7 @@ extern real_euler_angles2d player_control_port_debug_facing[]; /* network_game_globals.c's */ boolean network_game_distributed_client(void); +#include "third_person.h" /* port: port/linux/game/third_person_director.c */ /* ---------- constants */ @@ -308,6 +309,13 @@ boolean director_inhibited_input( return director_get(local_player_index)->inhibited_input; } +/* port: expose camera identity without exposing mutable director state. */ +boolean director_camera_is(short local_player_index, director_camera_update_proc camera_proc) +{ + return local_player_index >= 0 && local_player_index < MAXIMUM_NUMBER_OF_LOCAL_PLAYERS && + director_get(local_player_index)->camera_proc == camera_proc; +} + /* port: the unit whose motion the camera follows: the player's own in first person or behind it, the one a dead player watches; NONE for a scripted, editor or flying camera. For the sounds' Doppler effect (sound_manager.c). */ @@ -319,6 +327,7 @@ long director_get_followed_unit( if (*director_camera_scripted) return NONE; if (director->camera_proc == (director_camera_update_proc)first_person_camera_update || + director->camera_proc == third_person_camera_update || /* port: shoulder camera follows the same unit */ director->camera_proc == (director_camera_update_proc)following_camera_update) return player_control_get_unit_index(local_player_index); if (director->camera_proc == (director_camera_update_proc)dead_camera_update) @@ -338,6 +347,13 @@ director_perspective director_get_perspective( if (camera->camera_change_pause == 0.f) camera->perspective = 0; } + /* port: report the resolved shoulder view, including collision fallback. */ + else if (camera->camera_proc == third_person_camera_update) + { + camera->perspective = third_person_active(local_player_index) && + third_person_available(local_player_index) ? + _director_perspective_third_person : _director_perspective_first_person; + } else if (camera->camera_proc == following_camera_update) { camera->perspective = 1; @@ -680,6 +696,26 @@ static void director_choose_game_perspective( when the seat's enter/exit state has not changed. */ if (passenger) following = TRUE; + /* port: select the feature-owned on-foot camera without replacing seats, + scripts or debug cameras. Its eye uses the first-person camera data. */ + if (!following && third_person_available(local_player_index) && + (force || director->camera_proc == (director_camera_update_proc)first_person_camera_update || + director->camera_proc == third_person_camera_update)) + { + if (director->camera_proc != third_person_camera_update) + { + first_person_camera_new((struct first_person_camera *)director->camera_data); + director_set_camera(local_player_index, third_person_camera_update, FALSE); + director->camera_change_pause = 0.f; + } + director->seat_state = perspective; + return; + } + if (director->camera_proc == third_person_camera_update) + { + director_set_camera(local_player_index, (director_camera_update_proc)first_person_camera_update, FALSE); + director->camera_change_pause = 0.f; + } if (force || director->seat_state != perspective || passenger != passenger_views[local_player_index]) { @@ -909,6 +945,8 @@ static boolean director_update_controls( if (remapped) switch_camera = controller_remap_camera_cycle((short)player_index, director_camera_switch_fast); if (director->camera_proc != (director_camera_update_proc)first_person_camera_update && + /* port: shoulder view uses gameplay controls, never debug controls. */ + director->camera_proc != third_person_camera_update && director->camera_proc != (director_camera_update_proc)following_camera_update) { @@ -967,6 +1005,8 @@ static boolean director_update_controls( /* port: the passenger follows their aim, never the debug mouse orbit */ if (!passenger_camera_enabled(local_player_index) && ((director->camera_proc != (director_camera_update_proc)first_person_camera_update && + /* port: right mouse remains gameplay input in shoulder view. */ + director->camera_proc != third_person_camera_update && mouse->buttons[1]) || input_key_is_down(_key_tab))) { SET_FLAG(control_flags, _camera_control_forward_bit, diff --git a/source/camera/director.h b/source/camera/director.h index 65af5dd062..ff82906dcf 100644 --- a/source/camera/director.h +++ b/source/camera/director.h @@ -119,6 +119,9 @@ struct director_globals /* ---------- prototypes/DIRECTOR.C */ +/* port: read-only camera identity for feature-owned camera procedures. */ +boolean director_camera_is(short local_player_index, director_camera_update_proc camera_proc); + void director_initialize( void); void director_dispose( diff --git a/source/cutscene/cinematics.c b/source/cutscene/cinematics.c index a373915910..130583ecf7 100644 --- a/source/cutscene/cinematics.c +++ b/source/cutscene/cinematics.c @@ -464,29 +464,18 @@ void cinematic_render( (title->shadow_color & 0x00FFFFFF)); { - /* port: the bounds are for 640 columns: on a wider screen - move them so the edge the text is justified to (its middle, - if centered) keeps its place relative to the screen's sides, - where the Xbox's 4:3 picture had it. Moving the middle of a - right-justified title's box (most chapter titles: a box from - near the left edge) left the text short of the right side. - The justification is draw_string.c's: 0 left, 1 right, - 2 center */ + /* port: use the justified anchor in the authored 640-column + bounds. The box center pulls right-aligned chapter titles + inward on wide screens. Keep the box's width and height. */ static rectangle2d wide_bounds; short anchor; short shift; switch (title->justification) { - case 0: - anchor = title_bounds->x0; - break; - case 1: - anchor = title_bounds->x1; - break; - default: - anchor = (short)((title_bounds->x0 + title_bounds->x1) / 2); - break; + case 0: anchor = title_bounds->x0; break; /* left */ + case 1: anchor = title_bounds->x1; break; /* right */ + default: anchor = (short)((title_bounds->x0 + title_bounds->x1) / 2); break; } shift = (short)(anchor * (halo_screen_width() - 640) / 640); diff --git a/source/effects/contrails.c b/source/effects/contrails.c index 22a1db4ba3..1b267b68ac 100644 --- a/source/effects/contrails.c +++ b/source/effects/contrails.c @@ -143,16 +143,27 @@ static void contrail_add_points( long contrail_index, short contrail_point_count, boolean force); +/* port: age on the emission clock; move every frame. */ static void contrail_update_points( long contrail_index, - real dt); + real dt, + real state_dt); static void contrail_verify( long contrail_index); /* ---------- globals */ +/* port: emission and point aging share a map-local tick clock. */ +static long last_point_game_time = NONE; + /* ---------- public code */ +/* port: point emission and aging do not inherit another state's clock. */ +void contrails_reset_render_state(void) +{ + last_point_game_time = NONE; +} + real contrail_scale_value( real value, real scale, @@ -215,6 +226,7 @@ void contrails_initialize( void contrails_initialize_for_new_map( void) { + contrails_reset_render_state(); /* port: reset the render clock */ data_make_valid(contrail_data); data_make_valid(contrail_point_data); @@ -224,6 +236,7 @@ void contrails_initialize_for_new_map( void contrails_dispose_from_old_map( void) { + contrails_reset_render_state(); /* port: reset the render clock */ data_make_invalid(contrail_point_data); data_make_invalid(contrail_data); @@ -369,12 +382,10 @@ void contrails_update( real dt) { long contrail_index; - /* The native builds update contrails every frame, several frames per - tick (port/linux/game/render_interpolation.c), but objects and their - markers move only on ticks: points due on a frame that ran no tick would - land on the last point, be skipped and be lost. Emit on the first frame - after each tick, for all the time since the last emission. */ - static long last_point_game_time = NONE; + /* port: emit and age points together on the first frame after a tick. + Point states discard elapsed time when changing states; aging every + render frame shortened the 30 Hz trails, especially states shorter + than a tick. Texture animation below still advances every frame. */ real point_dt; /* port: the ticks' own time, a 30th of a second each, as the Xbox's @@ -387,7 +398,7 @@ void contrails_update( speed, as game_frame halves the frame's time. */ if (last_point_game_time != game_time_get()) { - long ticks = game_time_get() - last_point_game_time; + long ticks = (long)((unsigned long)game_time_get() - (unsigned long)last_point_game_time); if (last_point_game_time == NONE || ticks < 1 || ticks > TICKS_PER_SECOND) ticks = 1; @@ -477,17 +488,8 @@ void contrails_update( texture_animation_v = texture_animation_v * contrail->density; contrail->texture_offset_v = texture_animation_v * frame_dt + contrail->texture_offset_v; - /* port: the points age a tick at a time too, as on the Xbox, which - drew a frame a tick: a point's state that ends drops the rest of the - frame's time (contrail_update_points), so each state lasted at least a - tick. A Shade's or a Spirit's points (states of 0.01, 0.05 and 0.005 - seconds) lived four ticks, 133 ms, and aged a frame at a time at 240 - frames a second they lived about half that, the trail half as long. - The points' physics and their states' fades step with them, so at a - high frame rate a point moves and fades once a tick, as on the Xbox, - not on every frame */ - if (point_dt > 0.0f) - contrail_update_points(contrail_index, point_dt); + /* port: zero still initializes newly attached/collision points. */ + contrail_update_points(contrail_index, dt, point_dt); for (instance_index = 0; instance_index < MAXIMUM_CONTRAIL_INSTANCES; @@ -606,14 +608,26 @@ static void contrail_verify( return; } +/* port: age on the emission clock; move every frame. */ static void contrail_update_points( long contrail_index, - real dt) + real dt, + real state_dt) { struct contrail_datum *contrail = contrail_get(contrail_index); struct contrail_definition *definition = contrail_definition_get(contrail->definition_index); long contrail_point_indices[MAXIMUM_CONTRAIL_POINTS]; short instance_index; + /* port: a slow frame may span several ticks. State transitions discard + the remainder of a step, so age each tick separately without stepping + point physics more than once per rendered frame. Zero still initializes + new points and zero-duration transitions. */ + short state_steps = (short)(state_dt * TICKS_PER_SECOND * + (game_players_are_double_speed() ? 2.0f : 1.0f) + 0.5f); + + if (state_steps < 1) + state_steps = 1; + state_dt /= state_steps; for (instance_index = 0; instance_index < MAXIMUM_CONTRAIL_INSTANCES; @@ -626,9 +640,13 @@ static void contrail_update_points( { struct contrail_point_datum *contrail_point = contrail_point_get(contrail_point_index); - if (!TEST_FLAG(contrail_point->flags, _contrail_point_expired_bit)) + short state_step; + + for (state_step = 0; state_step < state_steps && + !TEST_FLAG(contrail_point->flags, _contrail_point_expired_bit); state_step++) { - contrail_point->time = dt * contrail_point->delta + contrail_point->time; + /* port: match state lifetimes to tick-batched point emission. */ + contrail_point->time = state_dt * contrail_point->delta + contrail_point->time; while (contrail_point->delta == 0.0f || contrail_point->time > 1.0f) { diff --git a/source/effects/contrails.h b/source/effects/contrails.h index f1b5b2b143..93c6060a1c 100644 --- a/source/effects/contrails.h +++ b/source/effects/contrails.h @@ -106,4 +106,7 @@ extern struct data_array *contrail_point_data; /* ---------- public code */ +/* port: clear render-only state after a checkpoint load. */ +void contrails_reset_render_state(void); + #endif // __CONTRAILS_H diff --git a/source/effects/effects.c b/source/effects/effects.c index 3ee26fd4c5..424f87f6e6 100644 --- a/source/effects/effects.c +++ b/source/effects/effects.c @@ -155,6 +155,7 @@ symbols in this file: #include "game/game.h" #include "game/players.h" #include "interface/first_person_weapons.h" +#include "third_person.h" /* port: port/linux/game/third_person.c */ #include "memory/data.h" #include "math/real_math.h" #include "game/game_globals.h" @@ -1265,6 +1266,8 @@ static struct effect_location_datum *effect_location_get_next_instance( if (camera_mode == _effect_camera_mode_first_person_only || (camera_mode == _effect_camera_mode_both && + /* port: smoke and casings use the world weapon in shoulder view. */ + !third_person_active(effect->local_player_index) && effect->local_player_index != NONE && local_player_count() == 1)) { diff --git a/source/effects/player_effects.c b/source/effects/player_effects.c index 8f2dddc2b2..1a1f402257 100644 --- a/source/effects/player_effects.c +++ b/source/effects/player_effects.c @@ -349,14 +349,20 @@ void player_effect_dispose( return; } +/* port: camera matrices belong to the current restored-state epoch. */ +void player_effect_reset_render_state(void) +{ + csmemset(camera_effect_of_tick, 0, sizeof(camera_effect_of_tick)); +} + void player_effect_initialize_for_new_map( void) { csmemset(player_effect_globals, 0, sizeof(struct player_effect_globals_definition)); player_effect_globals->screen_fade.ticks = NONE; player_effect_globals->reference_time = game_time_get(); - /* port: (player_effect_get_camera_effect_matrix) */ - csmemset(camera_effect_of_tick, 0, sizeof(camera_effect_of_tick)); + /* port: discard the previous map's camera matrices. */ + player_effect_reset_render_state(); return; } @@ -364,6 +370,7 @@ void player_effect_initialize_for_new_map( void player_effect_dispose_from_old_map( void) { + player_effect_reset_render_state(); /* port: no cached shake after unload */ return; } diff --git a/source/effects/player_effects.h b/source/effects/player_effects.h index 3688fe75e7..f0819b09c5 100644 --- a/source/effects/player_effects.h +++ b/source/effects/player_effects.h @@ -114,4 +114,7 @@ void player_telefrag_effect_start( long player_index, real intensity); +/* port: clear render-only state after a checkpoint load. */ +void player_effect_reset_render_state(void); + #endif // __PLAYER_EFFECTS_H diff --git a/source/game/cheats.c b/source/game/cheats.c index fbba41ce1e..6db7c89b6f 100644 --- a/source/game/cheats.c +++ b/source/game/cheats.c @@ -54,6 +54,7 @@ symbols in this file: #include "cache/cache_files.h" #include "camera/director.h" #include "camera/observer.h" +#include "game/game.h" /* port: distinguish network hosts when spawning cheats */ #include "game/game_globals.h" #include "game/players.h" #include "hs/hs.h" @@ -67,6 +68,9 @@ symbols in this file: #include "scenario/scenario.h" #include "tag_files/tag_groups.h" #include "units/units.h" +#ifdef HALO_ANDROID +#include "android_cheats.h" /* port: port/linux/game/android_cheats.c */ +#endif /* ---------- constants */ @@ -113,6 +117,9 @@ void cheats_dispose( void cheats_dispose_from_old_map( void) { +#ifdef HALO_ANDROID + android_cheats_reset(); /* port: release menu-owned switches and queued requests at map unload */ +#endif return; } @@ -393,6 +400,14 @@ static void cheat_objects( real angle = arctangent(forward.i, forward.j)+ (reference_index-reference_count/2)*angle_separation; + /* port: flags and balls need game-engine ownership. Cheat spawns + have none, so clients refuse them and cannot match their pickups. */ + if (game_connection() == _game_connection_network_server && + object_definition_get(references[reference_index].index)->object.type == _object_type_weapon && + TEST_FLAG(weapon_definition_get(references[reference_index].index)->weapon.flags, _weapon_must_be_readied_bit)) + { + continue; + } object_placement_data_new(&data, references[reference_index].index, NONE); data.position.x = cosine(angle)*1.5f+origin.x; diff --git a/source/game/game.c b/source/game/game.c index 2c7853bb3f..e065808991 100644 --- a/source/game/game.c +++ b/source/game/game.c @@ -640,11 +640,14 @@ boolean game_load( game_options_verify(options)); random_seed_debug_log(TRUE); + render_prepare_end(); /* port: clear recipes even when the next load fails */ mcc_loading_begin(options->map_name); /* port: no-op for Xbox/CE loads */ csmemcpy(&game_globals->options, options, sizeof(*options)); if (scenario_load(options->map_name)) { game_globals->map_loaded = TRUE; + render_prepare_map(options->map_name); /* port: optional map-scoped shader preparation */ + texture_prepare_map(); /* port: optional bounded Xbox/CE texture preparation */ } mcc_loading_end(game_globals->map_loaded); /* port: includes failed MCC loads */ @@ -722,6 +725,7 @@ void game_initialize_for_new_map( from now on go elsewhere, port/linux/game/network_objects.c) */ network_objects_placed(); ui_widgets_safe_to_load(TRUE); + material_prepare_map(); /* port: select optional material shaders before gameplay */ return; } @@ -748,6 +752,7 @@ boolean game_map_loading_in_progress( void game_unload( void) { + render_prepare_end(); /* port: save observed recipes and release unused prepared programs */ if (cache_files_precache_in_progress()) { long map_status; @@ -782,6 +787,7 @@ void game_unload( void game_dispose( void) { + render_prepare_end(); /* port: release optional preparation before renderer shutdown */ recorded_animations_dispose(); cinematic_dispose(); hs_dispose(); diff --git a/source/game/game_engine_ctf.c b/source/game/game_engine_ctf.c index f110ea11c2..cded99df1d 100644 --- a/source/game/game_engine_ctf.c +++ b/source/game/game_engine_ctf.c @@ -1732,3 +1732,35 @@ boolean game_engine_ctf_read_network_state( } return TRUE; } + +/* port: read-only queries for port/linux/game/enhanced_bots.c, adapted from +thelinkin3000/halo-ce-universal d92cc93385edf03d0a4a21cfe4c58dd578a3e786. */ +#include "bots_objectives.h" /* port: port/linux/game/bots_objectives.h */ + +/* port: a team's flag as the bots see it (port/linux/game/bots.c, the +host's alone): FALSE if the team has none this game (one flag's assault: +the attackers'); else where it is (in a unit's hands, where the unit is), +who carries it (NONE), whether it stands at home untouched, and where home +is (its netgame flag) */ +boolean game_engine_ctf_flag_state( + long team_index, + real_point3d *position, + long *carrier_player_index, + boolean *at_home, + real_point3d *home) +{ + long weapon_index; + struct weapon_datum *weapon; + + if (!VALID_INDEX(team_index, NUMBER_OF_CTF_TEAMS) || !ctf_globals.flags[team_index]) + return FALSE; + weapon_index = ctf_globals.weapon_indices[team_index]; + weapon = weapon_index != NONE ? weapon_try_and_get(weapon_index) : NULL; + if (!weapon || weapon->object.owner_team_index != team_index) + return FALSE; + item_get_position_even_if_in_inventory(weapon_index, position); + *carrier_player_index = ctf_find_flag_carrier(weapon_index); + *at_home = !TEST_FLAG(weapon->weapon.flags, _ctf_weapon_handled_bit) && *carrier_player_index == NONE; + *home = ctf_globals.flags[team_index]->position; + return TRUE; +} diff --git a/source/game/game_engine_king.c b/source/game/game_engine_king.c index ef364d7910..8d48f1aa65 100644 --- a/source/game/game_engine_king.c +++ b/source/game/game_engine_king.c @@ -1476,3 +1476,51 @@ boolean game_engine_king_read_network_state( game_engine_play_multiplayer_sound(_multiplayer_sound_hill_move); return TRUE; } + +/* port: read-only queries for port/linux/game/enhanced_bots.c, adapted from +thelinkin3000/halo-ce-universal d92cc93385edf03d0a4a21cfe4c58dd578a3e786. */ +#include "bots_objectives.h" /* port: port/linux/game/bots_objectives.h */ + +/* port: the first active hill as the bots see it (port/linux/game/enhanced_bots.c, the host's +alone): FALSE while there is none or the buffer is too small; else all points, +its height (from its bottom to its top), its middle and its number, which +changes as the moving hill moves */ +boolean game_engine_king_hill( + real_point3d *points, + long maximum, + long *point_count, + real *bottom, + real *top, + real_point3d *center, + long *hill_id) +{ + long index; + + if (king_globals.hill_point_count <= 0 || maximum < king_globals.hill_point_count) + return FALSE; + *point_count = MIN(king_globals.hill_point_count, maximum); + for (index = 0; index < *point_count; index++) + points[index] = king_globals.hill_points[index]; + *bottom = king_globals.hill_bottom; + *top = king_globals.hill_top; + *center = king_globals.hill_center; + *hill_id = king_globals.hill_id; + return TRUE; +} + +/* port: (the bots') whether a point is on the first active hill, using the +same height and hull test as player_inside_this_hill. */ +boolean game_engine_king_point_on_hill( + real_point3d const *position) +{ + real_point2d point; + + if (king_globals.hill_point_count <= 0 || position->z < king_globals.hill_bottom || + position->z > king_globals.hill_top) + { + return FALSE; + } + point.x = position->x; + point.y = position->y; + return convex_hull2d_test_point(king_globals.hill_point_count, king_globals.convex_hull, &point, 0.0f); +} diff --git a/source/game/player_control.c b/source/game/player_control.c index cf33f5f300..ce3d6ee63b 100644 --- a/source/game/player_control.c +++ b/source/game/player_control.c @@ -181,6 +181,7 @@ symbols in this file: /* ---------- headers */ #include "cseries.h" +#include "third_person.h" /* port: port/linux/game/third_person.c */ #define limit2d limit2d_inline #include "game/game.h" #undef limit2d @@ -213,6 +214,7 @@ symbols in this file: #include "real_math.h" #include "passenger_camera.h" /* port: port/linux/game/passenger_camera.c; after the limit2d alias above */ #include "network_coop.h" /* port: port/linux/game/network_coop.c */ +#include "dualsense_game.h" /* port: port/linux/game/dualsense_game.c */ /* ---------- constants */ @@ -445,6 +447,7 @@ void player_control_dispose( void player_control_dispose_from_old_map( void) { + dualsense_game_reset(); /* port: release feature feedback before the map goes */ return; } @@ -838,6 +841,9 @@ static void handle_one_player_input( action.desired_facing = player->desired_angles; action.control_flags = player->control_flags; + /* port: replicate this tick's shoulder view, including collision fallback. */ + SET_FLAG(action.control_flags, THIRD_PERSON_INPUT_BIT, + third_person_active(local_player_index) && third_person_enabled() && player->zoom_level == NONE); action.desired_weapon_index = player->desired_weapon_index; action.desired_grenade_index = player->desired_grenade_index; action.desired_zoom_level = player->zoom_level; @@ -872,6 +878,7 @@ boolean player_control_update( { handle_one_player_input(local_player_index, time_delta_sec); } + dualsense_game_update(); /* port: feedback also observes menus and players without units */ collision_log_end_period(); profile_exit(player_control_update_section); @@ -1239,6 +1246,9 @@ static void get_local_player_input_blob( { touch_pitch = -touch_pitch; } + /* port: discard unzoomed gyro samples instead of saving a turn + for the next zoom (port/linux/src/touch_gyro.c). */ + halo_linux_gyro_filter(control->zoom_level != NONE, &gyro_yaw, &gyro_pitch); look_delta.yaw += (touch_yaw + gyro_yaw) / touch_scale; look_delta.pitch += (touch_pitch + gyro_pitch) / touch_scale; } @@ -1924,6 +1934,7 @@ void player_control_initialize_for_new_map( { short local_player_index; + dualsense_game_reset(); /* port: no feedback history crosses map loads */ player_control_globals->action_test_flags = 0; player_control_globals->action_flags = 0; player_control_globals->suppressed_action_flags = 0; @@ -1981,6 +1992,10 @@ static void player_control_modify_desired_angles( real pitch_minimum = -DEGREES_TO_RADIANS(85.5f); real pitch_maximum = DEGREES_TO_RADIANS(85.5f); + /* port: orbit the shoulder camera while keeping gameplay aim fixed. */ + if (third_person_free_look_input(local_player_index, delta_yaw, delta_pitch)) + return; + match_assert( "c:\\halo\\SOURCE\\game\\player_control.c", 0x494, diff --git a/source/game/player_queues_new.c b/source/game/player_queues_new.c index 0df6588c57..4c13a7309b 100644 --- a/source/game/player_queues_new.c +++ b/source/game/player_queues_new.c @@ -633,7 +633,8 @@ void update_client_queue( *saved = *action; *pending |= action->control_flags; *pending_primary_trigger = MAX(*pending_primary_trigger, action->primary_trigger); - saved->control_flags = *pending; + /* port: only buttons accumulate; camera state belongs to the latest input. */ + saved->control_flags = (*pending & 0xFFFFUL) | (action->control_flags & 0x10000UL); saved->primary_trigger = *pending_primary_trigger; } ++update_client_globals.current_local_player; @@ -904,7 +905,7 @@ void update_server_handle_client_update( } queue->current_action = actions[action_index]; update_server_pending_control_flags[DATUM_INDEX_TO_ABSOLUTE_INDEX(player_list[player_index])] |= - queue->current_action.control_flags; + queue->current_action.control_flags & 0xFFFFUL; /* port: only latch buttons */ match_assert_valid_real( "c:\\halo\\SOURCE\\game\\player_queues_new.c", 0x238, @@ -1153,6 +1154,18 @@ void update_server_handle_distributed_input( queue->current_action = *action; } +/* port: the host's bot input replaces the queued idle action in the same +update its tick executed. Clients receive the existing player-action message. +Adapted from halo-ce-universal ed6cdaeda8871b7bee781c76bff3a4da2836c1bf. */ +void update_server_note_bot_action(short player_index, struct player_action const *action) +{ + long number = update_server_ticked_update_number(); + struct update *update = number != NONE ? update_server_get_update(number) : NULL; + if (update && update->update_number == number && player_index >= 0 && + player_index < (short)update->update.action_count) + update->update.actions[player_index] = *action; +} + long update_server_ticked_update_number( void) { diff --git a/source/game/player_queues_new.h b/source/game/player_queues_new.h index 901af8f738..9341a86e92 100644 --- a/source/game/player_queues_new.h +++ b/source/game/player_queues_new.h @@ -78,6 +78,8 @@ void update_server_handle_distributed_input( short count); /* (the host) the update its last tick ran (NONE for none), and an update's actions (NULL once it is gone) */ +/* port: host bot actions in the existing relayed update (bots_network.c). */ +void update_server_note_bot_action(short player_index, struct player_action const *action); long update_server_ticked_update_number( void); struct player_action const *update_server_update_actions( diff --git a/source/game/players.c b/source/game/players.c index a52ad9a522..380699c6cc 100644 --- a/source/game/players.c +++ b/source/game/players.c @@ -282,6 +282,7 @@ symbols in this file: #include "units/units.h" #include "units/vehicle_definitions.h" #include "units/vehicles.h" +#include "third_person.h" /* port: replicated shoulder firing state */ #include "mcc_seats.h" /* port: port/linux/game/mcc_seats.c */ /* network_game_globals.c's */ @@ -611,7 +612,7 @@ void players_initialize_for_new_map( machine_to_player_table, NONE, sizeof(machine_to_player_table)); - /* port: the bots of local games (port/linux/game/bots.c) */ + /* port: host-owned bots (port/linux/game/bots.c) */ bots_initialize_for_new_map(); return; @@ -620,7 +621,7 @@ void players_initialize_for_new_map( void players_dispose_from_old_map( void) { - /* port: the bots of local games (port/linux/game/bots.c) */ + /* port: host-owned bots (port/linux/game/bots.c) */ bots_dispose_from_old_map(); data_make_invalid(player_data); data_make_invalid(team_data); @@ -4885,7 +4886,7 @@ void players_update_before_game( /* port: or the main menu's scene's idle players (players_idle_actions) */ if (update_client_dequeue(actions) || players_idle_actions(actions)) { - /* port: the controls of a local game's bots this tick + /* port: the controls of host-owned bots this tick (port/linux/game/bots.c), in place of what their queues held */ bots_update_actions(actions); data_iterator_new(&iterator, player_data); @@ -5077,6 +5078,10 @@ void players_update_before_game( 0x2E5, (NONE == control_data.zoom_level) || ((control_data.zoom_level >= 0))); unit_control(player->unit_index, &control_data); + /* port: keep camera state out of the stock unit input flags. */ + SET_FLAG(unit->unit.control_flags, THIRD_PERSON_INPUT_BIT, + TEST_FLAG(action->control_flags, THIRD_PERSON_INPUT_BIT) && + third_person_policy() != _third_person_forced_off); } else if (unit->unit.swarm_actor_index == NONE && unit->unit.actor_index == NONE) diff --git a/source/hs/hs.c b/source/hs/hs.c index eb6408956a..c4c25879d5 100644 --- a/source/hs/hs.c +++ b/source/hs/hs.c @@ -2780,6 +2780,7 @@ symbols in this file: #include "camera/director.h" #include "cache/sound_cache.h" #include "hs.h" +#include "bots.h" /* port: port/linux/game/bots_network.c */ #include "hs_library_external.h" #include "hs_library_internal.h" #include "object_lists.h" @@ -15695,6 +15696,10 @@ static boolean hs_compile_and_evaluate_command( return server_result; } /* port: typed bot controls, after the dedicated console's role check. */ + { + int bot_result = bots_console_command(expression); + if (bot_result >= 0) return bot_result != 0; + } /* port: the co-op host's bringto, which brings every player to the host (players.c; a client is told it is the host's) */ if (hs_host_player_command(expression, "bringto")) diff --git a/source/interface/first_person_weapons.c b/source/interface/first_person_weapons.c index 3761b670db..eb2c3b1cf7 100644 --- a/source/interface/first_person_weapons.c +++ b/source/interface/first_person_weapons.c @@ -126,12 +126,9 @@ symbols in this file: #include "sound/sound_manager.h" #include "units/units.h" #include "view_fov.h" /* port: port/linux/game/view_fov.c */ -#include "shaders/shader_definitions.h" /* port: (the shield's flare on the arms) */ -#include "shaders/shaders.h" -/* port: port/linux/game/shield_color.c */ -real_rgb_color const *shield_color_colors(long unit_index, real_rgb_color const *colors); -/* port: port/linux/game/overshield_effect.c */ -real const *overshield_effect_values(long unit_index, real const *values, boolean arms); +#include "viewmodel_shield.h" /* port: port/linux/game/viewmodel_shield.c */ +#include "shield_look.h" /* port: port/linux/game/shield_look.c */ +#include "third_person.h" /* port: port/linux/game/third_person_director.c */ /* ---------- constants */ @@ -565,30 +562,6 @@ void first_person_weapon_draw( FLAG(_render_model_first_person_bit)); } - /* port: the shield's flare on the arms as on the body, the - unit's own modifier shader (display.viewmodel_shield, - view_fov.c), in the color chosen for it as on the body - (display.shield_color, shield_color.c); the weapon above is - drawn without it */ - if (viewmodel_shield_is_visible()) - { - struct object_definition *unit_definition= object_definition_get(object_get(unit_index)->definition_index); - - if (unit_definition->object.modifier_shader.index!=NONE) - { - struct shader *modifier_shader= shader_definition_get(unit_definition->object.modifier_shader.index); - - if (shader_type_is_valid_for_modifier(modifier_shader->base.type)) - { - model_effect.modifier_shader= modifier_shader; - model_effect.modifier_animation.colors= shield_color_colors(unit_index, - unit->object.outgoing_change_colors); - model_effect.modifier_animation.values= overshield_effect_values(unit_index, - unit_functions, TRUE); - } - } - } - if (first_person_weapon->hands_node_remapping_table_valid && first_person_interface->hands.index!=NONE) { @@ -598,6 +571,20 @@ void first_person_weapon_draw( weapon_definition->weapon.interface_definition.first_person_animations.index, first_person_weapon->node_matrices, first_person_weapon->hands_node_remapping_table); + /* port: the unit's shield flare on the hands, as on its + body (display.viewmodel_shield); the weapon above is + drawn without it */ + /* port: Arm Shields owns first-person activation and offset; + SHIELD LOOK only restyles an enabled, eligible arm pass. */ + viewmodel_shield_apply(render.local_player_index, unit_index, + first_person_interface->hands.index, model_node_matrices, unit_functions, &model_effect); + shield_look_arms(render.local_player_index, unit_index, + first_person_interface->hands.index, &model_effect); + /* port: recharge also requires the Arm Shields pass. */ + shield_recharge_prepare(unit_index, &model_effect, TRUE); + /* port: Arm Shields also owns depleted first-person arcs. */ + shield_arcs_draw(unit_index, first_person_interface->hands.index, + model_node_matrices, &model_effect, TRUE); render_model( first_person_interface->hands.index, 0.0f, @@ -635,7 +622,9 @@ short first_person_weapon_get_marker_by_name( short local_player_index= first_person_weapon_index_from_weapon_index(weapon_index); if (local_player_index!=NONE && - director_get_perspective(local_player_index)==_director_perspective_first_person) + (director_get_perspective(local_player_index)==_director_perspective_first_person || + /* port: retain live markers and weapon sounds through shoulder transitions. */ + third_person_director_active(local_player_index))) { struct first_person_weapon *first_person_weapon= first_person_weapon_get(local_player_index); struct weapon_definition *weapon_definition= weapon_definition_get(weapon->definition_index); @@ -672,7 +661,9 @@ void first_person_weapon_render_update( if (first_person_weapon->unit_index!=NONE && first_person_weapon->weapon_index!=NONE) { - boolean visible= director_get_perspective(render.local_player_index)==_director_perspective_first_person && + /* port: keep viewmodel poses ready for collision fallback; view_fov.c hides the draw. */ + boolean visible= (director_get_perspective(render.local_player_index)==_director_perspective_first_person || + third_person_director_active(render.local_player_index)) && player_control_get_zoom_level(render.local_player_index)==NONE; first_person_weapon_set_visibility(render.local_player_index, visible); @@ -1483,8 +1474,8 @@ static void first_person_weapon_build_node_matrices( &render.camera.forward, &render.camera.up); /* the pose between the last two ticks (render_interpolation.c) */ - /* port: no more nodes than the weapon's matrices hold (a map's count); - the weapon and its graph tell its poses from another weapon's */ + /* port: identify the weapon and skeleton across frames; no more nodes + than the weapon's matrices hold (a map's count). */ render_interpolation_first_person( local_player_index, first_person_weapon->weapon_index, @@ -1903,7 +1894,9 @@ static void first_person_weapon_update( } if (sound_definition_index!=NONE && - director_get_perspective(local_player_index)==_director_perspective_first_person) + (director_get_perspective(local_player_index)==_director_perspective_first_person || + /* port: retain live markers and weapon sounds through shoulder transitions. */ + third_person_director_active(local_player_index))) { first_person_weapon->current_sound_index= object_impulse_sound_new( first_person_weapon->weapon_index, diff --git a/source/interface/hud.c b/source/interface/hud.c index 9fcdf7e701..4dd950a95c 100644 --- a/source/interface/hud.c +++ b/source/interface/hud.c @@ -86,6 +86,8 @@ symbols in this file: #include "game/game_globals.h" #include "game/players.h" #include "interface/hud.h" +#include "custom_edition_hud_draw.h" /* port: port/linux/game/custom_edition_hud_draw.c */ +#include "mcc_cache.h" /* port: port/linux/game/mcc_cache.c */ #include "mcc_hud_draw.h" /* port: port/linux/game/mcc_hud_draw.c */ #include "interface/hud_definitions.h" #include "interface/hud_messaging.h" @@ -952,7 +954,9 @@ static void hud_draw_friendly_indicator( bitmap, &position, &clip, - mcc_hud_bitmap_scale(interface_get_tag_index(_interface_bitmap_multiplayer_hud)), /* port: MCC bitmap units */ + (mcc_cache_tags_loaded() ? + mcc_hud_bitmap_scale(interface_get_tag_index(_interface_bitmap_multiplayer_hud)) : + custom_edition_hud_bitmap_scale(interface_get_tag_index(_interface_bitmap_multiplayer_hud))), /* port: MCC bitmap units */ 0.0f, 1.0f); } @@ -1176,7 +1180,9 @@ static void hud_draw_player_name( if (bitmap) y -= (short)(bitmap->registration_point.y * - mcc_hud_bitmap_scale(interface_get_tag_index(_interface_bitmap_multiplayer_hud))); /* port: match the MCC arrow's scale */ + (mcc_cache_tags_loaded() ? + mcc_hud_bitmap_scale(interface_get_tag_index(_interface_bitmap_multiplayer_hud)) : + custom_edition_hud_bitmap_scale(interface_get_tag_index(_interface_bitmap_multiplayer_hud)))); /* port: match the MCC arrow's scale */ } y -= 2; font = font_definition_get(font_index); diff --git a/source/interface/hud_draw.c b/source/interface/hud_draw.c index 70f1500e00..261ef179bc 100644 --- a/source/interface/hud_draw.c +++ b/source/interface/hud_draw.c @@ -83,6 +83,7 @@ symbols in this file: /* ---------- headers */ #include "cseries/cseries.h" +#include "third_person.h" /* port: port/linux/game/third_person.c */ #include "passenger_camera.h" /* port: port/linux/game/passenger_camera.c */ #include "cseries/errors.h" #include "math/real_math.h" @@ -109,6 +110,7 @@ symbols in this file: #include "units/units.h" #include "cache_file_formats.h" /* port: port/linux/game/cache_file_formats.c */ #include "custom_edition_cache.h" +#include "custom_edition_hud_draw.h" /* port: port/linux/game/custom_edition_hud_draw.c */ #include "view_fov.h" /* port: port/linux/game/view_fov.c */ /* ---------- constants */ @@ -1700,6 +1702,10 @@ static void hud_draw_bitmap_with_meter( _hud_dont_scale_offset_bit), 0.0f, &point); + /* port: move every reticle piece to the stock aim point in the shoulder view. */ + if (is_crosshair_bitmap && absolute_placement->corner == _hud_anchor_center && + !third_person_reticle(&point, render_fov_reticle_scale(render.local_player_index))) + return; /* port: the crosshairs_draw scope moves only the weapon's reticle */ if (is_crosshair_bitmap) passenger_camera_reticle_offset(&point); @@ -2117,6 +2123,12 @@ void hud_draw_numbers( digit_scale = TEST_FLAG(numbers->placement.multiplayer_scaling_flags, _hud_use_high_resolution_scale_bit) || TEST_FLAG(bitmap_group->flags, _bitmap_group_half_hud_scale_bit) ? scale*0.5f : scale; + /* port: CE bitmap flags compose without changing digit spacing. + Xbox/mod and MCC number handling keep the existing rule above. */ + if (custom_edition_cache_tags_loaded()) + digit_scale = scale * custom_edition_hud_number_scale(hud_number->number_bitmap.index, + numbers->placement.multiplayer_scaling_flags); + /* port: an MCC map's HUD canvas (mcc_hud.c) */ if (mcc_cache_tags_loaded()) digit_scale *= mcc_hud_canvas_scale(); diff --git a/source/interface/hud_messaging.c b/source/interface/hud_messaging.c index 2b8b5a63bf..4d966c0e84 100644 --- a/source/interface/hud_messaging.c +++ b/source/interface/hud_messaging.c @@ -115,6 +115,7 @@ symbols in this file: /* ---------- headers */ #include "mcc_hud_draw.h" /* port: port/linux/game/mcc_hud_draw.c */ +#include "custom_edition_hud_draw.h" /* port: port/linux/game/custom_edition_hud_draw.c */ #include "mcc_cache.h" /* port: preserve MCC-authored gameplay icons */ #include "cseries/cseries.h" @@ -539,6 +540,7 @@ static void render_state_bitmap( struct bitmap_data const *bitmap = NULL; real_rectangle2d const *clip = NULL; real scale; + real bitmap_scale; /* port: authored CE pickup icons, not controller glyphs. */ point2d point; /* port: keep gameplay prompts on the high-resolution HUD path, which @@ -565,6 +567,8 @@ static void render_state_bitmap( if (mcc_cache_tags_loaded() && hud_hires_button_draw(icon, cursor_bounds, color)) return; bitmap = hud_hires_sprite_bitmap(bitmap, icon->sequence_index); + /* port: controller glyphs return above; map artwork keeps its flags. */ + bitmap_scale = custom_edition_hud_bitmap_scale(bitmap_group_index); scale = local_player_count() > 1 ? 0.75f : 1.0f; point.x = (short)(icon->offset.x * scale + cursor_bounds->x0); point.y = (short)(cursor_bounds->y1 - icon->offset.y * scale); @@ -573,7 +577,7 @@ static void render_state_bitmap( _hud_corner_bottom_left, &point, clip, - scale, + scale * bitmap_scale, /* port: CE bitmap scale, independent of text offsets. */ 0.0f, TEST_FLAG(icon->flags, _hud_icon_use_color_bit) ? icon->color : color, FALSE); @@ -582,12 +586,12 @@ static void render_state_bitmap( else if (clip) { cursor_bounds->x0 = (short)( - ((clip->x1 - clip->x0) * bitmap->width + icon->width_offset) * scale + point.x); + ((clip->x1 - clip->x0) * bitmap->width * bitmap_scale + icon->width_offset) * scale + point.x); /* port: CE icon advance. */ } else { cursor_bounds->x0 = (short)( - (bitmap->width + icon->width_offset) * scale + point.x); + (bitmap->width * bitmap_scale + icon->width_offset) * scale + point.x); /* port: CE icon advance. */ } } diff --git a/source/interface/hud_nav_points.c b/source/interface/hud_nav_points.c index d7e252a564..06bdbfc056 100644 --- a/source/interface/hud_nav_points.c +++ b/source/interface/hud_nav_points.c @@ -99,6 +99,7 @@ symbols in this file: /* ---------- headers */ #include "mcc_hud_draw.h" /* port: port/linux/game/mcc_hud_draw.c */ +#include "custom_edition_hud_draw.h" /* port: port/linux/game/custom_edition_hud_draw.c */ #include "cseries/cseries.h" #include "cseries/errors.h" #include "game_state.h" @@ -763,6 +764,7 @@ void custom_render_nav_point( real_rgb_color rgb_temp; scale *= mcc_hud_bitmap_scale(bitmap_index); /* port: preserve MCC waypoint bitmap scaling. */ + scale *= custom_edition_hud_bitmap_scale(bitmap_index); /* port: CE arrows and their number offsets. */ corner.x = (short)screen_position.x; corner.y = (short)screen_position.y; alpha = PIN(255 * fast_ftol_C(arrow->opacity), 0, 255); diff --git a/source/interface/hud_unit.c b/source/interface/hud_unit.c index b6ded8e982..4f5b2f2de4 100644 --- a/source/interface/hud_unit.c +++ b/source/interface/hud_unit.c @@ -66,7 +66,8 @@ symbols in this file: /* ---------- headers */ -#include "mcc_hud_draw.h" /* port: port/linux/game/mcc_hud_draw.h */ +#include "mcc_hud_draw.h" +#include "custom_edition_hud_draw.h" /* port: port/linux/game/custom_edition_hud_draw.c */ #include "cseries/cseries.h" #include "cseries/errors.h" #include "cutscene/cinematics.h" @@ -654,8 +655,8 @@ void hud_render_damage_indicators( byte damage_indicators[NUMBER_OF_HUD_DAMAGE_INDICATOR_DIRECTIONS]; short direction; - /* port: an MCC map's indicator bitmap's own scale (mcc_hud.c) */ scale *= mcc_hud_bitmap_scale(definition->indicator_bitmap.index); + scale *= custom_edition_hud_bitmap_scale(definition->indicator_bitmap.index); /* port: CE damage arrows. */ player_effect_get_damage_indicators( local_player_index, @@ -776,7 +777,11 @@ void hud_tick_shield( long player_index, real amount) { - short local_player_index = player_get(player_index)->local_player_index; + /* port: overshield decay also runs on objects without a player HUD. */ + short local_player_index; + if (player_index == NONE) + return; + local_player_index = player_get(player_index)->local_player_index; if (local_player_index != NONE) get_hud_state(local_player_index)->last_shield_vitality -= amount; diff --git a/source/interface/hud_weapon.c b/source/interface/hud_weapon.c index 80ec2c366c..b54779376c 100644 --- a/source/interface/hud_weapon.c +++ b/source/interface/hud_weapon.c @@ -80,6 +80,7 @@ symbols in this file: #include "units/units.h" #include "mcc_hud_draw.h" /* port: port/linux/game/mcc_hud_draw.c */ #include "custom_edition_hud.h" /* port: CE warning placement and reticle classification */ +#include "custom_edition_hud_draw.h" /* port: port/linux/game/custom_edition_hud_draw.c */ #include "hud_hires_crosshairs.h" /* port: port/linux/game/hud_hires_tags.c */ #include @@ -1305,6 +1306,8 @@ static void crosshairs_draw( } inverse_scale = 1.0f / scale; + /* port: a CE scope covers the view at its converted bitmap scale. */ + inverse_scale /= custom_edition_hud_bitmap_scale(element->crosshairs.bitmap.index); expand_u = (bitmap->width - (render.camera.viewport_bounds.x1 - render.camera.viewport_bounds.x0) * inverse_scale) * texel_scale_u * -0.5f; expand_v = (bitmap->height - (render.camera.viewport_bounds.y1 - render.camera.viewport_bounds.y0) * inverse_scale) * diff --git a/source/interface/interface.c b/source/interface/interface.c index 971131ee81..f3ccdef927 100644 --- a/source/interface/interface.c +++ b/source/interface/interface.c @@ -85,6 +85,7 @@ symbols in this file: #include "game/players.h" #include "interface/first_person_weapons.h" #include "interface/hud.h" +#include "custom_edition_hud_draw.h" /* port: port/linux/game/custom_edition_hud_draw.c */ #include "mcc_hud_draw.h" /* port: port/linux/game/mcc_hud_draw.c */ #include "interface/hud_definitions.h" #include "interface/interface.h" @@ -725,9 +726,12 @@ void interface_draw_screen( } } + /* port: CE zoom-mask scaling lasts only for this view's HUD effect. */ + custom_edition_hud_mask_begin(parameters.convolution_mask); mcc_hud_mask_begin(parameters.convolution_mask); /* port: MCC screen-effect bitmap units */ rasterizer_screen_effect(¶meters); mcc_hud_mask_end(); /* port: release the current view's borrowed mask */ + custom_edition_hud_mask_end(); } else { diff --git a/source/interface/ui_widget.c b/source/interface/ui_widget.c index c3c7b4ece9..f233a4c603 100644 --- a/source/interface/ui_widget.c +++ b/source/interface/ui_widget.c @@ -627,9 +627,14 @@ symbols in this file: struct widget_instance; +#include "mcc_hud_draw.h" +#include "mcc_menu_preview.h" /* port: port/linux/game/mcc_menu_preview.c */ +#include "mcc_menu_text.h" /* port: port/linux/game/mcc_menu_text.c */ #include "cseries.h" -#include "keyboard_glyphs.h" /* port: port/linux/game/keyboard_glyphs.c; HUD prompts only */ +#include "frontend_menu.h" /* port: port/linux/game/frontend_menu.c and frontend_menu_runtime.inl */ +#include "keyboard_glyphs.h" /* port: port/linux/game/keyboard_glyphs.c */ #include "menu_button_glyphs.h" /* port: port/linux/game/menu_button_glyphs.c */ +#include "frontend_input.h" /* port: modern frontend input-source observation */ #include "errors.h" #include "bitmaps/bitmap_group.h" #include "bitmaps/bitmaps.h" @@ -656,6 +661,7 @@ struct widget_instance; #include "interface/progress_bar.h" #include "interface/ui_widget_game_data_input_functions.h" #include "custom_edition_maps.h" /* port: port/linux/game/custom_edition_maps.c */ +#include "mcc_maps.h" #include "interface/ui_widget_event_handler_functions.h" #include "interface/ui_widget_text_search_and_replace_functions.h" #include "interface/virtual_keyboard.h" @@ -1622,6 +1628,8 @@ static wchar_t const *const kills_to_win_extra_descriptions[] = /* port: an error message of the port's own text (display_error_text_deferred): the text waiting for its dialog, then the dialog's text box showing it */ static wchar_t const *ui_widget_port_error_pending_text = NULL; +/* port: one synchronous fatal-screen call; its text is copied by the caller. */ +static wchar_t const *ui_widget_port_fatal_text = NULL; static wchar_t const *ui_widget_port_error_text = NULL; static struct widget_instance *ui_widget_port_error_text_box = NULL; @@ -1980,7 +1988,9 @@ void draw_bitmap_in_rect( /* port: (rasterizer.h) */ parameters.alpha_weighted = FALSE; parameters.framebuffer_blend_function = 0; - rasterizer_psuedo_dynamic_screen_quad_draw(¶meters, vertices); + /* port: modern rounded panels preserve their ends using these same plasma parameters. */ + if (!frontend_panel_draw(¶meters, vertices, bitmap->width)) + rasterizer_psuedo_dynamic_screen_quad_draw(¶meters, vertices); } return; @@ -4305,6 +4315,9 @@ struct widget_instance *ui_widget_load_by_name_or_tag( (widget_stack>=0) && (widget_stackparameters.text_box.string_list_index = error_code; widget->widget_is_error_dialog = TRUE; dashboard_abort_error = error_code; + /* port: keep the fatal screen and lifecycle, with a loader's explanation. */ + if (ui_widget_port_fatal_text) + { + ui_widget_port_error_text_box = widget; + ui_widget_port_error_text = ui_widget_port_fatal_text; + } } else { error(_error_silent, "failed to load '%s' widget", widget_name); } + /* port: never carry this override into another error. */ + ui_widget_port_fatal_text = NULL; return; } +/* port: CE precache errors need text while retaining display_error_damaged_media's +fatal behaviour. The copy remains valid throughout its non-returning loop. */ +void display_error_damaged_media_text(wchar_t const *text) +{ + static wchar_t message[512]; + if (text && text[0]) + { + ustrncpy(message, text, NUMBEROF(message) - 1); + message[NUMBEROF(message) - 1] = 0; + ui_widget_port_fatal_text = message; + } + display_error_damaged_media(); +} + void display_error_damaged_media( void) { @@ -5366,7 +5403,8 @@ void main_screen_shell_load( { extern char const *pc_menus_root_name(void); - if (!ui_widget_load_by_name_or_tag(pc_menus_root_name(), NONE, NULL, NONE, NONE, NONE, NONE)) + /* port: apply frontend preferences only at this main-menu boundary. */ + if (!ui_widget_load_by_name_or_tag(frontend_menu_root(pc_menus_root_name()), NONE, NULL, NONE, NONE, NONE, NONE)) error(_error_silent, "failed to load main screen shell window"); } if (widget_globals.main_menu_deferred_error_code != NONE) @@ -5764,6 +5802,8 @@ static void widget_instance_render_text_box( bounds.y0 += offset.y; bounds.x0 += definition->horizontal_offset; bounds.y0 += definition->vertical_offset; + /* port: contextual help keeps the modern panel's authored blue text. */ + if (frontend_menu_wrap(widget->definition_tag_index)) focus = FALSE; if (focus) { color = get_ui_argb_white(); @@ -5839,6 +5879,19 @@ static void widget_instance_render_text_box( clip.y1 = MIN(clip.y1, bounds.y1); } } + /* port: measure modern help without the text renderer's horizontal clamp, + * then wrap its fresh instance copy to the actual panel width. */ + if (frontend_menu_wrap(widget->definition_tag_index)) + { + rectangle2d measure = bounds; + measure.x1 = SHORT_MAX; + frontend_menu_reflow_text(*text); + /* port: measure line advances from the left, then restore the authored + * alignment. A centered cursor includes half the measurement box. */ + draw_string_set_draw_mode(font_index, NONE, 0, 0, &color); + ui_widget_port_text_wrap(*text, &measure, (short)(bounds.x1 - bounds.x0 - 2)); + draw_string_set_draw_mode(font_index, NONE, justification, 0, &color); + } /* port: authored MCC catalog text needs measured wrapping in every * frontend. The MCC module owns formatting and clips to this text box. */ if (mcc_menu_text_draw(widget->definition_tag_index, widget->parameters.text_box.string_list_index, @@ -7299,6 +7352,10 @@ static void ui_widgets_process_mouse( ui_debug_frame++; pointer_active = halo_ui_pointer_update(ui_mouse_menus_active(), &pointer) != 0; + /* port: observe the existing pointer read without consuming input again. */ + if (pointer_active) + frontend_input_pointer(pointer.touch, pointer.moved || pointer.left_clicks || + pointer.right_clicks || pointer.wheel_steps || pointer.downs); if (pointer_active) ui_mouse_pointer_is_touch = pointer.touch != 0; if (pointer_active && ui_debug_targets_enabled()) @@ -7536,8 +7593,41 @@ static void widget_instance_render_recursive( /* port: (custom_edition_maps_picture) */ struct bitmap_data *custom_edition_picture; short frame_index; + /* port: a local modern definition supplies identical drawing and pointer bounds. */ + struct ui_widget_definition frontend_definition; + short mcc_picture_index; /* port: MCC owns its picture selection and cache. */ + rectangle2d frontend_clip; + short frontend_shift = 0; + short frontend_left = definition->bounds.x0, frontend_right = definition->bounds.x1; + boolean frontend_layout; + + frontend_layout = frontend_menu_geometry(widget->definition_tag_index, + &frontend_left, &frontend_right, &frontend_shift); + if (frontend_layout) + { + frontend_definition = *definition; + frontend_definition.bounds.x0 = frontend_left; + frontend_definition.bounds.x1 = frontend_right; + /* port: the modern value column grows with its text and right arrow. */ + if (widget->type == _ui_widget_type_spinner_list) + { + frontend_definition.list_footer_bounds.x0 += frontend_right - definition->bounds.x1; + frontend_definition.list_footer_bounds.x1 += frontend_right - definition->bounds.x1; + } + frontend_definition.text_font.index = frontend_menu_font(widget->definition_tag_index, definition->text_font.index); + definition = &frontend_definition; + offset.x += frontend_shift; + /* port: detached help text also has no parent; only the screen container + * supplies the viewport clip, before child offsets are accumulated. */ + if (!widget->parent && widget->type == _ui_widget_type_container && clip_rect) + { + frontend_clip = *clip_rect; + frontend_clip.x0 = definition->bounds.x0; + frontend_clip.x1 = definition->bounds.x1; + clip_rect = &frontend_clip; + } + } - short mcc_picture_index; /* port: MCC owns its preview cache. */ if (!use_nifty_plasma_fx && TEST_FLAG(definition->flags, _widget_always_render_with_nifty_fx_bit)) @@ -7561,6 +7651,8 @@ static void widget_instance_render_recursive( } if (!widget->visible) return; + /* port: modern scrolling excludes off-screen rows from drawing and pointer hits. */ + if (!frontend_menu_row_drawable(widget)) return; ui_mouse_note_target(widget, definition, offset); /* port: a Custom Edition map's picture, drawn over the whole widget, or the unknown level's frame for a map without one @@ -7671,6 +7763,9 @@ static void widget_instance_render_recursive( boolean shown = TRUE; boolean stretched = custom_edition_picture && custom_edition_maps_campaign_level(widget->animation.current_frame_index) == NONE; + /* port: modern art follows its responsive bounds; inherited map and + * gametype previews retain their native padded-bitmap texel placement. */ + stretched = stretched || (frontend_layout && frontend_menu_stretch_bitmap(widget->definition_tag_index)); /* port: MCC art fits and clips to this style's authored thumbnail * rectangle; only the MCC module decodes or owns its texture. */ @@ -7691,6 +7786,15 @@ static void widget_instance_render_recursive( widget->local_player_index >= 0 && widget->local_player_index < 4 ? widget->local_player_index : 0, &bounds, clip, color)) { + /* port: scaled modern difficulty icons exclude the native bitmap's + * power-of-two padding, keeping their visible art centered. */ + if (frontend_layout && frontend_menu_bitmap_region(widget->definition_tag_index, &frame_width, &frame_height)) + { + set_rectangle2d(&texels, 0, 0, frame_width, frame_height); + stretched = FALSE; + } + /* port: scope panel slicing to this modern widget's background. */ + frontend_panel_begin(widget->definition_tag_index); draw_bitmap_in_rect( bitmap, &bounds, @@ -7699,6 +7803,7 @@ static void widget_instance_render_recursive( color, &multitexture_params, widget->disabled); + frontend_panel_end(); } } if (use_nifty_plasma_fx) @@ -7712,6 +7817,8 @@ static void widget_instance_render_recursive( switch (widget->type) { case _ui_widget_type_text_box: + /* port: the widened clip belongs only to this modern text draw. */ + frontend_menu_text_begin(widget->definition_tag_index); widget_instance_render_text_box( widget, definition, @@ -7730,6 +7837,7 @@ static void widget_instance_render_recursive( text_bounds.y0 += definition->vertical_offset; menu_functions_text_box_drawn(widget, &text_bounds); } + frontend_menu_text_end(); break; case _ui_widget_type_spinner_list: @@ -8293,6 +8401,12 @@ static void widget_instance_process_one_event_recursive( "c:\\halo\\SOURCE\\interface\\ui_widget.c", 3067, widget && definition && event && return_widget_deleted); + /* port: optional main-menu shortcuts and additive Xbox editor actions. */ + if (event_for_this_widget && frontend_menu_shortcut(widget, event)) + { + *return_widget_deleted = TRUE; + return; + } if (event->type == _event_type_button && event->data.button.index >= _widget_event_dpad_up && event->data.button.index <= _widget_event_dpad_right) diff --git a/source/interface/ui_widget.h b/source/interface/ui_widget.h index 0488e7a754..ce7f1189e8 100644 --- a/source/interface/ui_widget.h +++ b/source/interface/ui_widget.h @@ -230,6 +230,8 @@ void display_error_abort_to_dashboard( boolean optional); void display_error_damaged_media( void); +/* port: explanatory text with the same fatal media-error lifecycle. */ +void display_error_damaged_media_text(wchar_t const *text); void display_errors_deferred_until_cinematic_stop( void); void display_scenario_help( diff --git a/source/interface/ui_widget_event_handler_functions.c b/source/interface/ui_widget_event_handler_functions.c index 24cf59d600..756e63c003 100644 --- a/source/interface/ui_widget_event_handler_functions.c +++ b/source/interface/ui_widget_event_handler_functions.c @@ -3002,7 +3002,7 @@ static boolean create_and_begin_editing_new_player_profile( return result; } -/* port: a Custom Edition map's own New Game screen has a column list of rows, +/* port: a Custom Edition map's own New Game screen has a column list of rows, not the Xbox's spinner of three: the menus' map list fills it (menu_functions.c) */ static boolean multiplayer_level_list_initialize( struct widget_instance *widget, @@ -5870,7 +5870,7 @@ static boolean playlist_profile_change_player_options( return result; } -/* port: a map's own screen: the map chosen is kept until the game ends, +/* port: a map's own screen: the map chosen is kept until the game ends, when the server is in pregame to take it (menu_functions.c, pc_menu_map_stash) */ static boolean multiplayer_level_select( struct widget_instance *widget, @@ -5884,7 +5884,7 @@ static boolean multiplayer_level_select( struct widget_instance *level_list; struct ui_widget_definition *definition; long level_index; - + definition = ui_widget_definition_get(widget->definition_tag_index); if (definition->child_count != 1) { @@ -5984,7 +5984,7 @@ static boolean multiplayer_profile_set_for_game( definition = ui_widget_definition_get(widget->definition_tag_index); if (definition->child_count != 1) { - /* port: a map's own gametype screen: the gametype chosen is kept, and the game ends as its time + /* port: a map's own gametype screen: the gametype chosen is kept, and the game ends as its time limit would; the map and gametype are applied in the pregame that follows (pc_menu_new_game_apply) */ extern boolean pc_menu_new_game_begin(struct widget_instance *list, boolean *widget_deleted); return pc_menu_new_game_begin(widget, widget_deleted); /* port: a map's own screen */ @@ -6494,4 +6494,3 @@ boolean ui_widget_port_gametype_save( } return player_ui_save_profile(); } - diff --git a/source/interface/ui_widget_game_data_input_functions.c b/source/interface/ui_widget_game_data_input_functions.c index d4781d62cd..f67178319b 100644 --- a/source/interface/ui_widget_game_data_input_functions.c +++ b/source/interface/ui_widget_game_data_input_functions.c @@ -356,6 +356,7 @@ symbols in this file: #include "text/unicode.h" #include "custom_edition_maps.h" /* port: port/linux/game/custom_edition_maps.c */ #include "halo_menus.h" /* port: PC_MENU_FUNCTION_BASE */ +#include "frontend_menu.h" /* port: optional Xbox settings links */ /* ---------- constants */ @@ -2306,6 +2307,8 @@ static void player_profile_edit_select_menu_update_extended_description( leave the last item's description shown, as they have none */ if (pc_menu_tag(list_widget->definition_tag_index) && list_widget->focused_child->type == _ui_widget_type_column_list) index = NONE; + /* port: added Xbox links do not consume the native description's frames. */ + index = frontend_menu_legacy_description_index(list_widget, index); if (index != NONE) { @@ -2333,6 +2336,8 @@ static void game_options_menu_update_text_desc( struct widget_instance *spinner_list; struct ui_widget_definition *definition; long description_index = 0; + /* port: optional Xbox editor links have no native spinner description. */ + if (frontend_menu_legacy_controls_help(widget)) return; match_vassert( "c:\\halo\\SOURCE\\interface\\ui_widget_game_data_input_functions.c", diff --git a/source/items/weapon_definitions.h b/source/items/weapon_definitions.h index e90b9e37f2..0c829ae4b1 100644 --- a/source/items/weapon_definitions.h +++ b/source/items/weapon_definitions.h @@ -109,6 +109,17 @@ struct weapon_magazine_definition struct tag_block ammunition_objects; }; +/* port: shared with the shoulder camera's firing-effect marker lookup. + Firing, misfire and empty effects, in weapons.c's effect-type order. */ +struct weapon_firing_effect_definition +{ + short shots_lower_bound; + short shots_upper_bound; + long unused[8]; + struct tag_reference effects[3]; + struct tag_reference damage_effects[3]; +}; + struct weapon_trigger_definition { unsigned long flags; diff --git a/source/items/weapons.c b/source/items/weapons.c index 2f05f5d8cc..ac9e16bb27 100644 --- a/source/items/weapons.c +++ b/source/items/weapons.c @@ -201,6 +201,7 @@ symbols in this file: /* ---------- headers */ #include "cseries.h" +#include "third_person.h" /* port: port/linux/game/third_person_weapon.c */ #include "weapons.h" #include "equipment.h" @@ -219,6 +220,7 @@ symbols in this file: #include "effects/effects.h" #include "game/cheats.h" #include "mcc_script_effects.h" /* port: MCC host-approved ammunition prediction */ +#include "muzzle_lighting.h" /* port: port/linux/game/muzzle_lighting.c */ #include "mcc_campaign.h" /* port: MCC host-approved reserve/battery prediction */ #include "game/game.h" #include "game/game_engine.h" @@ -364,14 +366,7 @@ struct animation_graph_first_person_weapon_animations }; /* TU-local: weapon_trigger_definition.firing_effects element; no shared header declares it yet. */ -struct trigger_firing_effect -{ - short shots_lower_bound; - short shots_upper_bound; - long unused[8]; - struct tag_reference effects[NUMBER_OF_TRIGGER_FIRING_EFFECTS]; - struct tag_reference damage_effects[NUMBER_OF_TRIGGER_FIRING_EFFECTS]; -}; +/* port: firing-effect layout is shared in weapon_definitions.h. */ /* ---------- prototypes */ @@ -2479,12 +2474,13 @@ static void trigger_create_projectiles( long target_object_index= NONE; long projectile_definition_index; short projectile_count; - - /* port: MCC owns camera-relative placement and the pre-creation cover check. */ + boolean muzzle_origin = FALSE; /* port: exclude shooter from BSP repair */ + /* port: H1A camera rays are independently calculated and cover checked. */ boolean mcc_ray = mcc_projectile_ray(weapon_index, owner_object_index, trigger_index, TRUE, &origin, &forward, &velocity, &target_object_index); - if (!mcc_ray && !TEST_FLAG(trigger_definition->flags, _weapon_trigger_projectiles_cannot_be_aimed_bit) && + if (!mcc_ray && /* port: retain the original ray for all other shots */ + !TEST_FLAG(trigger_definition->flags, _weapon_trigger_projectiles_cannot_be_aimed_bit) && unit && !TEST_FLAG(unit->object.damage_flags, _object_dead_bit)) { @@ -2557,6 +2553,12 @@ static void trigger_create_projectiles( origin= markers[marker_index].matrix.position; } + /* port: shoulder shots leave the world muzzle. Custom + triggers that explicitly choose an origin or forbid aiming keep it. */ + if (!TEST_FLAG(trigger_definition->flags, _weapon_trigger_uses_weapon_origin_bit) && + !TEST_FLAG(trigger_definition->flags, _weapon_trigger_projectiles_cannot_be_aimed_bit)) + muzzle_origin = third_person_muzzle_shot(weapon_index, owner_object_index, trigger_index, &origin, &forward); + if (trigger_index==0 && weapon->weapon.alternate_shots_loaded>0) { struct weapon_trigger_definition *secondary_trigger_definition= TAG_BLOCK_GET_ELEMENT(&weapon_definition->weapon.triggers, 1, struct weapon_trigger_definition); @@ -2641,8 +2643,10 @@ static void trigger_create_projectiles( real_point3d camera_position; unit_get_camera_position(owner_object_index, &camera_position); - /* port: MCC already checks cover before attachments emit their first point. */ - if (!mcc_ray) object_force_inside_bsp(projectile_object_index, &camera_position); + /* port: MCC cover is checked before creation; shoulder rays exclude their owner. */ + if (!mcc_ray || muzzle_origin) + object_force_inside_bsp_ignoring(projectile_object_index, &camera_position, + muzzle_origin ? owner_object_index : NONE); } if (target_object_index!=NONE) { @@ -2733,7 +2737,7 @@ static void weapon_trigger_fire( if (trigger_definition->firing_effects.count>0) { - struct trigger_firing_effect *firing_effect; + struct weapon_firing_effect_definition *firing_effect; short effect_type; if (trigger->firing_effect_shots_remaining<=0) @@ -2752,7 +2756,7 @@ static void weapon_trigger_fire( do { - struct trigger_firing_effect *next_firing_effect; + struct weapon_firing_effect_definition *next_firing_effect; if (trigger->firing_effects_used_flags==FLAG(trigger_definition->firing_effects.count)-1) { @@ -2769,7 +2773,7 @@ static void weapon_trigger_fire( } while (TEST_FLAG(trigger->firing_effects_used_flags, firing_effect_index)); - next_firing_effect= TAG_BLOCK_GET_ELEMENT(&trigger_definition->firing_effects, firing_effect_index, struct trigger_firing_effect); + next_firing_effect= TAG_BLOCK_GET_ELEMENT(&trigger_definition->firing_effects, firing_effect_index, struct weapon_firing_effect_definition); trigger->firing_effect_index= firing_effect_index; SET_FLAG(trigger->firing_effects_used_flags, firing_effect_index, TRUE); trigger->firing_effect_shots_remaining= random_range(next_firing_effect->shots_lower_bound, next_firing_effect->shots_upper_bound); @@ -2778,7 +2782,7 @@ static void weapon_trigger_fire( } trigger->firing_effect_shots_remaining--; - firing_effect= TAG_BLOCK_GET_ELEMENT(&trigger_definition->firing_effects, trigger->firing_effect_index, struct trigger_firing_effect); + firing_effect= TAG_BLOCK_GET_ELEMENT(&trigger_definition->firing_effects, trigger->firing_effect_index, struct weapon_firing_effect_definition); if (weapon_definition->weapon.age_misfire_start>0.0f && weapon_definition->weapon.age_misfire_start<1.0f && @@ -2886,6 +2890,7 @@ static void weapon_trigger_fire( else { trigger_create_projectiles(weapon_index, trigger_index); + muzzle_lighting_shot(weapon_index, trigger_index); /* port: successful shot only */ ai_handle_unit_effect(owner_object_index, _ai_unit_effect_shooting, trigger_definition->firing_noise); } } diff --git a/source/main/main.c b/source/main/main.c index 9bc94632ab..2192311d26 100644 --- a/source/main/main.c +++ b/source/main/main.c @@ -332,6 +332,7 @@ symbols in this file: /* ---------- headers */ #include "cseries.h" +#include "third_person.h" /* port: port/linux/game/third_person.c */ #include "errors.h" #include "cseries/profile.h" #include "cseries/cseries_windows.h" @@ -379,7 +380,7 @@ symbols in this file: #include "networking/network_game_globals.h" #include "networking/network_game_manager.h" #include "networking/network_server_manager.h" /* port: a co-op game's level won */ -#include "network_coop.h" +#include "network_coop.h" /* port: port/linux/game/network_coop.c */ #include "coop_scripts.h" /* port: port/linux/game/coop_scripts.c */ #include "network_voice.h" /* port: port/linux/game/network_voice.c */ #include "network_chat.h" /* port: port/linux/game/network_chat.c */ @@ -409,6 +410,7 @@ symbols in this file: #include "mcc_cache.h" /* port: port/linux/game/mcc_cache.h */ #include "mcc_main.h" /* port: port/linux/game/mcc_main.h */ #include "view_fov.h" /* port: display.fov, before the projection and culling */ +#include "frontend_menu.h" /* port: optional menu-tag lifecycle at the main menu */ #if defined(HALO_WINDOWS) || defined(HALO_ANDROID) || defined(__linux__) #define HALO_NATIVE_BUILD_INFO 1 @@ -1133,6 +1135,9 @@ void main_menu_unload( void main_menu_load( void) { + /* port: optional frontend tags are rebuilt only at the main-menu boundary. */ + if (frontend_menu_reload_required()) + main_menu_unload(); if (!main_globals.main_menu_scenario_loaded) main_load_ui_scenario(FALSE); main_screen_shell_load(); @@ -1170,12 +1175,12 @@ void set_window_camera_values( window->rasterizer_camera.position = observer->position; window->rasterizer_camera.forward = observer->forward; window->rasterizer_camera.up = observer->up; - /* port: display.fov's view, the local render view only (view_fov.c) */ + /* port: keep the stock FOV until the shoulder collision test below. */ window->rasterizer_camera.vertical_field_of_view = - render_fov_vertical(window->local_player_index, 2.0f * arctangent( + 2.0f * arctangent( 0.75f * render_camera_get_adjusted_field_of_view_tangent( observer->field_of_view), - 1.0f)); + 1.0f); if (window->local_player_index != NONE && !console_is_active() && @@ -1214,6 +1219,12 @@ void set_window_camera_values( 1.0f); } + /* port: the shoulder view is applied after interpolation and camera effects. */ + third_person_camera(window->local_player_index, observer ? &window->rasterizer_camera : NULL); + /* port: choose the FOV after collision has selected this frame's view. */ + if (observer) + window->rasterizer_camera.vertical_field_of_view = render_fov_vertical( + window->local_player_index, window->rasterizer_camera.vertical_field_of_view); window->rasterizer_camera.mirrored = FALSE; window->rasterizer_camera.z_near = rasterizer_globals.near_clip_distance; window->rasterizer_camera.z_far = rasterizer_globals.far_clip_distance; @@ -1484,10 +1495,13 @@ static void main_new_map( } else { - /* port: an MCC map that fails to load goes back to the menus (mcc_main.c) */ if (mcc_main_load_failed(options->map_name)) return; - error(_error_immediate, "game_load() failed."); + /* port: keep the existing fatal load path, but name the CE failure. */ + if (custom_edition_level_name(options->map_name)) + error(_error_immediate, "%s", custom_edition_cache_load_error(options->map_name)); + else + error(_error_immediate, "game_load() failed."); } if (!errors_handle()) @@ -3590,6 +3604,8 @@ static boolean main_loop_iteration( input_frame_begin(); input_update(); input_abstraction_update(); + /* port: camera shortcuts obey the host's match policy. */ + third_person_input_update(); profile_scope_exit(main_input_section) profile_scope_enter(main_platform_events_section) shell_idle(); diff --git a/source/models/models.c b/source/models/models.c index ec3d8d6b56..3657bb3117 100644 --- a/source/models/models.c +++ b/source/models/models.c @@ -64,6 +64,7 @@ symbols in this file: /* ---------- headers */ #include "cseries.h" +#include "shield_look.h" /* port: port/linux/game/shield_look.c */ #include "cseries/errors.h" #include "cseries/profile.h" #include "models.h" @@ -87,6 +88,7 @@ symbols in this file: #include "cache/cache_files.h" #include "rasterizer/rasterizer_transparent_geometry.h" #include "model_detail.h" /* port: port/linux/game/model_detail.c */ +#include "first_person_legs.h" /* port: feature-owned lower-body geometry */ /* ---------- constants */ @@ -336,6 +338,7 @@ static void render_model_parts( struct model_geometry_part *part = TAG_BLOCK_GET_ELEMENT(&geometry->parts, part_index, struct model_geometry_part); struct model_shader_reference *shader_reference; struct shader *shader; + struct triangle_buffer const *triangles = &part->triangle_buffer; /* port: original unless legs */ /* port: a shader the model has (a map's index); a part without one isn't drawn */ @@ -349,10 +352,23 @@ static void render_model_parts( part->shader_index, struct model_shader_reference); shader = shader_definition_get(shader_reference->shader.index); + /* port: selected player shield looks replace their authored plasma shells. */ + if (shield_look_skip_shell(object_index, model, shader, + TEST_FLAG(flags, _render_model_first_person_bit))) + continue; if (shader_type_is_valid_for_model(shader->base.type) && !TEST_FLAG(part->flags, _model_geometry_part_stripped_bit)) { + /* port: only the marked local body uses private indices. The + original vertices retain their CE/MCC palettes and materials. */ + if ((flags & FIRST_PERSON_LEGS_RENDER_FLAG) && !TEST_FLAG(flags, _render_model_shadow_bit)) + { + triangles = first_person_legs_triangles(object_index, model, + &part->vertex_buffer, &part->triangle_buffer); + if (!triangles) + continue; + } if (shader_type_is_transparent(shader->base.type)) { if (pass==_render_model_pass_transparent) @@ -380,9 +396,9 @@ static void render_model_parts( rasterizer_model_transparent_geometry_submit( shader, forced_shader_permutation_index ? forced_shader_permutation_index : shader_reference->permutation_index, - &part->triangle_buffer, + triangles, NONE, - part->triangle_buffer.count, + triangles->count, &part->vertex_buffer, NONE, ¢roid, @@ -414,9 +430,9 @@ static void render_model_parts( rasterizer_model_draw( shader, forced_shader_permutation_index ? forced_shader_permutation_index : shader_reference->permutation_index, - &part->triangle_buffer, + triangles, NONE, - part->triangle_buffer.count, + triangles->count, &part->vertex_buffer, NONE); } @@ -436,9 +452,9 @@ static void render_model_parts( rasterizer_model_draw( shader, forced_shader_permutation_index ? forced_shader_permutation_index : shader_reference->permutation_index, - &part->triangle_buffer, + triangles, NONE, - part->triangle_buffer.count, + triangles->count, &part->vertex_buffer, NONE); rasterizer_debug_model_vertices(object_index, skinning, part); diff --git a/source/networking/network_client_manager.c b/source/networking/network_client_manager.c index b70aa5abee..a6aeb2cf3a 100644 --- a/source/networking/network_client_manager.c +++ b/source/networking/network_client_manager.c @@ -388,6 +388,7 @@ symbols in this file: #include "networking/network_connection.h" #include "networking/network_game_globals.h" #include "networking/network_game_manager.h" +#include "third_person_protocol.h" /* port: port/linux/game/third_person_protocol.c */ void network_game_client_reset_settings_staging(void); /* port: discard partial settings across connections */ #include "mcc_cache.h" /* port: MCC-only origin-change admission guard */ #include "mcc_identity.h" /* port: MCC content admission and local package resolution */ @@ -395,6 +396,7 @@ void network_game_client_reset_settings_staging(void); /* port: discard partial #include "networking/network_messages.h" #include "networking/network_server_manager.h" #include "text/unicode.h" +#include "third_person.h" /* port: port/linux/game/third_person_policy.c */ #include "map_share.h" /* port: port/linux/game/map_share.c */ #include "custom_edition_cache.h" /* port: port/linux/game/custom_edition_cache.c */ @@ -934,6 +936,7 @@ void network_game_client_dispose( if (client) { network_game_client_reset_settings_staging(); /* port: discard partial old-host settings */ + third_person_session_client_clear(); /* port: discard camera permission too */ mcc_identity_disconnect(); /* port: discard the MCC session's local binding */ if (client->connection) network_connection_delete(client->connection); @@ -1307,6 +1310,8 @@ boolean network_game_client_game_settings_updated( added (network_game_add_player) */ message_packet->maximum_players > 0 && message_packet->maximum_players <= MAXIMUM_NUMBER_OF_PLAYERS && + /* port: reject unknown flags and the reserved camera policy. */ + third_person_match_flags_valid(message_packet->cooperative_flags) && network_game_client_map_name_is_valid(message_packet->map.name, sizeof(message_packet->map.name)) && VALID_INDEX(message_packet->difficulty, NUMBER_OF_GAME_DIFFICULTY_LEVELS)) { @@ -2135,6 +2140,24 @@ boolean network_game_client_initiate_join_game( 0x157, client && (client->state == _network_game_client_state_searching) && game && join_parameters && client->connection && !network_connection_connected(client->connection) && (game->platform == network_game_get_local_platform())); + /* port: bind the capability to the selected advertisement, not a prior host. */ + network_game_client_reset_settings_staging(); /* port: a new host starts a new record */ + { + unsigned int camera_version = 0; + long advertised_index; + /* port: the host joins its own loopback server using a temporary + * advertisement, which is not an entry in available_games. */ + if (global_network_game_server_get() && + address->address.long_words[0] == IPV4_LOOPBACK_ADDRESS) + camera_version = third_person_session_version(game->map.name); + else for (advertised_index = 0; advertised_index < MAXIMUM_NETWORK_ADVERTISED_GAMES; advertised_index++) + if (game == &client->available_games[advertised_index]) + { + camera_version = network_game_client_advertised_versions[advertised_index].version; + break; + } + third_person_session_client_begin(camera_version); /* port: host state owns loopback mode */ + } client->join_in_progress = TRUE; client->connect_process = 0; client->connection_attempt_time = system_milliseconds(); @@ -2162,6 +2185,7 @@ boolean network_game_client_initiate_join_game( else { client->join_in_progress = FALSE; + third_person_session_client_clear(); /* port: failed connection grants no camera permission */ display_error_when_main_menu_loaded(7); network_event( "failed attempt to initiate a connection to game @ %s", @@ -2299,6 +2323,7 @@ void network_game_client_reset( 0x4EE, client); + third_person_session_client_clear(); /* port: a reset ends the selected camera session */ network_game_invalidate(&client->game); client->machine_index = NONE; @@ -2383,6 +2408,7 @@ void network_game_client_rejected_by_game( word rejection_code) { const char *reason = ""; + boolean camera_retry = third_person_session_active(); /* port: retain only for the same-host pass retry */ match_assert( "c:\\halo\\SOURCE\\networking\\network_client_manager.c", @@ -2477,6 +2503,8 @@ void network_game_client_rejected_by_game( network_game_client_joining_with_link = FALSE; if (joining) { + /* port: the temporary advertisement has no camera metadata; this is the same host. */ + third_person_session_client_begin(camera_retry ? THIRD_PERSON_PROTOCOL_VERSION : 0); network_event("joining again with a Discord account's pass"); network_game_client_joined_again_with_link = TRUE; return; @@ -2976,6 +3004,7 @@ static boolean network_game_client_idle_joining( { struct message_client_join_game_request join_game_request; message_header *message; + word camera_join[THIRD_PERSON_PROTOCOL_JOIN_MAX / sizeof(word)]; /* port: required camera admission */ csmemset(&join_game_request, 0, sizeof(join_game_request)); join_game_request.network_version = HALO_PORT_NETWORK_VERSION; /* port: explicit shared agreement */ @@ -3012,6 +3041,8 @@ static boolean network_game_client_idle_joining( _message_client_join_game_request, &join_game_request, sizeof(join_game_request)); + if (message && third_person_session_active()) /* port: only negotiated camera sessions */ + message = (message_header *)third_person_protocol_join(message, GET_MESSAGE_SIZE(*message), camera_join); if (message) { if (network_game_client_write( @@ -3308,7 +3339,6 @@ boolean network_game_client_advertised_game_compatible( boolean tell) { long game_index = client ? game - client->available_games : NONE; - unsigned int ours = HALO_PORT_NETWORK_VERSION; unsigned int theirs; boolean distributed; @@ -3317,7 +3347,8 @@ boolean network_game_client_advertised_game_compatible( theirs = network_game_client_advertised_versions[game_index].version; distributed = (network_game_client_advertised_versions[game_index].flags & HALO_PORT_ADVERTISED_DISTRIBUTED_FLAG) != 0; - if (theirs == ours && distributed) + if (third_person_session_compatible(game->map.name, theirs, + network_game_client_advertised_versions[game_index].flags)) /* port: exact base or camera agreement */ { network_event("joining a host of network version %u", theirs); return TRUE; @@ -3334,7 +3365,7 @@ void network_game_client_tell_version( boolean distributed) { unsigned int ours = HALO_PORT_NETWORK_VERSION; - char message[400]; + char message[600]; /* port: room for the experimental branch's compatibility notice */ if (theirs == ours) { @@ -3358,6 +3389,9 @@ void network_game_client_tell_version( "Ask the host to update the game.", ours, theirs); } + /* port: numeric ordering alone cannot explain this branch's reserved versions. */ + csstrcat(message, "\n\nGulchCE Third Person sessions require a matching camera build. " + "OpenCE Crossplay sessions use the shared OpenCE protocol with multiplayer third person disabled."); network_event("not joining a host of network version %u%s (this machine's is %u)", theirs, distributed ? "" : " with the lockstep netcode", ours); platform_show_message("Halo: cannot join this game", message); diff --git a/source/networking/network_game_manager.c b/source/networking/network_game_manager.c index c2367f93ff..fea9b3e779 100644 --- a/source/networking/network_game_manager.c +++ b/source/networking/network_game_manager.c @@ -844,7 +844,11 @@ boolean network_game_create_game_objects( game->local_data.game_objects_loaded = FALSE; return FALSE; } - error(0, "game_load() failed."); + /* port: retain the existing error priority and network failure path. */ + if (custom_edition_level_name(options.map_name)) + error(0, "%s", custom_edition_cache_load_error(options.map_name)); + else + error(0, "game_load() failed."); } return game->local_data.game_objects_loaded; diff --git a/source/networking/network_server_manager.c b/source/networking/network_server_manager.c index 7db3e19b94..a52fe587e3 100644 --- a/source/networking/network_server_manager.c +++ b/source/networking/network_server_manager.c @@ -478,6 +478,8 @@ symbols in this file: #include "cache/cache_files.h" #include "interface/player_ui.h" +#include "third_person.h" /* port: port/linux/game/third_person_policy.c */ +#include "third_person_protocol.h" /* port: session compatibility lifecycle */ #include "tag_files/tag_files.h" #include "map_share.h" /* port: port/linux/game/map_share.c */ #include "server_director.h" /* port: port/linux/game/server_director.c */ @@ -1386,8 +1388,14 @@ struct network_game_server *network_game_server_create( network_game_server_reject_connection_game_is_full); network_game_invalidate(&server->game); + /* port: every match path, including quickstart and co-op, starts + with the host's camera rule. Subsequent rounds retain it. */ + third_person_session_host_begin(); + if (third_person_session_active()) + server->game.cooperative_flags |= third_person_host_policy() << THIRD_PERSON_POLICY_SHIFT; server->game.difficulty = main_get_difficulty(); + bots_network_session_begin(); /* port: reserve bot IDs only for an opted-in host */ server->game.number_of_games_played = -1; for (i = 0; i < MAXIMUM_NETWORK_MACHINE_COUNT; i++) @@ -1434,6 +1442,8 @@ struct network_game_server *network_game_server_create( void network_game_server_dispose( struct network_game_server *server) { + third_person_session_host_end(); /* port: discard the prior camera contract */ + bots_network_session_end(); /* port: bot policy belongs to this host alone */ match_assert(NETWORK_SERVER_MANAGER_FILE, 0x120, server); /* port: this server's MCC validation, pending map and restarts end with it */ @@ -1605,7 +1615,8 @@ static void network_game_server_list( char gametype[NUMBEROF(game->variant.human_readable_game_description) + 1]; boolean in_progress = state != _network_game_server_state_pregame || network_game_server_game_is_loading(server); boolean open = state == _network_game_server_state_ingame ? network_game_server_accepts_late_joins(server) : - network_game_server_game_is_open(server) && network_game_has_free_player_slot(game); + network_game_server_game_is_open(server) && + (network_game_has_free_player_slot(game) || bots_population_can_join(server)); /* port: bots yield to humans */ listing_text(name, sizeof(name), game->name, NUMBEROF(game->name)); listing_text(gametype, sizeof(gametype), game->variant.human_readable_game_description, @@ -1626,15 +1637,14 @@ static void network_game_server_list( } /* port: the bots (port/linux/game/bots.c, the settings' bots.count and -bots.teams): in the lobby of a local (split screen) Slayer game, as many bot +bots.teams): in an allowed lobby (bots_session_allowed), as many bot players as the settings ask for, as far as the game has room, each the one player of a machine of its own (BOTS_FIRST_MACHINE up, which no real machine is). In a team game they even the teams with the players or, for bots.teams "against", all take the team the players are not on; the players may change teams in the lobby, and the bots follow. They leave when the setting asks -for fewer, or the game is another gametype. Not once the game has been -started, nor in a game other machines may join (system link and internet -games: no bots there, which would need the clients told) */ +for fewer or the gametype is unsupported. Admission ends when the game +starts. Optional network bots use existing player records and tick actions */ static void network_game_server_port_bots( struct network_game_server *server) { @@ -1648,8 +1658,9 @@ static void network_game_server_port_bots( if (server->state != _network_game_server_state_pregame || server->sent_start_game_message) return; - if (network_game_is_splitscreen_local() && server->game.variant.game_engine_index == game_engine_slayer) - wanted = PIN(bots_wanted_count(), 0, BOTS_MAXIMUM); + /* port: optional bot objectives are selected by the feature module. */ + if (bots_session_allowed() && bots_gametype_allowed(server->game.variant.game_engine_index)) + wanted = PIN(bots_population_wanted(&server->game), 0, BOTS_MAXIMUM); /* port: humans replace network bots */ for (bot_index = 0; bot_index < BOTS_MAXIMUM; bot_index++) slot_of_bot[bot_index] = NONE; for (slot = 0; slot < MAXIMUM_NETWORK_PLAYER_COUNT; slot++) @@ -1658,7 +1669,8 @@ static void network_game_server_port_bots( if (!network_player_is_valid(player)) continue; - if (bots_machine_is_bot(player->machine_index)) + /* port: only players this host actually added as bots, never high-ID clients. */ + if (bots_player_owned(player->machine_index)) slot_of_bot[player->machine_index - BOTS_FIRST_MACHINE] = slot; else if (VALID_INDEX(player->team_index, NUMBER_OF_MULTIPLAYER_TEAMS)) { @@ -1680,6 +1692,7 @@ static void network_game_server_port_bots( if (network_game_remove_player(&server->game, &leaving)) { + bots_player_ownership(leaving.machine_index, FALSE); /* port: release this bot's identity */ network_event("bots: bot %ld left the lobby", bot_index + 1); changed = TRUE; } @@ -1709,6 +1722,7 @@ static void network_game_server_port_bots( joining.player_list_index = NONE; if (!network_game_add_player(&server->game, &joining)) break; + bots_player_ownership(joining.machine_index, TRUE); /* port: host-owned synthetic player */ network_event("bots: bot %ld joined the lobby (team %ld)", bot_index + 1, team_index); changed = TRUE; } @@ -1723,6 +1737,11 @@ static void network_game_server_port_bots( network_event("network_game_server_port_bots() failed to send updated game settings to clients"); } +/* port: host bot controls need this module's private player dispatch. */ +#include "bots_management.inl" +/* port: automatic replacement/restoration owns its state in the bot feature. */ +#include "bots_population.inl" + boolean network_game_server_idle( struct network_game_server *server) { @@ -1742,9 +1761,10 @@ boolean network_game_server_idle( mcc_ui_network_update_map(server); /* port: apply pending MCC selection after local admission */ /* port: the bots of a local game (port/linux/game/bots.c) */ network_game_server_port_bots(server); + bots_population_update(server); /* port: restore network bots after humans leave */ /* (what Discord shows of a game hosted for internet play, and the server browser's listing) */ - p2p_set_game_player_counts(server->game.player_count, server->game.maximum_players); + p2p_set_game_player_counts(bots_human_count(&server->game), server->game.maximum_players); /* port: advertise humans */ network_game_server_list(server); if (network_game_server_game_is_valid(server)) @@ -2008,6 +2028,7 @@ boolean network_game_server_start_network_game( /* port: an MCC check still in progress is a successful idle, not a failed connection. Keep the countdown pending until its validated settings are sent. */ if (mcc_ui_network_map_pending(server)) return TRUE; + third_person_session_lock(); /* port: non-menu hosts also fix the session contract before starting */ if (server->sent_start_game_message == FALSE) { @@ -2736,6 +2757,7 @@ boolean network_game_server_add_player_to_game( if (machine->machine_index == player->machine_index) { + bots_population_pregame_join(server, player); /* port: a validated human can replace a lobby bot */ /* port: the smaller team (the Xbox game took turns with a counter of its own, which a failed add or an earlier game moved on) */ { @@ -2879,6 +2901,7 @@ void network_game_server_update_ticks( } if (server->queued_player_valid) { + boolean waiting_for_bot = FALSE; /* port: retain joins while a bot's departure completes */ /* (a machine's slot is its index; the handlers queued only a machine's own players) */ client_machine_index = server->queued_player.machine_index; @@ -2899,6 +2922,10 @@ void network_game_server_update_ticks( { network_game_server_hold_requested_player(client_machine_index, &server->queued_player); } + else if (client_machine && bots_population_wait_for_slot(server, &server->queued_player)) + { + waiting_for_bot = TRUE; /* port: bounded wait, ordinary departure and addition messages */ + } else if (client_machine && network_game_server_machine_may_add_player_ingame(server, client_machine_index) && network_game_server_add_player_to_game( @@ -2948,7 +2975,7 @@ void network_game_server_update_ticks( } } - server->queued_player_valid = FALSE; + if (!waiting_for_bot) server->queued_player_valid = FALSE; /* port: retry the reserved human */ } } break; @@ -2980,7 +3007,7 @@ boolean network_game_server_accepts_late_joins( refused, network_game_server_refuse_late_joiner) */ return server->state == _network_game_server_state_ingame && network_game_server_game_is_open(server) && - network_game_has_free_player_slot(&server->game); + (network_game_has_free_player_slot(&server->game) || bots_population_can_join(server)); /* port: replaceable bots */ } boolean network_game_server_client_machine_is_loaded( @@ -4397,7 +4424,9 @@ void network_game_server_update_countdown( if (!halo_server_mode() && (network_game_should_accept_remote_connections() == FALSE || network_game_server_get_client_machine_count(server) > 1 || - server_players_on_one_machine(server))) + server_players_on_one_machine(server) || + /* port: owned bots have machine IDs but no connections. */ + bots_lobby_can_start(&server->game))) { unsigned long countdown; @@ -4732,6 +4761,19 @@ void network_game_server_port_set_cooperative_friendly_fire( network_event("network_game_server_port_set_cooperative_friendly_fire() failed to send updated game settings to clients"); } +/* port: update the authoritative pregame record, including late joiners. */ +void network_game_server_port_set_camera_policy(short policy) +{ + struct network_game_server *server = global_network_game_server_get(); + if (!server || server->state != _network_game_server_state_pregame || + !third_person_session_active() || policy < _third_person_player_choice || policy > _third_person_forced_off) + return; + server->game.cooperative_flags = (server->game.cooperative_flags & ~THIRD_PERSON_POLICY_MASK) | + (policy << THIRD_PERSON_POLICY_SHIFT); + if (!network_game_server_send_game_data_pregame(server)) + network_event("failed to send updated camera policy to clients"); +} + void network_game_server_port_set_cooperative_player_collisions( boolean player_collisions) { @@ -4945,6 +4987,8 @@ static boolean network_game_server_add_new_client( { boolean success = FALSE; int i; + /* port: optional bot identities are host-owned, never assigned to a client. */ + long machine_slots = bots_network_reserved() ? BOTS_FIRST_MACHINE : MAXIMUM_NETWORK_MACHINE_COUNT; match_assert(NETWORK_SERVER_MANAGER_FILE, 0x7D4, server && new_connection); @@ -4952,7 +4996,7 @@ static boolean network_game_server_add_new_client( load the game is told so, network_game_server_handle_message_client_join_game_request) */ if (TEST_FLAG(server->flags, _network_game_server_game_open_bit)) { - for (i = 0; i < MAXIMUM_NETWORK_MACHINE_COUNT; i++) + for (i = 0; i < machine_slots; i++) { if (server->client_machines[i].machine_index == NONE) { @@ -5036,7 +5080,7 @@ static boolean network_game_server_add_new_client( } } - if (i == MAXIMUM_NETWORK_MACHINE_COUNT) + if (i == machine_slots) { network_event( "failed to find an available machine slot in network_game_server_add_new_client()"); @@ -5416,7 +5460,7 @@ static boolean network_game_server_idle_pregame_tasks( !network_game_server_client_machine_is_local(server, client_machine) && !network_game_server_machine_has_players(server, client_machine->machine_index) && !map_share_machine_downloading(client_machine->machine_index) && - (!network_game_has_free_player_slot(&server->game) || + ((!network_game_has_free_player_slot(&server->game) && !bots_population_can_join(server)) || /* port: allow bot replacement */ system_milliseconds() - network_game_server_client_machine_join_times[client_machine->machine_index] > NETWORK_GAME_SERVER_PLAYERLESS_MACHINE_TIMEOUT)) { diff --git a/source/networking/network_server_manager.h b/source/networking/network_server_manager.h index f8ba24ac99..084f1e110e 100644 --- a/source/networking/network_server_manager.h +++ b/source/networking/network_server_manager.h @@ -87,6 +87,8 @@ every game the server sets up */ void network_game_server_port_set_settings( wchar_t const *name, long maximum_players); +/* port: host camera rule, editable only before the match starts. */ +void network_game_server_port_set_camera_policy(short policy); /* port: a co-op level was won (main.c). Ends the round for everyone as in multiplayer; the next round is on next_map (NULL repeats the level). */ void network_game_server_port_cooperative_won( diff --git a/source/networking/network_server_message_handler.c b/source/networking/network_server_message_handler.c index 70b26ce824..1054acc8ef 100644 --- a/source/networking/network_server_message_handler.c +++ b/source/networking/network_server_message_handler.c @@ -252,6 +252,7 @@ symbols in this file: #include "network_chat.h" /* port: port/linux/game/network_chat.c */ #include "bungie_net/common/message_header.h" #include "bungie_net/network/transport.h" +#include "bungie_net/network/transport_address_constants.h" /* port: distinguish the host's loopback admission */ #include "bungie_net/network/transport_endpoint_winsock.h" #include "game/game.h" #include "game/game_engine.h" @@ -259,7 +260,9 @@ symbols in this file: #include "networking/network_connection.h" #include "networking/network_game_globals.h" #include "networking/network_game_manager.h" +#include "third_person_protocol.h" /* port: port/linux/game/third_person_protocol.c */ #include "mcc_identity.h" /* port: attach MCC content identity to host settings */ +#include "bots.h" /* port: host-owned population reporting and replaceable capacity */ #include "networking/network_game_protocol.h" #include "networking/network_messages.h" #include "networking/network_server_manager_internal.h" @@ -1191,6 +1194,7 @@ boolean network_game_server_handle_client_message( boolean result = TRUE; word message_type; byte packet_type; + word camera_join[THIRD_PERSON_PROTOCOL_JOIN_MAX / sizeof(word)], camera_join_size; /* port */ /* port: the size comes from the wire, and an assert is no check (an empty message read its packet type from before the buffer): the machine @@ -1202,6 +1206,20 @@ boolean network_game_server_handle_client_message( return FALSE; } + /* port: camera sessions require compatibility before ordinary admission. + The normal join handler still owns tokens, bans and slots. */ + if (third_person_session_active() && !network_game_server_client_machine_is_joined_to_game(server, machine)) + { + if (!third_person_protocol_unwrap(message, message_buffer_size, camera_join, &camera_join_size)) + { + network_event("camera admission rejected: matching online-third-person protocol %u required", + THIRD_PERSON_PROTOCOL_VERSION); + return FALSE; + } + message = camera_join; + message_buffer_size = (short)camera_join_size; + } + match_assert( "c:\\halo\\SOURCE\\networking\\network_server_message_handler.c", 0xCF, @@ -1843,7 +1861,7 @@ static boolean network_game_server_handle_message_client_broadcast_game_search( advertisement.engine_type = (short)game->variant.game_engine_index; csmemcpy(&advertisement.map, &game->map, sizeof(game->map)); advertisement.machine_count = game->machine_count; - advertisement.player_count = game->player_count; + advertisement.player_count = bots_human_count(game); /* port: browser population counts humans */ advertisement.maximum_player_count = game->maximum_players; advertisement.variant_setting = (short)game->variant.universal_variant.score_to_win; advertisement.flags = 0; @@ -1861,8 +1879,9 @@ static boolean network_game_server_handle_message_client_broadcast_game_search( /* the native builds' network version and netcode (a client refuses a host of another version, or of the lockstep netcode older builds had: network_client_manager.c) */ - advertisement.reserved[HALO_PORT_ADVERTISED_VERSION_OFFSET] = (byte)(HALO_PORT_NETWORK_VERSION & 0xFF); - advertisement.reserved[HALO_PORT_ADVERTISED_VERSION_OFFSET + 1] = (byte)(HALO_PORT_NETWORK_VERSION >> 8); + advertisement.reserved[HALO_PORT_ADVERTISED_VERSION_OFFSET] = (byte)(third_person_session_version(game->map.name) & 0xFF); + advertisement.reserved[HALO_PORT_ADVERTISED_VERSION_OFFSET + 1] = (byte)(third_person_session_version(game->map.name) >> 8); + /* port: both session profiles use upstream distributed discovery flags. */ advertisement.reserved[HALO_PORT_ADVERTISED_FLAGS_OFFSET] = HALO_PORT_ADVERTISED_DISTRIBUTED_FLAG; if (network_game_server_get_state(server, NULL) != _network_game_server_state_pregame || @@ -1881,7 +1900,8 @@ static boolean network_game_server_handle_message_client_broadcast_game_search( once it is over, nor in progress when no player can join it) */ if (network_game_server_get_state(server, NULL) == _network_game_server_state_ingame ? network_game_server_accepts_late_joins(server) - : network_game_server_game_is_open(server) && network_game_has_free_player_slot(game)) + : network_game_server_game_is_open(server) && + (network_game_has_free_player_slot(game) || bots_population_can_join(server))) /* port: replaceable bots */ { advertisement.flags |= FLAG(_game_advertisement_open_bit); } @@ -2039,7 +2059,8 @@ static boolean network_game_server_handle_message_client_join_game_request( fill it) is full: a machine that joined could add none, and held the countdown for ever */ boolean full = network_game_server_get_state(server, NULL) == _network_game_server_state_pregame && - !network_game_has_free_player_slot(network_game_server_get_game(server)); + !network_game_has_free_player_slot(network_game_server_get_game(server)) && + !bots_population_can_join(server); /* port: validated humans can replace lobby bots */ /* port: discovery is advisory; direct joins must prove the same shared recovery agreement before ordinary admission. */ @@ -2108,6 +2129,12 @@ static boolean network_game_server_handle_message_client_join_game_request( struct network_machine *client_machine; long machine_index = NONE; + /* port: setup opens the socket before the host's loopback client + has its index. Only remote admission fixes the camera contract. */ + if (source_address.address.long_words[0] != IPV4_LOOPBACK_ADDRESS || + network_game_server_get_game(server)->machine_count > 1) + third_person_session_lock(); + client_machine = network_game_server_get_client_machine( server, server_client_machine, diff --git a/source/objects/damage.c b/source/objects/damage.c index 6a15d539e1..102f06d3d6 100644 --- a/source/objects/damage.c +++ b/source/objects/damage.c @@ -2224,13 +2224,20 @@ static long get_player_index_from_object_or_parents( while (object_index != NONE) { + struct object_datum *object; + if (unit_try_and_get(object_index)) { player_index = player_index_from_unit_index(object_index); break; } - object_index = object_get(object_index)->object.parent_object_index; + /* port: a projectile can outlive its owner; do not dereference a + deleted object or follow a replacement in the same datum slot. */ + object = object_try_and_get(object_index); + if (!object) + break; + object_index = object->object.parent_object_index; } return player_index; diff --git a/source/objects/object_lights.c b/source/objects/object_lights.c index 4050b5dce1..70923b5e4c 100644 --- a/source/objects/object_lights.c +++ b/source/objects/object_lights.c @@ -158,6 +158,7 @@ symbols in this file: #include "game/game.h" #include "game/game_engine.h" #include "interface/first_person_weapons.h" +#include "third_person.h" /* port: port/linux/game/third_person.c */ #include "math/periodic_functions.h" #include "memory/data.h" #include "objects/light_definitions.h" @@ -184,7 +185,13 @@ symbols in this file: #include "tag_files/tag_groups.h" #include "units/units.h" #include "cache/cache_files.h" /* port: (tag_iterator: light_port_glow_definition_get) */ -void shield_glow_update(void); /* port: port/linux/game/shield_glow.c */ +#include "plasma_occlusion.h" /* port: port/linux/game/plasma_occlusion.c */ +#include "muzzle_lighting.h" /* port: port/linux/game/muzzle_lighting.c */ +#include "covenant_lighting.h" /* port: port/linux/game/covenant_lighting.c */ +#include "covenant_emitter_lighting.h" /* port: port/linux/game/covenant_emitter_lighting.c */ +#include "rocket_lighting.h" /* port: port/linux/game/rocket_lighting.c */ +#include "plasma_lighting.h" /* port: port/linux/game/plasma_lighting.c */ +#include "shield_glow.h" /* port: port/linux/game/shield_glow.c */ /* port: port/linux/src (halo.log) */ void platform_log(const char *format, ...); @@ -712,12 +719,18 @@ void lights_initialize( void lights_dispose( void) { + muzzle_lighting_forget(); /* port: discard render-owned pulse identities */ + covenant_lighting_forget(); /* port: discard owned Covenant light identities */ + covenant_emitter_lighting_forget(); /* port: discard render-owned emitter identities */ + rocket_lighting_forget(); /* port: partition and light storage are being discarded */ + plasma_falloff_dispose(); /* port: release optional resources on shutdown too */ + shield_glow_reset(); /* port: discard shield and overshield render state */ cluster_partition_delete(&light_cluster_partition); return; } -/* port: glows the port lights itself (port/linux/game/shield_glow.c): an +/* port: glows owned by the optional dynamic lighting modules: an unattached light (light_new_unattached) on an object's node, kept alive and colored and sized each frame by its maker, gone a moment after its maker stops. Drawn with a light definition the map has (one without a lens flare @@ -777,10 +790,100 @@ boolean light_port_glow_set( return TRUE; } +/* port: move a feature-owned, unattached glow without exposing private light + storage. Muzzle markers may use a different rendered pose for each view. */ +boolean light_port_glow_move(long light_index, real_point3d const *position) +{ + struct light_datum *light; + if (!light_data->valid || light_index == NONE) + return FALSE; + light = (struct light_datum *)datum_try_and_get(light_data, light_index); + if (!light || light->object_index != NONE || light->definition_index != light_port_glow_definition || + !TEST_FLAG(light->flags, _point_light_port_glow_bit)) + return FALSE; + if (TEST_FLAG(light->flags, _point_light_connected_to_map_bit)) + light_disconnect_from_map(light_index); + light->position = *position; + light_reconnect_to_map(light_index); + return TRUE; +} + +/* port: the light definition layout is private to this implementation. */ +float plasma_occlusion_specular_scale(long rasterizer_index) +{ + real scale; + if (rasterizer_index < 0 || rasterizer_index >= rasterizer_lights.light_count) + return 1.0f; + scale = rasterizer_lights.lights[rasterizer_index].definition->specular_radius_multiplier; + return scale > 0.0f ? scale : 1.0f; +} + +/* port: this bridge keeps private light storage and partition ownership here. + The caller restores attachments after render interpolation ends. */ +int light_port_refresh_attachment(long light_index, long object_index) +{ + struct light_datum *light; + + if (!light_data->valid || light_index == NONE || object_index == NONE) + return FALSE; + light = (struct light_datum *)datum_try_and_get(light_data, light_index); + if (!light || light->object_index != object_index || + light->parent_light_index != NONE || !object_try_and_get(object_index)) + return FALSE; + /* port: the engine can retain attachments while their object is outside + the map. Render interpolation must not reconnect those lights. */ + if (TEST_FLAG(light->flags, _point_light_connects_to_map_bit) && + !TEST_FLAG(light->flags, _point_light_connected_to_map_bit)) + return FALSE; + light_disconnect_from_map(light_index); + light_reconnect_to_map(light_index); + return TRUE; +} + +/* port: save/restore a render-owned radius without exposing light datums. */ +int light_port_attachment_radius(long light_index, long object_index, float *radius, int restore) +{ + struct light_datum *light; + if (!light_data->valid || light_index == NONE || object_index == NONE) + return FALSE; + light = (struct light_datum *)datum_try_and_get(light_data, light_index); + if (!light || light->object_index != object_index || light->parent_light_index != NONE || + !object_try_and_get(object_index)) + return FALSE; + if (restore) + light->radius = *radius; + else + *radius = light->radius; + return TRUE; +} + +/* port: render-only promotion of a selected lens-flare attachment. Return its + original dynamic flag so the feature can restore it without changing tags. */ +int light_port_dynamic_set(long light_index, long object_index, int enabled) +{ + struct light_datum *light; + int previous; + if (!light_data->valid || light_index == NONE || object_index == NONE) + return FALSE; + light = (struct light_datum *)datum_try_and_get(light_data, light_index); + if (!light || light->object_index != object_index || light->parent_light_index != NONE) + return FALSE; + previous = TEST_FLAG(light->flags, _point_light_dynamic_bit); + SET_FLAG(light->flags, _point_light_dynamic_bit, enabled); + return previous; +} + void lights_initialize_for_new_map( void) { + muzzle_lighting_forget(); /* port: discard render-owned pulse identities */ + covenant_lighting_forget(); /* port: discard owned Covenant light identities */ + covenant_emitter_lighting_forget(); /* port: discard render-owned emitter identities */ + rocket_lighting_forget(); /* port: includes light-array recovery */ light_port_glow_definition = NONE - 1; /* port: (looked for again) */ + plasma_lighting_reset(); /* port: discard render-only attachment identities */ + plasma_falloff_dispose(); /* port: release the previous map's optional texture */ + shield_glow_reset(); /* port: discard handles from the previous light array */ data_make_valid(light_data); lights_game_globals->render_lights = TRUE; cluster_partition_make_valid(&light_cluster_partition); @@ -791,6 +894,13 @@ void lights_initialize_for_new_map( void lights_dispose_from_old_map( void) { + muzzle_lighting_forget(); /* port: discard render-owned pulse identities */ + covenant_lighting_forget(); /* port: discard owned Covenant light identities */ + covenant_emitter_lighting_forget(); /* port: discard render-owned emitter identities */ + rocket_lighting_forget(); /* port: no flight-light handles cross map loads */ + plasma_lighting_reset(); /* port: no attachment identities cross map loads */ + plasma_falloff_dispose(); /* port: release feature-owned attenuation */ + shield_glow_reset(); /* port: release feature state before invalidating map lights */ data_make_invalid(light_data); cluster_partition_make_invalid(&light_cluster_partition); @@ -974,6 +1084,10 @@ void lights_preprocess_scene( /* port: the lights in order before they are drawn (a frame can come between ticks: lights_port_recover) */ lights_port_recover(); + muzzle_lighting_update(); /* port: render-time muzzle poses and pulse fade */ + covenant_lighting_update(); /* port: missing Covenant flight lights */ + covenant_emitter_lighting_update(); /* port: feature-owned rendered emitter poses */ + rocket_lighting_update(); /* port: create flight lights before visibility collection */ shield_glow_update(); /* port: port/linux/game/shield_glow.c */ for (light_index = data_next_index(light_data, NONE); light_index != NONE; @@ -987,6 +1101,11 @@ void lights_preprocess_scene( FALSE); light->rasterizer_light_index = NONE; lights_port.radius_writes++; + /* port: pass the private definition identity for exact emitter selection; + refresh selected persistent attachments at the render pose, + before visibility and receiver selection (plasma_lighting.c). */ + if (light->parent_light_index == NONE) + plasma_lighting_prepare(light_index, light->object_index, light->definition_index); if (light->parent_light_index != NONE) { struct point_light_definition *definition = light_definition_get( @@ -1020,6 +1139,7 @@ void lights_preprocess_scene( light_mark); light_marker_end(); rasterizer_lights_begin(); + plasma_lighting_window_begin(); /* port: submitted light indices belong to this view */ for (rendered_cluster_index = 0; rendered_cluster_index < render.rendered_cluster_count; rendered_cluster_index++) @@ -1150,6 +1270,8 @@ void lights_preprocess_scene( /* port: a glow's radius is as set (light_port_glow_set) */ if (TEST_FLAG(light->flags, _point_light_port_glow_bit)) light->radius = light->intensity_scale; + /* port: feature-owned radius policy also feeds receiver selection. */ + light->radius = plasma_lighting_radius(scene_light_handle, light->object_index, light->radius); lights_port.radius_writes++; if (light->radius != 0.0f) { @@ -1162,6 +1284,10 @@ void lights_preprocess_scene( light_parameters.up = light->up; light_parameters.radius = light->radius; light_parameters.color = light->color; + /* port: optional flight-light tint affects only this render copy; + the authored datum still supplies flares and simulation queries. */ + if (light->parent_light_index == NONE) + covenant_lighting_color(light->object_index, light->definition_index, &light_parameters.color); match_assert( "c:\\halo\\SOURCE\\objects\\object_lights.c", 0x1EE, @@ -1175,7 +1301,8 @@ void lights_preprocess_scene( 0x1F0, light->color.blue >=0.0f && light->color.blue <=1.0f); - if (light->parent_light_index == NONE) + /* port: shoulder-view lights stay on the world weapon. */ + if (light->parent_light_index == NONE && !third_person_active(render.local_player_index)) { boolean adjusted = FALSE; @@ -1236,6 +1363,8 @@ void lights_preprocess_scene( light->rasterizer_light_index = rasterizer_light_submit( &light_parameters); + /* port: identify only this feature's existing submitted lights. */ + plasma_lighting_submitted(scene_light_handle, light->rasterizer_light_index); /* (port: the lights submitted so far: not a light the window had no room for (MAXIMUM_LIGHTS_PER_WINDOW), whose index is NONE: that made the count 0, and every object @@ -1285,7 +1414,9 @@ void lights_preprocess_scene( short marker_index; if (object->object.type == _object_type_weapon - && object->object.parent_object_index != NONE) + && object->object.parent_object_index != NONE + /* port: show the charge flare at the world muzzle. */ + && !third_person_active(render.local_player_index)) { marker_count = first_person_weapon_get_marker_by_name_render( light->object_index, @@ -1760,6 +1891,18 @@ static void light_compute_bounding_sphere( ? definition->radius_modifier_upper_bound * definition->radius : light->radius; + /* port: expanded render lights must reach the same visibility clusters. + Owned glow radii are independent of their borrowed light template. */ + if (maximum) + { + light_radius = shield_glow_radius(light_index, light_radius); /* port: body-sized shield bounds */ + light_radius = muzzle_lighting_radius(light_index, light_radius); /* port: owned flash bounds */ + light_radius = covenant_emitter_lighting_radius(light_index, light_radius); /* port: owned emitter bounds */ + light_radius = covenant_lighting_radius(light_index, light->object_index, light_radius); /* port: owned Covenant bounds */ + light_radius = rocket_lighting_radius(light_index, light->object_index, light_radius); + light_radius = plasma_lighting_radius(light_index, light->object_index, light_radius); + } + if (!TEST_FLAG(definition->flags, _light_definition_no_specular_bit) && (specular || maximum)) { diff --git a/source/objects/objects.c b/source/objects/objects.c index e502a22aed..2b4b02d558 100644 --- a/source/objects/objects.c +++ b/source/objects/objects.c @@ -64,6 +64,7 @@ OBJECTS.C void object_bounds_cache_update(long object_index, real_point3d const *center, real radius); /* port: port/linux/game/first_person_legs.c's */ void first_person_legs_reset(void); +#include "third_person.h" /* port: port/linux/game/third_person.c */ /* ---------- constants */ @@ -1120,6 +1121,8 @@ void objects_initialize_for_new_map( /* port: the last map's waist and mesh forgotten (port/linux/game/first_person_legs.c) */ first_person_legs_reset(); + /* port: reset the shoulder camera across map loads. */ + third_person_reset(); data_make_valid(object_header_data); /* port: (zeroed for a new map only: a revert or a load brings them back with the bipeds' snapshots) */ @@ -1147,6 +1150,7 @@ void objects_dispose_from_old_map( widgets_dispose_from_old_map(); object_types_dispose_from_old_map(); lights_dispose_from_old_map(); + first_person_legs_reset(); /* port: (and on a failed load's way out) */ if (object_header_data->valid) { @@ -3967,9 +3971,18 @@ void object_attach_to_node( return; } +/* port: muzzle shots must exclude their shooter during the safety check. */ boolean object_force_inside_bsp( long object_index, real_point3d const *known_good_point) +{ + return object_force_inside_bsp_ignoring(object_index, known_good_point, NONE); +} + +boolean object_force_inside_bsp_ignoring( + long object_index, + real_point3d const *known_good_point, + long ignore_object_index) { struct collision_result collision; @@ -3979,7 +3992,7 @@ boolean object_force_inside_bsp( match_assert("c:\\halo\\SOURCE\\objects\\objects.c", 2365, global_current_collision_user_depth < MAXIMUM_COLLISION_USER_STACK_DEPTH); global_current_collision_users[global_current_collision_user_depth++] = 19; - if (collision_test_line(_collision_test_for_projectiles_flags, known_good_point, &object->object.position, NONE, &collision) || + if (collision_test_line(_collision_test_for_projectiles_flags, known_good_point, &object->object.position, ignore_object_index, &collision) || object->object.location.cluster_index==NONE) { if (collision.location.cluster_index!=NONE) diff --git a/source/objects/objects.h b/source/objects/objects.h index 177cbcbbb4..9fd6767e1d 100644 --- a/source/objects/objects.h +++ b/source/objects/objects.h @@ -472,6 +472,8 @@ void object_translate(long object_index, real_point3d const *new_position, struc long object_new(struct object_placement_data *data); void object_attach_to_node(long parent_object_index, long child_object_index, short parent_node_index); boolean object_force_inside_bsp(long object_index, real_point3d const *known_good_point); +/* port: exclude the shooter when validating a muzzle-origin projectile. */ +boolean object_force_inside_bsp_ignoring(long object_index, real_point3d const *known_good_point, long ignore_object_index); void object_compute_node_matrices_recursive(long object_index); long object_new_from_scenario(struct scenario_object_datum *scenario_object, struct tag_block *palette); void object_attach_to_marker(long parent_object_index, char const *parent_marker_name, long child_object_index, char const *child_marker_name); diff --git a/source/objects/widgets/flags.c b/source/objects/widgets/flags.c index 63a1aea6c6..747f29387a 100644 --- a/source/objects/widgets/flags.c +++ b/source/objects/widgets/flags.c @@ -221,6 +221,13 @@ static real flag_pending_delta = 0.0f; /* ---------- public code */ +/* port: discard partial frame time across maps and checkpoint restores. */ +void flags_reset_render_state(void) +{ + flag_last_step_game_time = NONE; + flag_pending_delta = 0.0f; +} + void flags_initialize( void) { @@ -245,6 +252,7 @@ void flags_initialize_for_new_map( void flags_dispose_from_old_map( void) { + flags_reset_render_state(); /* port: reset the render clock */ data_make_invalid(flag_data); return; diff --git a/source/objects/widgets/flags.h b/source/objects/widgets/flags.h index dc0b89a304..5c8e8ddef8 100644 --- a/source/objects/widgets/flags.h +++ b/source/objects/widgets/flags.h @@ -46,4 +46,7 @@ extern struct data_array *flag_data; /* ---------- public code */ +/* port: clear render-only state after a checkpoint load. */ +void flags_reset_render_state(void); + #endif // __FLAGS_H diff --git a/source/objects/widgets/glow.c b/source/objects/widgets/glow.c index 64b1326973..67b59b9c2a 100644 --- a/source/objects/widgets/glow.c +++ b/source/objects/widgets/glow.c @@ -829,7 +829,11 @@ static void get_particle_world_position( for (marker_index = 0; marker_index < glow->number_of_markers - 1; marker_index++) { if (glow->marker_time_index[marker_index] <= particle->t && - glow->marker_time_index[marker_index + 1] > particle->t) + (glow->marker_time_index[marker_index + 1] > particle->t || + /* port: particle updates/random ranges admit the final endpoint. + Keep interior boundaries half-open, but include the last marker. */ + (marker_index == glow->number_of_markers - 2 && + particle->t == glow->marker_time_index[marker_index + 1]))) { break; } diff --git a/source/objects/widgets/lightning.c b/source/objects/widgets/lightning.c index 04fbf79a05..80592f9972 100644 --- a/source/objects/widgets/lightning.c +++ b/source/objects/widgets/lightning.c @@ -194,13 +194,20 @@ void lightnings_dispose( return; } +/* port: render-only seeds are not part of a restored game state's pool. */ +void lightnings_reset_render_state( + void) +{ + csmemset(lightning_tick_seeds, 0, sizeof(lightning_tick_seeds)); +} + void lightnings_initialize_for_new_map( void) { if (lightning_globals.lightning_data) data_make_valid(lightning_globals.lightning_data); /* port: (lightning_submit) */ - csmemset(lightning_tick_seeds, 0, sizeof(lightning_tick_seeds)); + lightnings_reset_render_state(); return; } @@ -210,6 +217,8 @@ void lightnings_dispose_from_old_map( { if (lightning_globals.lightning_data) data_make_invalid(lightning_globals.lightning_data); + /* port: discard the old map's render-only cache. */ + lightnings_reset_render_state(); return; } diff --git a/source/objects/widgets/lightning.h b/source/objects/widgets/lightning.h index 11dd86a4b3..3a8f43f4b4 100644 --- a/source/objects/widgets/lightning.h +++ b/source/objects/widgets/lightning.h @@ -42,6 +42,9 @@ typedef char lightning_datum_size_assert[ /* ---------- prototypes/LIGHTNING.C */ +/* port: invalidate render-only seeds after restoring the game state. */ +void lightnings_reset_render_state(void); + void lightnings_initialize( void); diff --git a/source/physics/collision_bsp.c b/source/physics/collision_bsp.c index cba14b6c86..cc9a20c1a5 100644 --- a/source/physics/collision_bsp.c +++ b/source/physics/collision_bsp.c @@ -230,10 +230,12 @@ struct collision_bsp_test_vector_context long last_plane_index; /* port: (as in collision_bsp_test_pill_new_context) */ long nodes_left; + /* port: only an explicit synchronous batch reuses node/point data. */ + struct collision_bsp_vector_cache *cache; }; typedef char collision_bsp_test_vector_context_size_assert[ - sizeof(struct collision_bsp_test_vector_context) == 0x28 + 4 ? 1 : -1]; + sizeof(struct collision_bsp_test_vector_context) == 0x28 + 8 ? 1 : -1]; /* port: batch scratch */ struct collision_bsp_usage_times { @@ -1217,7 +1219,9 @@ boolean collision_bsp_test_sphere( return result->surface_count > 0 || result->edge_count > 0; } -boolean collision_bsp_test_vector( +/* port: a render-only batch may prove a common prefix of the tree. Keep the +same traversal, leaf order, intersection tests and remaining safety budgets. */ +static boolean collision_bsp_test_vector_at_node( unsigned long flags, struct collision_bsp const *bsp, short breakable_surface_count, @@ -1225,7 +1229,10 @@ boolean collision_bsp_test_vector( real_point3d const *point, real_vector3d const *vector, real maximum_t, - struct collision_bsp_test_vector_result *result) + struct collision_bsp_test_vector_result *result, + long start_node, + short start_depth, + struct collision_bsp_vector_cache *cache) { struct collision_bsp_test_vector_context context; short collision_function = 4 + (bsp == global_collision_bsp); @@ -1242,16 +1249,17 @@ boolean collision_bsp_test_vector( context.point = point; context.vector = vector; context.result = result; + context.cache = cache; /* port: stock callers pass NULL */ result->t = maximum_t < 0.f ? 0.f : maximum_t; context.last_leaf_index = NONE; context.last_plane_index = NONE; result->leaf_count = 0; context.last_contents = _contents_unknown; /* port: (collision_bsp3d_enter_node) */ - context.nodes_left = bsp->bsp3d.nodes.count; + context.nodes_left = bsp->bsp3d.nodes.count - start_depth; t = PIN(maximum_t, 0.f, 1.f); - return_value = collision_bsp_test_vector_recursive(&context, 0, 0.f, t, 0); + return_value = collision_bsp_test_vector_recursive(&context, start_node, 0.f, t, start_depth); collision_log_end_time( collision_function, collision_bsp_usage_times.vector.QuadPart); @@ -1259,6 +1267,40 @@ boolean collision_bsp_test_vector( return return_value; } +/* port: stock callers always start at the root, as before. */ +boolean collision_bsp_test_vector( + unsigned long flags, + struct collision_bsp const *bsp, + short breakable_surface_count, + byte const *breakable_surface_flags, + real_point3d const *point, + real_vector3d const *vector, + real maximum_t, + struct collision_bsp_test_vector_result *result) +{ + return collision_bsp_test_vector_at_node(flags, bsp, breakable_surface_count, + breakable_surface_flags, point, vector, maximum_t, result, 0, 0, NULL); +} + +/* port: only callers that proved the entire segment stays in this subtree +may skip its prefix. No global state or change to simulation callers. */ +boolean collision_bsp_test_vector_from_node( + unsigned long flags, + struct collision_bsp const *bsp, + short breakable_surface_count, + byte const *breakable_surface_flags, + real_point3d const *point, + real_vector3d const *vector, + real maximum_t, + struct collision_bsp_test_vector_result *result, + long start_node, + short start_depth, + struct collision_bsp_vector_cache *cache) +{ + return collision_bsp_test_vector_at_node(flags, bsp, breakable_surface_count, + breakable_surface_flags, point, vector, maximum_t, result, start_node, start_depth, cache); +} + /* ---------- private code */ /* port: whether a test may enter a node (from the map) `depth` nodes deep @@ -2140,6 +2182,7 @@ static boolean collision_bsp_test_vector_recursive( real distance1; boolean reaches_back; boolean reaches_front; + unsigned long cache_slot; /* port: batch-only node/point reuse */ /* port: (collision_bsp3d_enter_node: the test ends with no more hits) */ @@ -2147,15 +2190,47 @@ static boolean collision_bsp_test_vector_recursive( { return FALSE; } - node = TAG_BLOCK_GET_ELEMENT( - &data->bsp->bsp3d.nodes, - node_index, - struct bsp3d_node); - plane = TAG_BLOCK_GET_ELEMENT( - &data->bsp->bsp3d.planes, - node->plane_designator, - real_plane3d); - distance = plane3d_distance_to_point(plane, data->point); + /* port: identical BSP and origin throughout the batch. Keep the + original checked lookup and arithmetic on a miss or a stock query. */ + cache_slot = (unsigned long)node_index % COLLISION_VECTOR_CACHE_NODES; + if (data->cache && data->cache->nodes[cache_slot].index_plus_one == node_index + 1) + { + node = data->cache->nodes[cache_slot].node; + plane = data->cache->nodes[cache_slot].plane; + distance = data->cache->nodes[cache_slot].distance; + /* port: batch preparation can prove an entire one-sided chain. + Charge every skipped node to the original depth/visit limits; if + the remaining budget is insufficient, use the original traversal. */ + if (data->cache->nodes[cache_slot].skip_count > 0 && + depth + data->cache->nodes[cache_slot].skip_count <= MAXIMUM_BSP3D_TRAVERSAL_DEPTH && + data->nodes_left >= data->cache->nodes[cache_slot].skip_count - 1) + { + data->nodes_left -= data->cache->nodes[cache_slot].skip_count - 1; + return collision_bsp_test_vector_recursive(data, + data->cache->nodes[cache_slot].skip_node, t0, t1, + depth + data->cache->nodes[cache_slot].skip_count); + } + } + else + { + node = TAG_BLOCK_GET_ELEMENT( + &data->bsp->bsp3d.nodes, + node_index, + struct bsp3d_node); + plane = TAG_BLOCK_GET_ELEMENT( + &data->bsp->bsp3d.planes, + node->plane_designator, + real_plane3d); + distance = plane3d_distance_to_point(plane, data->point); + if (data->cache) + { + data->cache->nodes[cache_slot].index_plus_one = node_index + 1; + data->cache->nodes[cache_slot].node = node; + data->cache->nodes[cache_slot].plane = plane; + data->cache->nodes[cache_slot].distance = distance; + data->cache->nodes[cache_slot].skip_count = 0; /* port: slot replacement */ + } + } dot = dot_product3d(data->vector, &plane->n); distance0 = dot*t0 + distance; distance1 = dot*t1 + distance; diff --git a/source/physics/collision_bsp.h b/source/physics/collision_bsp.h index 3f1e6a10de..1a4a4f3e50 100644 --- a/source/physics/collision_bsp.h +++ b/source/physics/collision_bsp.h @@ -17,6 +17,24 @@ header included in hcex build. /* ---------- structures */ +/* port: optional synchronous vector-batch scratch. Zero before use; all rays +must share the same BSP and point. No pointers may survive the batch. */ +enum { COLLISION_VECTOR_CACHE_NODES = 512 }; +struct collision_bsp_vector_cache +{ + struct + { + long index_plus_one; + struct bsp3d_node const *node; + real_plane3d const *plane; + real distance; + /* port: optional caller-proven one-sided chain for every batch ray. + Skipped nodes must be valid, and never cross a plane or visit a leaf. */ + long skip_node; + short skip_count; + } nodes[COLLISION_VECTOR_CACHE_NODES]; +}; + struct collision_bsp_test_vector_result { real t; @@ -87,6 +105,21 @@ struct collision_bsp_test_sphere_result /* ---------- prototypes/COLLISION_BSP.C */ +/* port: render batches may skip a proven common prefix; callers retain the +original depth and prove the entire segment lies in the requested subtree. */ +boolean collision_bsp_test_vector_from_node( + unsigned long flags, + struct collision_bsp const *bsp, + short breakable_surface_count, + byte const *breakable_surface_flags, + real_point3d const *point, + real_vector3d const *vector, + real maximum_t, + struct collision_bsp_test_vector_result *result, + long start_node, + short start_depth, + struct collision_bsp_vector_cache *cache); + /* port: whether a surface's ring of edges (from the map) goes on to `edge_index` after `edge_count` of its edges (FALSE, reported once, if it leaves the bsp's edges or does not close within a surface's most edges) */ diff --git a/source/rasterizer/rasterizer_text.c b/source/rasterizer/rasterizer_text.c index b495442333..9acff1af22 100644 --- a/source/rasterizer/rasterizer_text.c +++ b/source/rasterizer/rasterizer_text.c @@ -63,6 +63,8 @@ symbols in this file: /* ---------- headers */ +#include "frontend_menu.h" /* port: scoped modern frontend text clipping */ + #include "cseries/cseries.h" #include "cseries/errors.h" #include "bitmaps/bitmap_group.h" @@ -659,6 +661,8 @@ rasterizer_draw_unicode_string( MIN(render.camera.viewport_bounds.x1 - render.camera.viewport_bounds.x0, clip->x1), MIN(render.camera.viewport_bounds.y1 - render.camera.viewport_bounds.y0, clip->y1)); } + /* port: only the current modern widget can extend the centered UI clip. */ + if (clip) frontend_menu_clip_text(clip->x0, clip->x1, &viewport_bounds.x0, &viewport_bounds.x1); /* port: text drawn scaled (rasterizer_text_set_scale) clipped where it reaches the viewport once scaled: the clip as it is before the scale */ diff --git a/source/rasterizer/xbox/rasterizer_xbox.c b/source/rasterizer/xbox/rasterizer_xbox.c index e679734070..0f77c77dca 100644 --- a/source/rasterizer/xbox/rasterizer_xbox.c +++ b/source/rasterizer/xbox/rasterizer_xbox.c @@ -386,6 +386,7 @@ symbols in this file: /* ---------- headers */ #include "cseries.h" +#include "plasma_model_shader.h" /* port: port/linux/game/plasma_lighting.c */ #include "bitmaps/bitmap_group.h" #include "bitmaps/bitmap_group_internal.h" #include "bitmaps/bitmaps.h" @@ -1099,6 +1100,7 @@ void rasterizer_set_model_lighting_point_light( "c:\\halo\\SOURCE\\rasterizer\\xbox\\rasterizer_xbox.c", 2826, lighting_constants); + plasma_model_lighting_slot(light_index, constant_index); /* port: select only this model light slot */ if (light_index != NONE) { struct rasterizer_light_submit_parameters const *light; @@ -1195,6 +1197,7 @@ void rasterizer_set_model_lighting( "c:\\halo\\SOURCE\\rasterizer\\xbox\\rasterizer_xbox.c", 2898, lighting->distant_light_count>=0 && lighting->distant_light_count<=MAXIMUM_RENDERED_DISTANT_LIGHTS); + plasma_model_lighting_reset(); /* port: each model owns its light selection, including ambient-only draws */ if (rasterizer_debug_options.model_lighting_ambient > 0.0f) { csmemset(&lighting_constants, 0, sizeof(lighting_constants)); diff --git a/source/rasterizer/xbox/rasterizer_xbox_draw_primitives.c b/source/rasterizer/xbox/rasterizer_xbox_draw_primitives.c index a94e00565f..80b55091ee 100644 --- a/source/rasterizer/xbox/rasterizer_xbox_draw_primitives.c +++ b/source/rasterizer/xbox/rasterizer_xbox_draw_primitives.c @@ -1879,6 +1879,8 @@ void rasterizer_draw( struct vertex_buffer const *vertex_buffer, long dynamic_vertex_buffer_index) { + /* port: select/compile loading-time materials without submitting geometry. */ + if (material_prepare_draw()) return; match_assert( RASTERIZER_XBOX_DRAW_PRIMITIVES_FILE, 1145, diff --git a/source/rasterizer/xbox/rasterizer_xbox_environment.c b/source/rasterizer/xbox/rasterizer_xbox_environment.c index ba6114c3b0..e100181d67 100644 --- a/source/rasterizer/xbox/rasterizer_xbox_environment.c +++ b/source/rasterizer/xbox/rasterizer_xbox_environment.c @@ -145,6 +145,7 @@ symbols in this file: #include "cseries/errors.h" #include "effects/decals.h" #include "game/game_globals.h" +#include "plasma_lighting.h" /* port: port/linux/game/plasma_falloff.c */ #include "interface/hud_draw.h" #include "bitmaps/bitmaps_inlines.h" #include "math/periodic_functions.h" @@ -1145,6 +1146,7 @@ void _rasterizer_environment_lightmap_begin( void _rasterizer_environment_diffuse_light_end( void) { + plasma_falloff_end(); /* port: restore stock attenuation before the next light */ return; } @@ -1244,6 +1246,7 @@ void _rasterizer_environment_diffuse_light_begin( D3DDevice_SetRenderState( D3DRS_PSCONSTANT0_0, real_rgb_color_to_pixel32(&light->color)); + plasma_falloff_begin(light_index); /* port: scoped to this selected plasma light */ } return; } @@ -1760,6 +1763,7 @@ void _rasterizer_environment_diffuse_texture_draw( void _rasterizer_environment_specular_light_end( void) { + plasma_falloff_end(); /* port: restore the selected plasma specular pass */ return; } @@ -1814,6 +1818,7 @@ void _rasterizer_environment_specular_lights_begin( void _rasterizer_environment_specular_light_begin( long light_index) { + plasma_specular_begin(light_index); /* port: hue for selected enhanced lights only */ match_assert( "c:\\halo\\SOURCE\\rasterizer\\xbox\\rasterizer_xbox_environment.c", 0x5C0, @@ -1918,6 +1923,7 @@ void _rasterizer_environment_specular_light_begin( pixel_shader.final_combiner_inputs_abcd = 0x0C0F0000; pixel_shader.final_combiner_inputs_efg = 0x1D200D00; rasterizer_set_pixel_shader(&pixel_shader); + plasma_falloff_specular_begin(light_index); /* port: selected omni plasma attenuation */ } } return; @@ -2002,6 +2008,9 @@ void _rasterizer_environment_specular_light_draw( real_rgb_color_to_pixel32(&shader_environment->environment.specular.view_perpendicular_color); pixel_shader.constant_1[3] = real_rgb_color_to_pixel32(&shader_environment->environment.specular.view_parallel_color); + /* port: keep enhanced reflections the colour of their emitting light. */ + pixel_shader.constant_0[3] = plasma_specular_color(pixel_shader.constant_0[3]); + pixel_shader.constant_1[3] = plasma_specular_color(pixel_shader.constant_1[3]); if (TEST_FLAG( shader_environment->environment.flags, diff --git a/source/rasterizer/xbox/rasterizer_xbox_models.c b/source/rasterizer/xbox/rasterizer_xbox_models.c index f205c9f848..2d9cc6c04f 100644 --- a/source/rasterizer/xbox/rasterizer_xbox_models.c +++ b/source/rasterizer/xbox/rasterizer_xbox_models.c @@ -123,8 +123,12 @@ symbols in this file: #include "rasterizer/xbox/rasterizer_xbox_draw_primitives.h" #include "rasterizer/xbox/rasterizer_xbox_internal.h" #include "rasterizer/xbox/rasterizer_xbox_models.h" +#include "needler_lighting.h" /* port: port/linux/game/needler_lighting.c */ +#include "ammo_counter_lighting.h" /* port: port/linux/game/ammo_counter_lighting.c */ #include "view_fov.h" /* port: port/linux/game/view_fov.c */ +#include "shield_look.h" /* port: port/linux/game/shield_look.c */ + /* ---------- constants */ enum @@ -1664,7 +1668,10 @@ void _rasterizer_model_draw( NUMBER_OF_SHADER_ANIMATION_FUNCTIONS || !local_parameters->effect.modifier_animation.values || local_parameters->effect.modifier_animation.values[ - intensity_exponent_source-1] != 0.0f) + intensity_exponent_source-1] != 0.0f || + /* port: a recharge layer can outlast the hit intensity function. */ + shield_recharge_visible(local_parameters->effect.modifier_shader, + local_parameters->effect.modifier_animation.values)) { group = _rasterizer_model_transparent_geometry_submit( local_parameters->effect.modifier_shader, @@ -1991,6 +1998,11 @@ void _rasterizer_model_draw( self_illumination_color.blue *= external_color->blue; } + /* port: optional AR screen emission, confined to its authored mask. */ + ammo_counter_lighting_screen(shader, &self_illumination_color); + /* port: optional masked needle emission in both weapon models. */ + needler_lighting_material(shader, &self_illumination_color); + if (shader_model->model.change_color_source>0 && shader_model->model.change_color_source< NUMBER_OF_SHADER_ANIMATION_SOURCES) @@ -2331,6 +2343,9 @@ void _rasterizer_model_draw( shader_model->model.flags, _shader_model_true_atmospheric_fog_bit)); + /* port: boost only the optional AR display material draw. */ + ammo_counter_lighting_draw_begin(shader, pixel_shader.rgb_outputs[7]); + IDirect3DDevice8_SetRenderState( global_d3d_device, D3DRS_CULLMODE, @@ -2419,6 +2434,8 @@ void _rasterizer_model_draw( vertex_buffer); } } + /* port: restore the display output before fog or another material. */ + ammo_counter_lighting_draw_end(); } if (local_environment_fog_screen_flag) diff --git a/source/rasterizer/xbox/rasterizer_xbox_plasma_energy.c b/source/rasterizer/xbox/rasterizer_xbox_plasma_energy.c index f03fd643fd..f264967f66 100644 --- a/source/rasterizer/xbox/rasterizer_xbox_plasma_energy.c +++ b/source/rasterizer/xbox/rasterizer_xbox_plasma_energy.c @@ -40,18 +40,11 @@ symbols in this file: #include #include "rasterizer/xbox/rasterizer_xbox_pixel_shader.h" #include "rasterizer/rasterizer_console_vars.h" -#include "view_fov.h" /* port: port/linux/game/view_fov.c */ +#include "viewmodel_shield.h" /* port: port/linux/game/viewmodel_shield.c */ -/* ---------- constants */ +#include "shield_look.h" /* port: port/linux/game/shield_look.c */ -/* port: rasterizer_xbox_transparent_geometry.c's -_rasterizer_geometry_first_person_bit */ -#define PLASMA_GEOMETRY_FIRST_PERSON_BIT 7 -/* port: the farthest the shield's flare is pushed out from the first-person -arms (display.viewmodel_shield), in world units: a body's shield stands off -much farther than an arm's radius, which so close to the camera fills the -view */ -#define PLASMA_FIRST_PERSON_MAXIMUM_OFFSET 0.0075f +/* ---------- constants */ /* ---------- macros */ @@ -65,8 +58,7 @@ struct plasma_runtime_parameters struct rasterizer_transparent_geometry_group_plasma { - unsigned long geometry_flags; /* port: (the first-person bit) */ - byte reserved04[8]; + byte reserved00[0xC]; struct shader *shader; short bitmap_sequence_index; byte reserved12[0x5A]; @@ -139,14 +131,17 @@ void rasterizer_set_vertex_shader_permutation( void rasterizer_set_pixel_shader( struct pixel_shader_definition const *definition); -/* port: port/linux/game/shield_color.c */ -boolean shield_color_override(real_rgb_color const *colors, real_rgb_color *chosen); -void shield_color_apply(real_rgb_color const *chosen, real_rgb_color const *original, real_rgb_color *result); /* port: port/linux/game/overshield_effect.c */ boolean overshield_effect_draw(real const *values, real *energy_speed, real *inverse_softness, real *height); -boolean overshield_effect_color(real const *values, real_rgb_color *color); +boolean overshield_effect_color(real const *values, real_rgb_color *perpendicular, real_rgb_color *parallel); +/* port: port/linux/game/shield_look.c */ +boolean shield_look_colors(struct shader const *shader, real_rgb_color const *colors, + real_rgb_color *perpendicular, real_rgb_color *parallel); /* port: port/linux/src/d3d8_gl.c */ void d3d8_gl_set_height_fade(float inverse_softness, float height, float offset, float scale); +/* port: draw-local mapping for port/linux/src/shield_honeycomb_gl.h */ +void d3d8_gl_set_shield_honeycomb(float scale, float time, + const float *difference, const float *parallel, float classic_surface); /* ---------- globals */ @@ -166,7 +161,6 @@ void rasterizer_plasma_energy_draw( real_rgb_color const *tint; real intensity; real offset; - real offset_amount; /* port: PLASMA_FIRST_PERSON_MAXIMUM_OFFSET */ real primary_time; real secondary_time; real primary_scale; @@ -174,13 +168,13 @@ void rasterizer_plasma_energy_draw( real vertex_constants[6][4]; real color_constants[3][4]; short source; - real_rgb_color perpendicular_color; /* port: (shield_color.c) */ + real_rgb_color perpendicular_color; /* port: (overshield_effect.c) */ real_rgb_color parallel_color; - real_rgb_color chosen; real energy_speed; /* port: (overshield_effect.c) */ real fade_inverse_softness; real fade_height; boolean overshield; + real honeycomb_scale; /* port: shield_look.c owns the body/arms cell density. */ match_assert( "c:\\halo\\SOURCE\\rasterizer\\xbox\\rasterizer_xbox_plasma_energy.c", @@ -193,14 +187,6 @@ void rasterizer_plasma_energy_draw( tint = global_real_rgb_white; intensity = 1.0f; offset = 0.0f; - /* port: the shield on the first-person arms kept close to them */ - offset_amount = plasma->offset_amount; - if (viewmodel_shield_is_visible() && - TEST_FLAG(group->geometry_flags, PLASMA_GEOMETRY_FIRST_PERSON_BIT) && - offset_amount > PLASMA_FIRST_PERSON_MAXIMUM_OFFSET) - { - offset_amount = PLASMA_FIRST_PERSON_MAXIMUM_OFFSET; - } runtime = group->runtime_parameters; if (runtime) { @@ -221,19 +207,27 @@ void rasterizer_plasma_energy_draw( if (source >= 1 && source <= 4) offset = (real)pow( (double)runtime->exponents[source - 1], - (double)plasma->offset_exponent) * offset_amount; + (double)plasma->offset_exponent) * plasma->offset_amount; + /* port: cap the final displacement on the first-person + arms, after the authored function and exponent scale it + (display.viewmodel_shield); other plasma keeps its own. */ + offset = viewmodel_shield_offset_amount(runtime->exponents, offset); } } - /* port: a local player's shield in the color chosen for it - (port/linux/game/shield_color.c) */ + /* port: the selected recharge envelope preserves colours and arm limits. */ + shield_recharge_draw(group->shader, runtime ? runtime->exponents : NULL, &intensity, &offset); + + /* port: preserve the separate overshield effect + (port/linux/game/overshield_effect.c) */ perpendicular_color = plasma->perpendicular_color; parallel_color = plasma->parallel_color; - if ((runtime && overshield_effect_color(runtime->exponents, &chosen)) || - shield_color_override(runtime ? runtime->colors : NULL, &chosen)) + /* port: inherit authored hue only on feature-owned shield draws. + Overshield layer colours retain precedence. */ + shield_look_colors(group->shader, runtime ? runtime->colors : NULL, + &perpendicular_color, ¶llel_color); + if (runtime && overshield_effect_color(runtime->exponents, &perpendicular_color, ¶llel_color)) { - shield_color_apply(&chosen, &plasma->perpendicular_color, &perpendicular_color); - shield_color_apply(&chosen, &plasma->parallel_color, ¶llel_color); tint = global_real_rgb_white; } @@ -363,9 +357,22 @@ void rasterizer_plasma_energy_draw( plus the animation's offset) */ if (overshield && fade_inverse_softness > 0.0f && primary_scale != 0.0f) d3d8_gl_set_height_fade(fade_inverse_softness, fade_height, vertex_constants[2][3], primary_scale); + /* port: only the selected feature-owned surface uses the procedural + honeycomb on its existing UVs, with no overlapping rear shell. */ + honeycomb_scale = shield_look_honeycomb_scale(group->shader); + if (honeycomb_scale > 0.f) + { + IDirect3DDevice8_SetRenderState(global_d3d_device, D3DRS_CULLMODE, D3DCULL_CCW); + d3d8_gl_set_shield_honeycomb(honeycomb_scale, global_frame_parameters.game_time_sec, + color_constants[1], color_constants[2], shield_look_honeycomb_classic_mode(group->shader)); + } rasterizer_transparent_geometry_group_draw__internal( (struct transparent_geometry_group const *)group, FALSE); + /* port: do not leak the surface or its one-sided shell into subsequent draws. */ + if (honeycomb_scale > 0.f) + IDirect3DDevice8_SetRenderState(global_d3d_device, D3DRS_CULLMODE, D3DCULL_NONE); + d3d8_gl_set_shield_honeycomb(0.f, 0.f, NULL, NULL, 0.f); if (overshield) d3d8_gl_set_height_fade(0.0f, 0.0f, 0.0f, 0.0f); } diff --git a/source/rasterizer/xbox/rasterizer_xbox_screen_effect.c b/source/rasterizer/xbox/rasterizer_xbox_screen_effect.c index 01abf62365..4bd5e4dbc8 100644 --- a/source/rasterizer/xbox/rasterizer_xbox_screen_effect.c +++ b/source/rasterizer/xbox/rasterizer_xbox_screen_effect.c @@ -96,6 +96,7 @@ symbols in this file: #include "bitmaps/bitmap_group.h" #include "cseries/errors.h" #include "interface/hud_draw.h" +#include "custom_edition_hud_draw.h" /* port: port/linux/game/custom_edition_hud_draw.c */ #include "mcc_hud_draw.h" /* port: port/linux/game/mcc_hud_draw.c */ #include "bitmaps/bitmaps_inlines.h" #include "main/main.h" @@ -290,6 +291,8 @@ static void rasterizer_screen_effect_set_texture_transforms( convolution_scale = TEST_FLAG(convolution_bitmap->flags, _bitmap_linear_bit) ? default_scale : vector2d_reciprocal(&convolution_size); + /* port: only the CE HUD mask's scoped draw changes its texture transform. */ + custom_edition_hud_mask_transform(convolution_bitmap, &convolution_size, &convolution_scale); /* port: MCC HUD masks retain texels but honor their bitmap size flags. */ mcc_hud_mask_transform(convolution_bitmap, &convolution_size, &convolution_scale); diff --git a/source/rasterizer/xbox/rasterizer_xbox_shadows.c b/source/rasterizer/xbox/rasterizer_xbox_shadows.c index 678b8f4b5e..17f8bd2a8c 100644 --- a/source/rasterizer/xbox/rasterizer_xbox_shadows.c +++ b/source/rasterizer/xbox/rasterizer_xbox_shadows.c @@ -212,7 +212,8 @@ boolean _rasterizer_environment_shadow_begin( real object_bounding_radius, real *shadow_volume_bounding_radius) { - boolean success = TRUE; + /* port: a skipped pass has no initialized shadow volume for the caller. */ + boolean success = FALSE; real inverse_radius; real vsh_constants__screenproj[20]; @@ -322,6 +323,7 @@ boolean _rasterizer_environment_shadow_begin( shadow_setup = FALSE; shadow_used = FALSE; shadow_restored = FALSE; + success = TRUE; /* port: report success only after shadow setup. */ if (rasterizer_debug_options.statistics_mode == _rasterizer_statistics_mode_enabled) diff --git a/source/rasterizer/xbox/rasterizer_xbox_transparent_geometry.c b/source/rasterizer/xbox/rasterizer_xbox_transparent_geometry.c index f978346751..665cb21e77 100644 --- a/source/rasterizer/xbox/rasterizer_xbox_transparent_geometry.c +++ b/source/rasterizer/xbox/rasterizer_xbox_transparent_geometry.c @@ -170,6 +170,7 @@ symbols in this file: #include "rasterizer/xbox/rasterizer_xbox_plasma_energy.h" #include "rasterizer/xbox/rasterizer_xbox_water.h" #include "rasterizer/xbox/shader_transparent_chicago_preprocessor.h" +#include "needler_lighting.h" /* port: port/linux/game/needler_lighting.c */ /* ---------- constants */ @@ -946,6 +947,8 @@ void rasterizer_transparent_geometry_group_draw__internal( struct transparent_geometry_group const *group, boolean has_lightmap) { + /* port: compile optional loading-time material variants without geometry. */ + if (material_prepare_draw()) return; match_assert( "c:\\halo\\SOURCE\\rasterizer\\xbox\\rasterizer_xbox_transparent_geometry.c", 109, @@ -1072,6 +1075,8 @@ void rasterizer_transparent_geometry_group_draw( { boolean success = TRUE; boolean draw_active_camouflage_groups2 = FALSE; + /* port: loading preparation excludes layers that need real geometry. */ + if (material_prepare_skip_shader(group ? group->shader : NULL)) return; match_assert( "c:\\halo\\SOURCE\\rasterizer\\xbox\\rasterizer_xbox_transparent_geometry.c", @@ -2399,6 +2404,9 @@ void rasterizer_transparent_geometry_group_draw( pixel_shader.constant_0[stage_index] = real_argb_color_to_pixel32(&constant_color0); } + /* port: brighten the optional Needler core before fog. */ + needler_lighting_transparent(group->shader, &pixel_shader, + shader_transparent_generic->generic.stages.count); break; } @@ -2688,6 +2696,9 @@ void rasterizer_transparent_geometry_group_draw( success = success && shader_transparent_chicago_create( group->shader, &pixel_shader); + /* port: optional world-model needle emission, before fog. */ + needler_lighting_transparent(group->shader, &pixel_shader, + shader_transparent_chicago->chicago.maps.count); if (rasterizer_debug_options.draw_environment_fog) { diff --git a/source/render/render_objects.c b/source/render/render_objects.c index 022195bbed..3c1c1c2c9c 100644 --- a/source/render/render_objects.c +++ b/source/render/render_objects.c @@ -112,6 +112,7 @@ symbols in this file: #include "saved games/game_state.h" #include "rasterizer/rasterizer_console_vars.h" #include "rasterizer/rasterizer_model_types.h" +#include "first_person_legs.h" /* port: port/linux/game/first_person_legs.c */ /* ---------- constants */ @@ -372,13 +373,9 @@ void render_objects( return; } -/* port: port/linux/game/first_person_legs.c */ -boolean first_person_legs_wanted(long object_index); -real_matrix4x3 const *first_person_legs_node_matrices(long object_index, real_matrix4x3 const *nodes); -/* port: port/linux/game/shield_color.c */ -real_rgb_color const *shield_color_colors(long unit_index, real_rgb_color const *colors); /* port: port/linux/game/overshield_effect.c */ -real const *overshield_effect_values(long unit_index, real const *values, boolean arms); +real const *overshield_effect_values(long unit_index, real const *values); +#include "shield_look.h" /* port: port/linux/game/shield_look.c */ void render_object_shadows( void) @@ -411,6 +408,7 @@ static boolean object_is_first_person_camera( ? NONE : player_get(local_player_get_player_index(render.local_player_index))->unit_index; + /* port: draw the complete local body in the shoulder view. */ return (unit_index == object_index && director_get_perspective(render.local_player_index) == _director_perspective_first_person) || @@ -478,14 +476,12 @@ static void render_object_list( while (object_index != NONE) { struct object_datum *object = object_get(object_index); - /* port: the player's own legs, seen looking down in first person - (port/linux/game/first_person_legs.c): its body drawn from the waist - down, nothing it carries */ - boolean legs = !data->shadow && !render.camera.mirrored && - object_is_first_person_camera(object_index) && first_person_legs_wanted(object_index); - real_matrix4x3 const *node_matrices = legs ? - first_person_legs_node_matrices(object_index, object_get_node_matrices(object_index)) : - object_get_node_matrices(object_index); + /* port: the player's own body in its first-person view, from the + waist down (display.first_person_legs); nothing it carries or wears */ + real_matrix4x3 const *legs_node_matrices = + !data->shadow && !render.camera.mirrored && object_is_first_person_camera(object_index) ? + first_person_legs_node_matrices(render.local_player_index, object_index) : + NULL; /* port: the function values the picture shows (object_function_values_for_render), kept in the rasterizer's memory for the frame: a modifier's group, a queued transparent part and a @@ -494,7 +490,7 @@ static void render_object_list( (overshield_effect.c), so they are not copied again */ real const *shown_functions = object->object.outgoing_function_values; - if (!object_is_first_person_camera(object_index) || render.camera.mirrored || (legs && node_matrices)) + if (!object_is_first_person_camera(object_index) || render.camera.mirrored || legs_node_matrices) { struct render_model_effect model_effect; @@ -554,18 +550,18 @@ static void render_object_list( if (shader_type_is_valid_for_modifier( model_effect.modifier_shader->base.type)) { - /* port: a local player's shield in the color - chosen for it (port/linux/game/shield_color.c) */ + /* port: selected shield profile; CLASSIC preserves the map shader. */ + model_effect.modifier_shader = shield_look_body(object_index, model_effect.modifier_shader); model_effect.modifier_animation.colors = - TEST_FLAG(_object_mask_unit, object->object.type) ? - shield_color_colors(object_index, object->object.outgoing_change_colors) : - object->object.outgoing_change_colors; + object->object.outgoing_change_colors; /* port: an overshield as it rises and lasts (port/linux/game/overshield_effect.c) */ model_effect.modifier_animation.values = TEST_FLAG(_object_mask_unit, object->object.type) ? - overshield_effect_values(object_index, shown_functions, FALSE) : + overshield_effect_values(object_index, shown_functions) : shown_functions; + /* port: register the selected recharge layer before submission. */ + shield_recharge_prepare(object_index, &model_effect, FALSE); } else { @@ -644,7 +640,7 @@ static void render_object_list( render_model( definition->object.model.index, level_of_detail_pixels, - node_matrices, + legs_node_matrices ? legs_node_matrices : object_get_node_matrices(object_index), /* port: (the legs' pose) */ object->object.region_permutations, object->object.outgoing_change_colors, shown_functions, @@ -654,7 +650,13 @@ static void render_object_list( &model_effect, object_index, object->object.forced_shader_permutation_index, - data->no_planar_fog ? FLAG(_render_model_no_planar_fog_bit) : 0); + (data->no_planar_fog ? FLAG(_render_model_no_planar_fog_bit) : 0) | + (legs_node_matrices ? FIRST_PERSON_LEGS_RENDER_FLAG : 0)); /* port: private lower-body geometry */ + + /* port: draw-only depleted shield arcs; no first-person leg duplicates. */ + if (!data->shadow && !legs_node_matrices) + shield_arcs_draw(object_index, definition->object.model.index, + object_get_node_matrices(object_index), &model_effect, FALSE); if (debug_objects) { @@ -666,7 +668,7 @@ static void render_object_list( render_model( definition->object.model.index, level_of_detail_pixels * 0.3f, - node_matrices, + object_get_node_matrices(object_index), object->object.region_permutations, object->object.outgoing_change_colors, object->object.outgoing_function_values, @@ -680,7 +682,7 @@ static void render_object_list( } } - if (!data->shadow && !legs && object->object.first_widget_index != NONE) + if (!data->shadow && !legs_node_matrices && object->object.first_widget_index != NONE) /* port: (not with the legs) */ { struct render_animation animation; real widget_functions[NUMBER_OF_OUTGOING_OBJECT_FUNCTIONS]; @@ -693,7 +695,7 @@ static void render_object_list( widgets_render(object_index, data->lighting, &animation); } - if (object->object.first_child_object_index != NONE && !legs) + if (object->object.first_child_object_index != NONE && !legs_node_matrices) /* port: (nor these) */ { render_object_list( data, diff --git a/source/saved games/game_state.c b/source/saved games/game_state.c index 8142f74554..3e79700df8 100644 --- a/source/saved games/game_state.c +++ b/source/saved games/game_state.c @@ -95,6 +95,7 @@ symbols in this file: /* ---------- headers */ #include "cseries.h" +#include "dualsense_game.h" /* port: port/linux/game/dualsense_game.c */ #include "cseries_windows.h" #include "cseries/errors.h" #include "real_math.h" @@ -108,6 +109,10 @@ symbols in this file: #include "scenario.h" #include "main.h" #include "objects.h" +#include "objects/widgets/lightning.h" /* port: reset render seeds after a load */ +#include "objects/widgets/flags.h" /* port: reset cloth timing after a load */ +#include "effects/contrails.h" /* port: reset point timing after a load */ +#include "effects/player_effects.h" /* port: reset camera shake after a load */ #include "objects/object_types.h" /* port: object_type_definitions (the saved game's layout checksum) */ #include "game_sound.h" #include "sound_manager.h" @@ -125,9 +130,10 @@ symbols in this file: #include "lruv_cache.h" #include "memory_pool.h" #include "cluster_partitions.h" -#include "mcc_cache.h" /* port: port/linux/game/mcc_cache.h */ -#include "mcc_checkpoint.h" /* port: port/linux/game/mcc_checkpoint.h */ +#include "mcc_cache.h" +#include "mcc_checkpoint.h" #include "hs_console_state.h" /* port: port/linux/game/hs_console_state.inl */ +#include "third_person.h" /* port: port/linux/game/third_person.c */ /* port: object_bounds_cache.c's */ void object_bounds_cache_invalidate(void); @@ -199,6 +205,7 @@ static game_state_before_save_proc before_save_procs[] = static game_state_before_load_proc before_load_procs[] = { + dualsense_game_reset, /* port: cancel feedback before restoring object identities */ game_sound_clear, /* port: where the cluster lists' references are, which the game state being loaded does not hold */ @@ -212,12 +219,20 @@ static game_state_before_load_proc before_load_procs[] = static game_state_after_load_proc after_load_procs[] = { + /* port: restored lightning slots and times must not reuse discarded seeds. */ + lightnings_reset_render_state, + /* port: these render caches also live outside the saved game buffer. */ + flags_reset_render_state, + contrails_reset_render_state, + player_effect_reset_render_state, scenario_reload_structure_bsp_if_necessary, /* port: the session roster is not part of a gameplay checkpoint. */ network_coop_restore_players, sound_stop_all, game_sound_restore, observer_initialize_for_new_map, + /* port: camera smoothing and free look are not stored in checkpoints. */ + third_person_reset, update_queues_reset_and_fill_with_lies, rasterizer_decals_update_function_pointers, recorded_animations_clear_debug_storage, diff --git a/tools/android_build.py b/tools/android_build.py index 5652b178f1..f4b89f6c5e 100644 --- a/tools/android_build.py +++ b/tools/android_build.py @@ -67,6 +67,17 @@ SDL_ANDROID_MOUSE_LISTENER = "android-project/app/src/main/java/org/libsdl/app/SDLControllerManager.java" ANDROID_API = 28 +# Android keeps stock lighting until the optional renderer is validated on +# devices. Its existing engine hooks link to dynamic_lighting_disabled.c; +# none of the added light pools, traces, textures or shader emitters are built. +DYNAMIC_LIGHTING_GAME_SOURCES = { + "plasma_lighting.c", "plasma_falloff.c", "plasma_occlusion.c", "plasma_collision.c", "plasma_collision_scene.c", "plasma_collision_models.c", + "rocket_lighting.c", "muzzle_lighting.c", "covenant_lighting.c", + "covenant_emitter_lighting.c", "ammo_counter_lighting.c", "ammo_counter_falloff.c", + "needler_lighting.c", "authored_emitter_lighting.c", "ambient_emitter_lighting.c", "shield_glow.c", "lighting_config.c", +} +DYNAMIC_LIGHTING_PLATFORM_SOURCES = {"plasma_model_shader.c", "plasma_occlusion_gl.c"} + # The guest ABI: AArch64 code with 32-bit pointers (clang's only such target # is Apple's arm64_32, whose Mach-O output is converted afterwards). The # Darwin environment is hidden from the sources; the C library is musl. @@ -468,7 +479,14 @@ def guest_object(source: Path, cflags: str, prefix: str = "") -> Path: cflags += f" -include {PORT_DIR}/include/halo_android_variadic_prototypes.h" objects.append(guest_object(source, cflags)) for source in sorted(Path(config["game_sources"]).glob("*.c")): - objects.append(guest_object(source, game_cflags)) + if source.name in DYNAMIC_LIGHTING_GAME_SOURCES: + continue + cflags = game_cflags + # The main menu labels the executable with its release number. + if source.as_posix() == "port/linux/game/menu_functions.c": + cflags += " " + updater_defines(getattr(sln, "port_release", False)) + objects.append(guest_object(source, cflags)) + objects.append(guest_object(PORT_DIR / "guest/dynamic_lighting_disabled.c", game_cflags)) objects.append(guest_object(STB_VORBIS_SOURCE, game_cflags)) # the platform layer shared with Linux, and the guest runtime @@ -480,9 +498,10 @@ def guest_object(source: Path, cflags: str, prefix: str = "") -> Path: f"-I{ZLIB_DIR}", "-Isource -Isource/cseries", f"-I{SDL_DIR}/include", f"-I{gl_include}", *libc_includes, f"-idirafter {XDK_INCLUDE}", ]) - guest_host_only = {"memory_watch.c"} # replaced by guest_memory_watch.c + # memory_watch.c is replaced by guest_memory_watch.c. + guest_excluded = {"memory_watch.c"} | DYNAMIC_LIGHTING_PLATFORM_SOURCES for source in sorted((LINUX_DIR / "src").glob("*.c")): - if source.name.startswith("posix_") or source.name in guest_host_only: + if source.name.startswith("posix_") or source.name in guest_excluded: continue objects.append(guest_object(source, platform_cflags)) # the high-res HUD's textures (port/assets/hud; port/linux/src/hud_hires.c) @@ -663,7 +682,7 @@ def guest_object(source: Path, cflags: str, prefix: str = "") -> Path: description="ANDROID GRADLE $out", pool="console", ) - n.build(outputs=apk, rule="android_gradle", inputs=[libmain, staged_sdl, staged_image, staged_brokers], + n.build(outputs=apk, rule="android_gradle", inputs=[libmain, staged_sdl, staged_image, staged_brokers, staged_bcdec_license], implicit=[sdl_android_mouse_listener]) n.build(outputs="android_apk", rule="phony", inputs=apk) n.newline() diff --git a/tools/android_signing.py b/tools/android_signing.py new file mode 100644 index 0000000000..eeb2b69a22 --- /dev/null +++ b/tools/android_signing.py @@ -0,0 +1,43 @@ +"""Stage the CI signing key; published main builds must never use debug keys.""" + +import base64 +import binascii +import os +import sys +from pathlib import Path + + +def main(): + encoded = os.environ.get("KEYSTORE", "").strip() + password = os.environ.get("HALO_ANDROID_KEYSTORE_PASSWORD", "") + required = os.environ.get("GITHUB_REF") == "refs/heads/main" + if not encoded or not password: + if required or encoded or password: + print("::error::Android signing requires both ANDROID_KEYSTORE_BASE64 " + "and ANDROID_KEYSTORE_PASSWORD; refusing a debug-signed release.") + return 1 + print("::warning::No Android signing secrets: this branch uses a debug key " + "and cannot update installed releases.") + return 0 + + try: + key = base64.b64decode("".join(encoded.split()), validate=True) + if not key: + raise ValueError("empty keystore") + except (binascii.Error, ValueError): + print("::error::ANDROID_KEYSTORE_BASE64 is not a nonempty base64 keystore.") + return 1 + + path = Path(os.environ["RUNNER_TEMP"]) / "halo.keystore" + # A fresh runner owns this file. Refuse to overwrite an existing key. + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(fd, "wb") as output: + output.write(key) + with open(os.environ["GITHUB_ENV"], "a", encoding="utf-8") as output: + output.write(f"HALO_ANDROID_KEYSTORE={path}\n") + # Gradle validates the keystore, password and halo alias when signing. + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/camera_policy_sessions.py b/tools/camera_policy_sessions.py new file mode 100644 index 0000000000..9536864a4c --- /dev/null +++ b/tools/camera_policy_sessions.py @@ -0,0 +1,119 @@ +"""Run two headless Windows instances against private, locally supplied maps. + +Checks authoritative policy on both peers, including a late join and co-op. +Uses isolated data/settings/save directories and loopback only. No game assets +are committed. Only processes started by this script are terminated. +""" +import argparse +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import time + + +def run_case(binary, maps, output, name, policy, preferences, coop=False, late=False, combat=False, latency=0, saves=None): + jobs = [] + results = [] + expected_policy = {"player_choice": 0, "forced_on": 1, "forced_off": 2}[policy] + try: + for index, role in enumerate(("host", "client")): + folder = output / name / role + (folder / "maps").mkdir(parents=True) + if saves: + shutil.copytree(saves, folder / "saves") + for filename in ("halo.exe", "SDL3.dll"): + shutil.copy2(binary.parent / filename, folder / filename) + for filename in ("ui.map", "carousel.map", "bloodgulch.map", *(["a30.map"] if coop else [])): + shutil.copy2(maps / filename, folder / "maps" / filename) + (folder / "config.toml").write_text(f"[display]\nthird_person = {'true' if preferences[index] else 'false'}\nfov = {140 if index else 70}\n") + env = {k: v for k, v in os.environ.items() if not k.startswith("HALO_")} + env.update(SDL_VIDEO_DRIVER="dummy", SDL_AUDIO_DRIVER="dummy", HALO_NULL_RENDERER="1", + HALO_HIDDEN_WINDOW="1", HALO_NO_AUDIO="1", HALO_NET_ONLINE="0", + HALO_NET_PUBLIC_LOBBY="0", HALO_NET_ALLOW_UPNP="0", HALO_MAX_FPS="30", + HALO_NETWORK_TEST_PUBLIC="0", HALO_NET_JOIN_FROM_CLIPBOARD="0", + HALO_NETWORK_TEST=("host:levels\\a30\\a30:coop" if coop else "host:levels\\test\\bloodgulch\\bloodgulch:slayer") if index == 0 else "join", + HALO_NETWORK_TEST_START="10", HALO_NET_ADDRESS=f"127.0.0.{236+index}", + HALO_NET_BROADCAST=f"127.0.0.{237-index}", HALO_DATA_ROOT=str(folder), + HALO_SAVE_ROOT=str(folder / "saves"), HALO_UPDATE_ANSWER="never", + # An opposing client's host preference must have no authority. + HALO_SESSION_COMPATIBILITY="gulchce_third_person", + HALO_CAMERA_POLICY=policy if index == 0 else ("forced_off" if policy != "forced_off" else "forced_on")) + if index and late: + time.sleep(20) + if combat: + env.update(HALO_TEST_INPUT=f"bot:{index}", HALO_NETWORK_LATENCY=str(latency), + HALO_NETWORK_LOSS="5" if latency else "0") + process = subprocess.Popen([str(folder / "halo.exe")], cwd=folder, env=env, + creationflags=subprocess.CREATE_NO_WINDOW) + jobs.append((role, folder, process)) + deadline = time.monotonic() + 45 + while time.monotonic() < deadline: + ready = [] + for role, folder, process in jobs: + log = (folder / "halo.log").read_text(errors="replace") if (folder / "halo.log").exists() else "" + records = [line for line in log.splitlines() if "camera-policy" in line and "player 1:" in line] + ready.append(len(records) >= (20 if combat else 5)) + if all(ready) or any(p.poll() is not None for _, _, p in jobs): + break + time.sleep(.5) + finally: + for index, (role, folder, process) in enumerate(jobs): + early_exit = process.poll() + if early_exit is None: + process.terminate() + process.wait(timeout=10) + log = (folder / "halo.log").read_text(errors="replace") + records = [line for line in log.splitlines() if "camera-policy" in line and "player 1:" in line] + values = [tuple(map(int, match)) for line in records + for match in re.findall(r"camera-policy (\d+) preference (\d+) effective (\d+) active (\d+)", line)] + expected = (expected_policy, preferences[index], 1 if expected_policy == 1 else 0 if expected_policy == 2 else preferences[index]) + saved = (folder / "config.toml").read_text() + preference_preserved = f"third_person = {'true' if preferences[index] else 'false'}" in saved + camera_observed = (not expected[2] and all(v[3] == 0 for v in values)) or (expected[2] and (coop or any(v[3] == 1 for v in values))) + passed = early_exit is None and len(values) >= 5 and all(v[:3] == expected for v in values) and preference_preserved and camera_observed + muzzle_players = sorted(set(int(p) for p in re.findall(r"network muzzle: player (\d+)", log))) + if combat and not coop: + # Player indices are assigned by join order, not machine order. + machines = {int(p): int(m) for line in records for p, m in + re.findall(r"player (\d+):.*?\bm(\d+)(?= player | \|)", line)} + expected_shooters = sorted(p for p, m in machines.items() + if expected_policy == 1 or (expected_policy == 0 and preferences[m])) + passed = passed and muzzle_players == expected_shooters + result = dict(case=name, role=role, passed=passed, samples=len(values), expected=expected, + observed=sorted(set(values)), preference_preserved=preference_preserved, + early_exit=early_exit) + result.update(muzzle_players=muzzle_players, combat=combat, latency=latency) + results.append(result) + print(json.dumps(result), flush=True) + return results + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--binary", type=Path, required=True) + parser.add_argument("--maps", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--saves", type=Path, help="Copy a preselected profile into each isolated save folder") + parser.add_argument("--combat", action="store_true", help="Fire bot weapons and check muzzle decisions on both peers") + args = parser.parse_args() + results = [] + for name, policy, preferences, coop, late in ( + ("choice", "player_choice", (0, 1), False, False), + ("on", "forced_on", (0, 0), False, False), + ("off", "forced_off", (1, 1), False, False), + ("late", "forced_on", (0, 0), False, True), + ("coop", "forced_on", (0, 0), True, False), + ): + print("Starting " + name, flush=True) + results += run_case(args.binary.resolve(), args.maps.resolve(), args.output.resolve(), name, policy, preferences, coop, late, args.combat, saves=args.saves) + if args.combat: + results += run_case(args.binary.resolve(), args.maps.resolve(), args.output.resolve(), "latency", "forced_on", (0, 0), combat=True, latency=100, saves=args.saves) + (args.output / "results.json").write_text(json.dumps(results, indent=2)) + return 0 if len(results) == (12 if args.combat else 10) and all(row["passed"] for row in results) else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/ce_menus.py b/tools/ce_menus.py index a9a2dcaae6..b4fe7ab3ea 100644 --- a/tools/ce_menus.py +++ b/tools/ce_menus.py @@ -50,6 +50,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent)) from hud_assets import bleed, render_svg # noqa: E402 import port_settings # noqa: E402 +import changelog_menu # noqa: E402 ROOT = Path(__file__).resolve().parent.parent MENUS = ROOT / "port/assets/menus" @@ -612,6 +613,57 @@ def pause_art(art): return lines +def regenerate_pause_art(): + """Regenerate port-owned pause art without requiring the PC tag archive.""" + import re + art = Art.__new__(Art) + art.pngs = [] + lines = pause_art(art) + path = CE / "bitmaps.xml" + text = path.read_text() + pattern = r'\t.*?\n' + matches = list(re.finditer(pattern, text, flags=re.S)) + position = matches[0].start() + text = re.sub(pattern, "", text, flags=re.S) + text = text[:position] + "\n".join(lines) + "\n" + text[position:] + path.write_text(text) + manifest = MENUS / "menus.json" + data = json.loads(manifest.read_text()) + files = set(data["files"]) | set(art.pngs) + data["files"] = sorted(name for name in files if name.endswith(".xml")) + sorted( + name for name in files if not name.endswith(".xml")) + manifest.write_text(json.dumps(data, indent=1) + "\n") + + +def regenerate_child_offsets(): + """Apply the same child positions to existing XML without the PC tags.""" + import re + for path in CE.glob("*.xml"): + original = path.read_text() + parent = None + lines = [] + for line in original.splitlines(keepends=True): + widget = re.match(r'\t", attribute + "/>") + lines.append(line) + updated = "".join(lines) + if updated != original: + path.write_text(updated) + + def regenerate_settings(): """Write port-owned settings and register any new screens for embedding.""" screens = {**port_settings.settings_files(), **port_settings.multiplayer_files()} @@ -629,17 +681,30 @@ def regenerate_settings(): def main() -> None: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--pause-art-only", action="store_true", help="regenerate only the port-owned pause panels") + parser.add_argument("--child-offsets-only", action="store_true", help="apply child positions to existing menu XML") + parser.add_argument("--changelog-only", action="store_true", help="regenerate only the sample changelog menus") parser.add_argument("--settings-only", action="store_true", help="regenerate port-owned settings screens and their manifest") - parser.add_argument("--tags", type=Path, required="--settings-only" not in sys.argv) - parser.add_argument("--definitions", type=Path, required="--settings-only" not in sys.argv) - parser.add_argument("--redraws", type=Path, required="--settings-only" not in sys.argv) - parser.add_argument("--placeholder", type=Path, required="--settings-only" not in sys.argv, help="the picture for frames with no redraw") + partial_only = any(option in sys.argv for option in ("--pause-art-only", "--child-offsets-only", "--changelog-only", "--settings-only")) + parser.add_argument("--tags", type=Path, required=not partial_only) + parser.add_argument("--definitions", type=Path, required=not partial_only) + parser.add_argument("--redraws", type=Path, required=not partial_only) + parser.add_argument("--placeholder", type=Path, required=not partial_only, help="the picture for frames with no redraw") parser.add_argument("--pictures", type=Path, help="the PC version's pictures, as PNGs by tag path: only where each is, to place its placeholder") arguments = parser.parse_args() if arguments.settings_only: regenerate_settings() return + if arguments.changelog_only: + changelog_menu.regenerate() + return + if arguments.child_offsets_only: + regenerate_child_offsets() + return + if arguments.pause_art_only: + regenerate_pause_art() + return tags = Tags(arguments.tags, arguments.definitions) # (the names of the Xbox's own as the game has them, which the tags' own # names give a little differently: "create&edit", "NULL") @@ -691,6 +756,9 @@ def main() -> None: (CE / f"{folder.replace('/', '.')}.xml").write_text("\n".join(lines) + "\n") for name, lines in [*port_settings.settings_files().items(), *port_settings.multiplayer_files().items()]: (CE / name).write_text("\n".join(lines)) + main_menu = CE / "main_menu.xml" + main_menu.write_text(changelog_menu.insert_item(main_menu.read_text())) + changelog_menu.generate(art) # their strings (CE / "strings.xml").write_text(strings_xml({ tag: [text_value(item["string"]) for item in tags.load(tag, "unicode_string_list")["strings"]] @@ -797,7 +865,9 @@ def main() -> None: report += ["", "Wired: " + ", ".join(f"`{name}`" for name in sorted(WIRED)) + ".", ""] (MENUS / "UNWIRED.md").write_text("\n".join(report)) files = sorted(path.relative_to(MENUS).as_posix() for path in MENUS.rglob("*.xml")) - files += sorted(art.pngs) + # The optional frontend's independent generator owns these redraws. + files += sorted(set(art.pngs) | {path.relative_to(MENUS).as_posix() + for path in (MENUS / "modern").glob("*.png")}) (MENUS / "menus.json").write_text(json.dumps({ "comment": "The menus' files the game embeds (tools/ce_menus.py, tools/embed_assets.py).", "files": files, diff --git a/tools/changelog_menu.py b/tools/changelog_menu.py new file mode 100644 index 0000000000..a0f59d1a8e --- /dev/null +++ b/tools/changelog_menu.py @@ -0,0 +1,343 @@ +#!/usr/bin/env python3 +"""Generate the port's player notes screens without the PC tag archive. + + python tools/changelog_menu.py + +Use --text-only to update notes while preserving the committed artwork. +Build navigation uses existing open/back events; scrolling belongs to each +screen instance and resets when another build is opened. +""" + +import argparse +from datetime import date +import json +from pathlib import Path +import re +import xml.etree.ElementTree as ET + +import port_settings + +ROOT = Path(__file__).resolve().parent.parent +MENUS = ROOT / "port/assets/menus" +FILE = "main_menu.changelog.port.xml" +ITEM = "main_menu/main_menu_item_changelog" +CORNER = "main_menu/changelog_corner" +BASE = "main_menu/changelog" +# Center beneath the original version's visible text (x454..544), rather +# than its wider text widget, whose center is farther to the right. +CHILD = f'' +CORNER_WIDTH = 104 +CORNER_HEIGHT = 21 +BUILD_LABEL = "main_menu/gulch_build_number" +BITMAP = "main_menu/menu_changelog" +TITLE = f"{BASE}/header_changelog" +NOTES = ROOT / "port/assets/changelog/notes.json" +NOTE_LINE_HEIGHT = 22 +VISIBLE_LINES = 8 +NOTE_COLUMNS = 44 + +# The handmade redraws' letter side bearings, fitted to their existing +# menu/header pairs in the same way as port_settings.MENU_ITEM_SPACES. +SPACING = {"CH": 3.19, "HA": 1.22, "AN": 1.33, "NG": 3.0, + "GE": 2.35, "EL": 3.56, "LO": -0.11, "OG": 2.27} + +def validate_notes(data): + """Reject data that could introduce menu escapes or unsupported text.""" + if not isinstance(data, dict) or set(data) != {"schema_version", "head", "entries"}: + raise ValueError("notes must contain schema_version, head and entries") + if type(data["schema_version"]) is not int or data["schema_version"] != 2: + raise ValueError("unsupported notes schema_version") + sha = re.compile(r"[0-9a-f]{40}") + if not isinstance(data["head"], str) or not sha.fullmatch(data["head"]): + raise ValueError("notes head must be a full lowercase commit SHA") + if not isinstance(data["entries"], list): + raise ValueError("notes entries must be a list") + total_notes, builds = 0, set() + for index, entry in enumerate(data["entries"]): + context = f"notes entry {index + 1}" + if (not isinstance(entry, dict) or not {"build", "date", "commit", "notes"} <= set(entry) + or set(entry) - {"build", "date", "commit", "notes", "categories"}): + raise ValueError(f"{context} must contain build, date, commit and notes") + if entry["build"] is not None and (type(entry["build"]) is not int or not 1 <= entry["build"] <= 2147483647): + raise ValueError(f"{context} build must be a positive integer or null") + if entry["build"] in builds: + raise ValueError(f"{context} duplicates a build") + builds.add(entry["build"]) + if not isinstance(entry["commit"], str) or not sha.fullmatch(entry["commit"]): + raise ValueError(f"{context} commit must be a full lowercase SHA") + try: + if not isinstance(entry["date"], str) or date.fromisoformat(entry["date"]).isoformat() != entry["date"]: + raise ValueError() + except (ValueError, TypeError): + raise ValueError(f"{context} date must be YYYY-MM-DD") from None + if not isinstance(entry["notes"], list): + raise ValueError(f"{context} notes must be a list") + if "categories" in entry: + categories = entry["categories"] + if (not isinstance(categories, list) or len(categories) != len(entry["notes"]) + or any(not isinstance(label, str) or label and + (len(label) > 24 or not re.fullmatch(r"[A-Z][A-Z0-9]*(?: [A-Z0-9]+)*", label)) + for label in categories)): + raise ValueError(f"{context} categories must match notes and contain uppercase labels up to 24 characters") + total_notes += len(entry["notes"]) + if total_notes > 4096: + raise ValueError("notes must contain at most 4096 player notes") + for note in entry["notes"]: + if (not isinstance(note, str) or not 1 <= len(note) <= 100 or note != note.strip() + or any(not 32 <= ord(char) <= 126 or char in "\\|" for char in note)): + raise ValueError(f"{context} notes must be printable ASCII, 1-100 characters, without backslash or pipe") + return data + + +def load_notes(path=NOTES): + return validate_notes(json.loads(Path(path).read_text(encoding="utf-8"))) + + +def note_lines(note): + # At small_ui's 10px capital height, this budget fits the 420px column, + # including digit runs. Capitals and wide lowercase glyphs occupy two + # columns. Split long words as well as wrapping at word boundaries. + def columns(text): + return sum(2 if char.isupper() or char in "mw@%&#" else 1 for char in text) + + lines, line, width = [], "- ", 2 + for word in note.split(" "): + separator = "" if line in ("- ", " ") else " " + if width + len(separator) + columns(word) > NOTE_COLUMNS and line not in ("- ", " "): + lines.append(line) + line, separator = " ", "" + width = 2 + line += separator + width += len(separator) + for char in word: + char_width = columns(char) + if width + char_width > NOTE_COLUMNS: + lines.append(line) + line = " " + width = 2 + line += char + width += char_width + lines.append(line) + return lines + + +def reading_rows(entry): + groups = {} + categories = entry.get("categories", [""] * len(entry["notes"])) if entry else [] + for category, note in zip(categories, entry["notes"] if entry else []): + groups.setdefault(category or "GENERAL", []).append(note) + rows = [] + for category, notes in groups.items(): + if rows: + rows.append(("", "")) + rows.append(("", category)) + for note in notes: + rows.extend((line, "") for line in note_lines(note)) + return rows or [("No player-facing changes recorded.", "")] + + +def reading_lines(entry): + return [body for body, heading in reading_rows(entry)] + + +def _text(name, text, x, y, width, height=24, font="small", color="#FFCCCCCC", align="left"): + return port_settings._widget(name, [ + ("type", "text"), ("left", x), ("top", y), ("width", width), ("height", height), + ("text", text), ("font", f"ui\\{font}_ui"), ("color", color), ("align", align), + ], []) + + +def corner_frames(redraws): + """Uniformly fit the existing design beneath the visible version text.""" + frames = [] + for index, (caption, _, _) in enumerate(port_settings.menu_item_frames("CHANGELOG", redraws, SPACING)): + border = (redraws / f"shell/bitmaps/text_button_background__{index}.svg").read_text(encoding="utf-8") + inner = lambda svg: svg[svg.index(">") + 1:svg.rindex("")] + svg = '\n'.join([ + '', + ' ', inner(border), ' ', + ' ', inner(caption), ' ', '', '']) + frames.append((svg, CORNER_WIDTH, CORNER_HEIGHT)) + return frames + + +def widget_lines(data=None): + """One scrolling screen per build, with one invoking-menu history entry. + + ui_widget_load_by_name_or_tag (source/interface/ui_widget.c) checks + the invoking root's no_history flag before saving it. Each screen must + carry the flag, while the main menu retains its existing history flags. + """ + data = load_notes() if data is None else validate_notes(data) + entries = data["entries"] or [None] + lines = port_settings._widget(ITEM, [ + ("type", "text"), ("width", CORNER_WIDTH), ("height", CORNER_HEIGHT), ("bitmap", BITMAP), + ], [f'', + '']) + lines += port_settings._widget(CORNER, [ + ("type", "column_list"), ("width", CORNER_WIDTH), ("height", CORNER_HEIGHT), + ("flags", "pass_unhandled_to_focused_child"), + ], [f'']) + lines += port_settings._header(TITLE, TITLE) + lines += port_settings._widget(BUILD_LABEL, [ + ("type", "text"), ("controller", 1), ("width", 150), ("height", 20), + ("font", "ui\\small_ui"), ("color", "#FFFF8000"), ("align", "center"), + ], ['']) + for index, entry in enumerate(entries, 1): + page = f"{BASE}/build_{index}" + contents = reading_rows(entry) + if len(contents) + VISIBLE_LINES > 32767: + raise ValueError(f"notes entry {index} exceeds the menu's 32767-line string index limit") + lines += port_settings._strings(f"{page}/lines", [body for body, heading in contents] + [""] * VISIBLE_LINES) + lines += port_settings._strings(f"{page}/headings", [heading for body, heading in contents] + [""] * VISIBLE_LINES) + children = [f'', + f'', + f'', + f'', + f''] + children += [f'' for row in range(VISIBLE_LINES)] + children += [f'' for row in range(VISIBLE_LINES)] + children += [f'', + f'', + f'', + f''] + events = ['', + '', + '', + ''] + if index < len(entries): + events.append(f'') + if index > 1: + events.append(f'') + lines += port_settings._widget(page, [ + ("width", 640), ("height", 480), ("flags", "pass_unhandled_to_focused_child pause_game no_history"), + ("bitmap", "bitmaps/gradient"), + ], events + [''] + children) + lines += _text(f"{page}/build_number", f"{index} / {len(entries)}", 430, 44, 170, + color="#FF2896FF", align="right") + lines += _text(f"{page}/label", "PLAYER NOTES", 55, 90, 530, color="#FFFFB020") + heading = (f"BUILD {entry['build']}" if entry["build"] is not None else "UNRELEASED") if entry else "NO PLAYER NOTES" + lines += _text(f"{page}/heading", heading, 55, 118, 530, 34, "large", "#FFFFFFFF") + lines += _text(f"{page}/date", entry["date"] if entry else "", 55, 158, 530) + for row in range(VISIBLE_LINES): + for name, table, color in (("row", "lines", "#FFCCCCCC"), ("heading_row", "headings", "#FF2896FF")): + lines += port_settings._widget(f"{page}/{name}_{row}", [ + ("type", "text"), ("left", 55), ("top", 188 + row * NOTE_LINE_HEIGHT), + ("width", 420), ("height", NOTE_LINE_HEIGHT), ("string_list", f"{page}/{table}"), + ("string_index", row), ("font", "ui\\small_ui"), ("color", color), + ], []) + lines += port_settings._widget(f"{page}/scroll_position", [ + ("type", "text"), ("left", 55), ("top", 382), ("width", 250), ("height", 24), + ("font", "ui\\small_ui"), ("color", "#FF999999"), + ], []) + lines += _text(f"{page}/instructions", "Scroll: Up/Down or mouse wheel", 300, 382, 310, + color="#FF999999", align="right") + for direction, label in (("up", "UP"), ("down", "DOWN")): + lines += port_settings._text_button(f"{page}/scroll_{direction}", label, + [f'']) + # Mouse targets must belong to a list (or a parent that tabs its + # children). Root-level text buttons cannot receive pointer focus. + lines += port_settings._widget(f"{page}/scroll_controls", [ + ("type", "column_list"), ("width", 128), ("height", 52), + ("flags", "pass_unhandled_to_focused_child"), + ], [f'', + f'']) + buttons = [] + for label, target, x in (("PREVIOUS", index + 1, 80), ("NEXT", index - 1, 250)): + if not 1 <= target <= len(entries): + continue + name = f"{page}/button_{label.lower()}" + buttons.append(f'') + lines += port_settings._text_button(name, label, [ + f'']) + name = f"{page}/button_back" + buttons.append(f'') + lines += port_settings._text_button(name, "BACK", ['']) + lines += port_settings._widget(f"{page}/buttons", [ + ("type", "column_list"), ("width", 640), ("height", 28), + ("flags", "pass_unhandled_to_focused_child"), + ], buttons) + return lines + + +def document(bitmaps, data=None): + return '\n'.join(['', + '', + '', *bitmaps, *widget_lines(data), '', '']) + + +def generate(art, data=None): + """Write the same feature file and art in focused and full generation.""" + bitmaps = [art.port_picture(BITMAP, corner_frames(art.redraws)), + art.title(TITLE, "CHANGELOG")] + (MENUS / "ce" / FILE).write_text(document(bitmaps, data), encoding="utf-8") + + +def regenerate_text(data=None): + """Keep bitmap XML verbatim; this path uses only the standard library.""" + path = MENUS / "ce" / FILE + text = path.read_text(encoding="utf-8") + root = ET.fromstring(text) + bitmaps = re.findall(r'\t]*>.*?', text, re.DOTALL) + if len(bitmaps) != 2 or {node.get("name") for node in root.findall("bitmap")} != {BITMAP, TITLE}: + raise ValueError("expected existing changelog item and title bitmap definitions") + path.write_text(document(bitmaps, data), encoding="utf-8") + main = MENUS / "ce/main_menu.xml" + if main.exists(): + main.write_text(insert_item(main.read_text(encoding="utf-8")), encoding="utf-8") + + +def insert_item(text): + """Add only the feature child; retain every legacy attribute/position.""" + for name in (ITEM, CORNER, BUILD_LABEL): + text, count = re.subn(r'\t\t\n', '', text) + if count > 1: + raise ValueError(f"expected at most one child for {name}") + for owned in ('', + '', + '', + ''): + text = text.replace('\t\t' + owned + '\n', '') + pattern = r'(\t\n' + '\t\t\n' + '\t\t\n', text) + if count != 1: + raise ValueError("expected one main menu root") + pattern = r'(\t\t' + + '\n\t\t' + CHILD, updated) + if count != 1: + raise ValueError("expected one main menu build-number child") + return updated + + +def regenerate(data=None): + # Art is shared with the full generator; no proprietary tags are read. + import ce_menus + art = ce_menus.Art.__new__(ce_menus.Art) + art.pngs = [] + art.redraws = MENUS / "svg" + generate(art, data) + main = MENUS / "ce/main_menu.xml" + main.write_text(insert_item(main.read_text(encoding="utf-8")), encoding="utf-8") + manifest = MENUS / "menus.json" + data = json.loads(manifest.read_text(encoding="utf-8")) + files = set(data["files"]) | set(art.pngs) | {f"ce/{FILE}"} + data["files"] = sorted(name for name in files if name.endswith(".xml")) + sorted( + name for name in files if not name.endswith(".xml")) + manifest.write_text(json.dumps(data, indent=1) + "\n", encoding="utf-8") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--notes", type=Path, default=NOTES, help="validated player notes JSON") + parser.add_argument("--text-only", action="store_true", help="preserve artwork and update only widget XML") + args = parser.parse_args() + try: + data = load_notes(args.notes) + (regenerate_text if args.text_only else regenerate)(data) + except (OSError, ValueError) as error: + parser.exit(1, f"changelog_menu: {error}\n") diff --git a/tools/changelog_release_base.py b/tools/changelog_release_base.py new file mode 100644 index 0000000000..d6d9a599b0 --- /dev/null +++ b/tools/changelog_release_base.py @@ -0,0 +1,86 @@ +"""Find the last published build in this commit's history for release highlights.""" + +import argparse +import json +from pathlib import Path +import re +import subprocess +import tempfile + + +def release_base(releases, head, current_tag, run=subprocess.run): + if not re.fullmatch(r"[0-9a-f]{40}", head): + raise ValueError("head must be a full commit SHA") + candidates = [release for release in releases + if re.fullmatch(r"build-[0-9]+", release["tagName"]) + and release["tagName"] != current_tag + and not release["isDraft"] and not release["isPrerelease"]] + for release in sorted(candidates, key=lambda item: item["publishedAt"], reverse=True): + ref = "refs/tags/" + release["tagName"] + "^{commit}" + resolved = run(["git", "rev-parse", "--verify", "--end-of-options", ref], + capture_output=True, text=True, check=True).stdout.strip() + ancestry = run(["git", "merge-base", "--is-ancestor", resolved, head], + capture_output=True, text=True) + if ancestry.returncode == 0: + return resolved, release["tagName"] + if ancestry.returncode != 1: + raise RuntimeError(ancestry.stderr) + return None + + +def download_archive(selected, destination, run=subprocess.run): + """Carry published build identities forward even after old tags expire.""" + destination = Path(destination) + if selected is None: + destination.unlink(missing_ok=True) + return False + commit, tag = selected + result = run(["gh", "release", "view", tag, "--json", "assets"], + capture_output=True, text=True, check=True) + assets = json.loads(result.stdout)["assets"] + archives = [asset for asset in assets if asset["name"] == "changelog.json"] + if not archives: + # Releases before this feature have no numbered history to preserve. + destination.unlink(missing_ok=True) + return False + if len(archives) != 1 or not 0 < archives[0]["size"] <= 2 * 1024 * 1024: + raise ValueError("published changelog archive has an invalid size or duplicate name") + destination.parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(prefix="changelog-", dir=destination.parent) as temporary: + run(["gh", "release", "download", tag, "--pattern", "changelog.json", "--dir", temporary], + capture_output=True, text=True, check=True) + downloaded = Path(temporary) / "changelog.json" + if not 0 < downloaded.stat().st_size <= 2 * 1024 * 1024: + raise ValueError("downloaded changelog archive exceeds its size limit") + data = json.loads(downloaded.read_text(encoding="utf-8")) + if (not isinstance(data, dict) or data.get("schema_version") != 2 + or data.get("head") != commit or not isinstance(data.get("entries"), list) + or not data["entries"] or not isinstance(data["entries"][0], dict) + or type(data["entries"][0].get("build")) is not int + or data["entries"][0]["build"] != int(tag.removeprefix("build-"))): + raise ValueError("published changelog does not match its release build and commit") + # The collector validates every remaining entry against Git ancestry. + downloaded.replace(destination) + return True + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--head", required=True) + parser.add_argument("--current-tag", required=True) + parser.add_argument("--output", required=True, help="GitHub Actions output file") + parser.add_argument("--archive-output", type=Path, required=True, + help="previous release's changelog JSON, if that asset exists") + args = parser.parse_args() + result = subprocess.run([ + "gh", "release", "list", "--limit", "100", "--json", + "tagName,isDraft,isPrerelease,publishedAt", + ], capture_output=True, text=True, check=True) + selected = release_base(json.loads(result.stdout), args.head, args.current_tag) + download_archive(selected, args.archive_output) + with open(args.output, "a", encoding="utf-8") as output: + output.write("base=" + (selected[0] if selected else "") + "\n") + + +if __name__ == "__main__": + main() diff --git a/tools/ci_build.py b/tools/ci_build.py index ed1cdaeda0..42f59d93ab 100644 --- a/tools/ci_build.py +++ b/tools/ci_build.py @@ -135,6 +135,12 @@ def main() -> int: for output in outputs: shutil.copy2(ROOT / output, dist) print(f"{output} -> {dist.relative_to(ROOT)}", flush=True) + if args.platform == "android": + diagnostics = dist / "diagnostics" + shutil.copytree(ROOT / "port/android/diagnostics", diagnostics, + ignore=shutil.ignore_patterns("__pycache__", "*.pyc")) + revision = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip() + (diagnostics / "build-revision.txt").write_text(revision + "\n", encoding="utf-8") if args.platform == "windows": # the symbols of halo.exe and SDL3.dll, apart (players do not need # them): the workflow uploads them to Sentry, which turns the crash @@ -150,6 +156,13 @@ def main() -> int: print(f"{pdb.relative_to(ROOT)} -> {symbols.relative_to(ROOT)}", flush=True) # OpenCE's own licence, the AGPL, which asks each copy to carry its text shutil.copy2(ROOT / "LICENSE", dist / "LICENSE.txt") + # DualSense effect packing and SDL's PS5 output format/palette. + for name in ("TriggerEffectGenerator", "SDL"): + shutil.copy2(ROOT / f"port/third_party/dualsense/{name}-LICENSE.txt", + dist / f"dualsense-{name}-LICENSE.txt") + # Enhanced bot tactics retain the Vita author's GPL 3.0 licence. + shutil.copy2(ROOT / "LICENSES/GPL-3.0-only.txt", dist / "bots-GPL-3.0.txt") + shutil.copy2(ROOT / "docs/reading/bots_and_android_features.md", dist / "bots-and-android-credits.md") if args.platform != "web": # internet play's DTLS with browsers, and the Linux self-updater's TLS # (port/third_party/mbedtls), whose Apache license asks the same diff --git a/tools/extract_shield_arcs.py b/tools/extract_shield_arcs.py new file mode 100644 index 0000000000..f5671cb3f2 --- /dev/null +++ b/tools/extract_shield_arcs.py @@ -0,0 +1,72 @@ +"""Extract Bigass v3 plasma-bolt sprites for local use; does not redistribute map assets.""" +import argparse +import hashlib +from pathlib import Path +import struct + + +def extract(path): + data = Path(path).read_bytes() + def read(offset, size): + if offset < 0 or size < 0 or offset > len(data) - size: + raise ValueError("map reference outside file") + return data[offset:offset + size] + def u32(offset): + return struct.unpack(" + +int config_boolean(char const *name); + +void lighting_compatibility_sample(void) +{ + static FILE *file; + static long previous = -30; + long tick = game_time_get(); + if (!game_in_progress() || (tick >= previous && tick - previous < 30)) return; + previous = tick; + if (!file) + { + file = fopen("lighting-policy.csv", "w"); + if (file) fprintf(file, "tick,connection,policy,shield_enabled,local_shield,local_plasma,local_needler\n"); + } + if (file) + { + fprintf(file, "%ld,%d,%d,%d,%d,%d,%d\n", tick, game_connection(), + network_shield_effects(), shield_glow_enabled(), config_boolean("display.shield_glow"), + config_boolean("display.plasma_lighting"), config_boolean("display.needler_lighting")); + fflush(file); + } +} diff --git a/tools/fixtures/lighting_diagnostics.inc b/tools/fixtures/lighting_diagnostics.inc new file mode 100644 index 0000000000..2bb7ccf35a --- /dev/null +++ b/tools/fixtures/lighting_diagnostics.inc @@ -0,0 +1,39 @@ +/* Test-only collision clocks. Categories overlap; do not add inclusive totals. */ +int lighting_trace_active; +static double collision_seconds[8]; +static unsigned long collision_calls[8]; +void lighting_resource_diagnostics(double seconds); +void lighting_texture_diagnostics(double seconds); + +void lighting_trace_time(int category, __int64 started) +{ + LARGE_INTEGER now, frequency; + if (!lighting_trace_active || !started || category < 0 || category >= 8) return; + QueryPerformanceCounter(&now); + QueryPerformanceFrequency(&frequency); + collision_seconds[category] += (double)(now.QuadPart - started) / (double)frequency.QuadPart; + collision_calls[category]++; +} + +void lighting_diagnostics_frame(double seconds) +{ + static FILE *file; + int i; + if (!file) + { + file = fopen("collision.csv", "w"); + if (file) fprintf(file, "seconds,category,ms,calls\n"); + } + if (file) + { + for (i = 0; i < 8; i++) + { + fprintf(file, "%.3f,%d,%.6f,%lu\n", seconds, i, collision_seconds[i]*1000, collision_calls[i]); + collision_seconds[i] = 0; + collision_calls[i] = 0; + } + fflush(file); + } + lighting_resource_diagnostics(seconds); + lighting_texture_diagnostics(seconds); +} diff --git a/tools/fixtures/lighting_gpu_profile.inc b/tools/fixtures/lighting_gpu_profile.inc new file mode 100644 index 0000000000..47af81246b --- /dev/null +++ b/tools/fixtures/lighting_gpu_profile.inc @@ -0,0 +1,63 @@ +/* Desktop test build only. Sample draws every 32nd frame; never wait for GPU + results. A full ring skips samples instead of stalling the rendering thread. + TIME_ELAPSED semantics: Khronos ARB_timer_query, independently implemented. */ +enum { LIGHTING_GPU_QUERIES = 4096 }; +static struct lighting_gpu_sample +{ + GLuint query; + unsigned long frame; + double seconds; + int kind; +} lighting_gpu_samples[LIGHTING_GPU_QUERIES]; +static unsigned long lighting_gpu_read, lighting_gpu_write, lighting_gpu_frame_number; +static int lighting_gpu_active; +static FILE *lighting_gpu_log; +double lighting_performance_seconds(void); + +static void lighting_gpu_begin(void) +{ + struct lighting_gpu_sample *sample; + if (lighting_gpu_frame_number % 32 || lighting_gpu_write - lighting_gpu_read == LIGHTING_GPU_QUERIES) + return; + sample = &lighting_gpu_samples[lighting_gpu_write % LIGHTING_GPU_QUERIES]; + if (!sample->query) glGenQueries(1, &sample->query); + sample->frame = lighting_gpu_frame_number; + sample->seconds = lighting_performance_seconds(); + sample->kind = lighting_profile_world ? lighting_profile_world : lighting_profile_model; + glBeginQuery(GL_TIME_ELAPSED, sample->query); + lighting_gpu_active = 1; +} + +static void lighting_gpu_end(void) +{ + if (!lighting_gpu_active) return; + glEndQuery(GL_TIME_ELAPSED); + lighting_gpu_active = 0; + lighting_gpu_write++; +} + +static void lighting_gpu_frame(unsigned long frame) +{ + if (!lighting_gpu_log) + { + lighting_gpu_log = fopen("gpu.csv", "w"); + if (lighting_gpu_log) + { + setvbuf(lighting_gpu_log, NULL, _IOFBF, 65536); + fprintf(lighting_gpu_log, "frame,seconds,kind,nanoseconds\n"); + } + } + while (lighting_gpu_read != lighting_gpu_write) + { + struct lighting_gpu_sample *sample = &lighting_gpu_samples[lighting_gpu_read % LIGHTING_GPU_QUERIES]; + GLuint ready, nanoseconds; + glGetQueryObjectuiv(sample->query, GL_QUERY_RESULT_AVAILABLE, &ready); + if (!ready) break; + glGetQueryObjectuiv(sample->query, GL_QUERY_RESULT, &nanoseconds); + if (lighting_gpu_log) + fprintf(lighting_gpu_log, "%lu,%.6f,%d,%u\n", sample->frame, sample->seconds, sample->kind, nanoseconds); + lighting_gpu_read++; + } + if (lighting_gpu_log) fflush(lighting_gpu_log); + lighting_gpu_frame_number = frame + 1; +} diff --git a/tools/fixtures/lighting_performance.c b/tools/fixtures/lighting_performance.c new file mode 100644 index 0000000000..910d0f23e5 --- /dev/null +++ b/tools/fixtures/lighting_performance.c @@ -0,0 +1,182 @@ +/* Windows benchmark instrumentation, installed only by the test builder. + Ordinary runs are passive. HALO_LIGHTING_BENCH_SHIELD explicitly adds one + stationary shield to an isolated test copy; host policy remains unchanged. */ +#include "cseries.h" +#include +#include "game/game.h" +#include "objects/objects.h" +#include "rasterizer/rasterizer.h" +#include "rasterizer/rasterizer_lights.h" +#include "plasma_lighting.h" +#include "camera/observer.h" +#include "tag_files/tag_files.h" +#include "physics/collisions.h" +#include +#include + +static FILE *timings; +static double origin, previous, flushed, next_capture; +static long selected, lights, occlusion_updates; +static double occlusion_started, occlusion_seconds; +static int screenshot_frames; +static FILE *profile; +enum { LIGHTING_PROFILE_PHASES = 12 }; +static double phase_start[LIGHTING_PROFILE_PHASES], phase_time[LIGHTING_PROFILE_PHASES]; +static long phase_calls[LIGHTING_PROFILE_PHASES]; + +/* Explicit isolated shield workload; ordinary performance runs stay passive. */ +static void stationary_shield_scene(double elapsed) +{ + static int created; + struct object_placement_data placement; + struct observer_result const *camera; + struct collision_result ground; + real_vector3d down = {0, 0, -5}; + real_point3d from; + long tag, object; + if (!getenv("HALO_LIGHTING_BENCH_SHIELD") || created || elapsed < 2.0) return; + created = TRUE; + tag = tag_loaded('scen', "scenery\\c_field_generator\\c_field_generator"); + if (tag == NONE) { fprintf(stderr, "BENCH shield tag missing\n"); return; } + camera = observer_get_camera(0); + object_placement_data_new(&placement, tag, NONE); + placement.position = camera->position; + placement.position.x += camera->forward.i * 2.5f; + placement.position.y += camera->forward.j * 2.5f; + from = placement.position; + from.z += 0.5f; + if (collision_test_vector(FLAG(_collision_test_structure_bit) | FLAG(_collision_test_front_facing_surfaces_bit), + &from, &down, NONE, &ground)) placement.position.z = ground.point.z + 0.03f; + placement.forward.i = -camera->forward.j; + placement.forward.j = camera->forward.i; + placement.forward.k = 0; + normalize3d(&placement.forward); + observer_up_from_forward(&placement.forward, &placement.up); + object = object_new(&placement); + fprintf(stderr, "BENCH shield created %ld\n", object); +} +static double clock_seconds(void) +{ + LARGE_INTEGER counter, frequency; + QueryPerformanceCounter(&counter); + QueryPerformanceFrequency(&frequency); + return (double)counter.QuadPart / (double)frequency.QuadPart; +} + +double lighting_performance_seconds(void) +{ + return origin ? clock_seconds() - origin : -1; +} + +/* Route inspection uses ordinary controller movement in a copied checkpoint. + It neither teleports the player nor changes the mission's actors/scripts. */ +int lighting_performance_input(XINPUT_GAMEPAD *pad) +{ + const char *advance = getenv("HALO_LIGHTING_BENCH_ADVANCE"); + double elapsed; + if (!advance) return FALSE; + elapsed = lighting_performance_seconds(); + if (elapsed < 2) return FALSE; + if (elapsed < 2 + atof(advance)) pad->sThumbLY = 32767; + else if (getenv("HALO_LIGHTING_BENCH_TURN") && elapsed < 2 + atof(advance) + atof(getenv("HALO_LIGHTING_BENCH_TURN"))) + pad->sThumbRX = 32767; + return TRUE; +} + +void lighting_profile_begin(int phase) +{ + phase_start[phase] = clock_seconds(); +} + +void lighting_profile_end(int phase) +{ + phase_time[phase] += clock_seconds() - phase_start[phase]; + phase_calls[phase]++; +} + +void lighting_performance_lights(void) +{ + long i; + selected = 0; + lights = rasterizer_lights.light_count; + for (i = 0; i < lights; i++) + selected += plasma_lighting_selected(i) != 0; +} + +void lighting_performance_occlusion(int updates) +{ + occlusion_updates = updates; +} + +void lighting_performance_occlusion_begin(void) +{ + occlusion_started = clock_seconds(); +} + +void lighting_performance_occlusion_end(void) +{ + occlusion_seconds += clock_seconds() - occlusion_started; +} + +int lighting_performance_capture(void) +{ + double elapsed; + if (!origin) return FALSE; + elapsed = clock_seconds() - origin; + if (elapsed < next_capture) return FALSE; + next_capture = elapsed + (getenv("HALO_LIGHTING_BENCH_ROUTE_CAPTURES") ? 2.0 : 60.0); + /* Readback can delay this frame and drain the next frame's GPU queue. */ + screenshot_frames = 3; + return TRUE; +} + +void lighting_performance_frame(void) +{ + int i; + double now = clock_seconds(); + if (origin) stationary_shield_scene(now - origin); + if (!origin) + { + origin = now; + previous = now; + next_capture = getenv("HALO_LIGHTING_BENCH_ROUTE_CAPTURES") ? 2.0 : 35.0; + timings = fopen("frames.csv", "w"); + if (!timings) return; + setvbuf(timings, NULL, _IOFBF, 65536); + fprintf(timings, "seconds,frame_ms,selected,scene_lights,occlusion_updates,capture_excluded,tick,occlusion_ms\n"); + } + if (phase_calls[0] || phase_calls[1] || phase_calls[2] || phase_calls[3] || phase_calls[7]) + { + if (!profile) + { + profile = fopen("profile.csv", "w"); + if (profile) + { + setvbuf(profile, NULL, _IOFBF, 65536); + fprintf(profile, "seconds,trace_ms,field_ms,texture_ms,bind_ms,prepare_ms,light_scene_ms,upload_ms,render_ms,traces,fields,textures,binds,prepares,light_scenes,uploads,renders,model_field_ms,model_resolve_ms,collision_scene_ms,mask_upload_ms\n"); + } + } + if (profile) + fprintf(profile, "%.6f,%.6f,%.6f,%.6f,%.6f,%.6f,%.6f,%.6f,%.6f,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%ld,%.6f,%.6f,%.6f,%.6f\n", now-origin, + phase_time[0]*1000, phase_time[1]*1000, phase_time[2]*1000, phase_time[3]*1000, + phase_time[4]*1000, phase_time[5]*1000, phase_time[6]*1000, phase_time[7]*1000, + phase_calls[0],phase_calls[1],phase_calls[2],phase_calls[3], + phase_calls[4],phase_calls[5],phase_calls[6],phase_calls[7], + phase_time[8]*1000,phase_time[9]*1000,phase_time[10]*1000,phase_time[11]*1000); + } + for (i = 0; i < LIGHTING_PROFILE_PHASES; i++) { phase_time[i] = 0; phase_calls[i] = 0; } + if (timings) + { + fprintf(timings, "%.6f,%.6f,%ld,%ld,%ld,%d,%ld,%.6f\n", now - origin, + (now - previous) * 1000.0, selected, lights, occlusion_updates, + screenshot_frames > 0, game_time_get(), occlusion_seconds * 1000.0); + if (now - flushed >= 1.0) + { + fflush(timings); + flushed = now; + } + } + if (screenshot_frames) screenshot_frames--; + previous = now; + occlusion_seconds = 0; +} diff --git a/tools/fixtures/lighting_resource_diagnostics.inc b/tools/fixtures/lighting_resource_diagnostics.inc new file mode 100644 index 0000000000..562caf0d2f --- /dev/null +++ b/tools/fixtures/lighting_resource_diagnostics.inc @@ -0,0 +1,45 @@ +/* Appended only to the diagnostic backend; no production API or state. */ +void lighting_resource_diagnostics(double seconds) +{ + static FILE *file; + unsigned long i, programs = 0, fragments = 0, targets = 0; + unsigned long sources = 0, source_bytes = 0; + unsigned long vertex_arrays = 0, mirror_buffers = 0, framebuffer_count = 0; + struct render_target_entry *target; + struct framebuffer_entry *framebuffer; + for (i = 0; i < PROGRAM_BUCKETS; i++) + { + struct program_entry *entry; + for (entry = program_buckets[i]; entry; entry = entry->next) programs++; + } + for (i = 0; i < FRAGMENT_BUCKETS; i++) + { + struct fragment_entry *entry; + struct fragment_source_entry *source; + for (entry = fragment_buckets[i]; entry; entry = entry->next) fragments++; + for (source = fragment_source_buckets[i]; source; source = source->next) + { + sources++; + source_bytes += strlen(source->source) + 1; + } + } + for (target = render_targets; target; target = target->next) targets++; + for (framebuffer = framebuffers; framebuffer; framebuffer = framebuffer->next) framebuffer_count++; + for (i = 0; i < VERTEX_ARRAY_BUCKET_COUNT; i++) + { + struct vertex_array_entry *entry; + for (entry = vertex_array_buckets[i]; entry; entry = entry->next) vertex_arrays++; + } + for (i = 0; i < MIRROR_SEGMENT_COUNT; i++) mirror_buffers += mirror.buffers[i] != 0; + if (!file) + { + file = fopen("resources.csv", "w"); + if (file) fprintf(file, "seconds,programs,fragments,targets,immediate_capacity,fragment_sources,fragment_source_bytes,vertex_arrays,samplers,mirror_buffers,framebuffers\n"); + } + if (file) + { + fprintf(file, "%.3f,%lu,%lu,%lu,%lu,%lu,%lu,%lu,%lu,%lu,%lu\n", seconds, programs, fragments, targets, device.immediate_capacity, sources, source_bytes, + vertex_arrays, sampler_cache_count, mirror_buffers, framebuffer_count); + fflush(file); + } +} diff --git a/tools/fixtures/lighting_stall_diagnostics.inc b/tools/fixtures/lighting_stall_diagnostics.inc new file mode 100644 index 0000000000..02e7f25ddc --- /dev/null +++ b/tools/fixtures/lighting_stall_diagnostics.inc @@ -0,0 +1,51 @@ +/* Windows diagnostic build only; no production API, state or GL queries. + GetThreadTimes reports CPU execution time in 100 ns units, not wall time: + https://learn.microsoft.com/windows/win32/api/processthreadsapi/nf-processthreadsapi-getthreadtimes + Keep its coarse accounting resolution in mind when interpreting short frames. */ +__declspec(dllimport) BOOL WINAPI GetThreadTimes(HANDLE, struct _FILETIME *, struct _FILETIME *, struct _FILETIME *, struct _FILETIME *); +static double stall_shader_started[2], stall_shader_ms[2]; +static unsigned long stall_shader_calls[2]; + +void lighting_stall_shader_begin(int kind) +{ + stall_shader_started[kind] = (double)SDL_GetPerformanceCounter() / (double)SDL_GetPerformanceFrequency(); +} + +void lighting_stall_shader_end(int kind) +{ + double now = (double)SDL_GetPerformanceCounter() / (double)SDL_GetPerformanceFrequency(); + stall_shader_ms[kind] += (now - stall_shader_started[kind])*1000.0; + stall_shader_calls[kind]++; +} + +void lighting_stall_frame(double seconds, double frame_ms) +{ + static FILE *file; + static double previous_cpu, flushed; + struct _FILETIME created, exited, kernel, user; + double cpu = -1, delta = -1; + if (GetThreadTimes(GetCurrentThread(), &created, &exited, &kernel, &user)) + { + cpu = ((double)kernel.dwHighDateTime*4294967296.0 + kernel.dwLowDateTime + + (double)user.dwHighDateTime*4294967296.0 + user.dwLowDateTime) / 10000.0; + if (previous_cpu > 0) delta = cpu - previous_cpu; + } + if (!file) + { + file = fopen("stalls.csv", "w"); + if (file) + { + setvbuf(file, NULL, _IOFBF, 65536); + fprintf(file, "seconds,frame_ms,thread_cpu_ms,compile_ms,link_ms,compiles,links\n"); + } + } + if (file) + { + fprintf(file, "%.6f,%.6f,%.6f,%.6f,%.6f,%lu,%lu\n", seconds, frame_ms, delta, + stall_shader_ms[0], stall_shader_ms[1], stall_shader_calls[0], stall_shader_calls[1]); + if (seconds-flushed >= 1) { fflush(file); flushed = seconds; } + } + previous_cpu = cpu; + stall_shader_ms[0] = stall_shader_ms[1] = 0; + stall_shader_calls[0] = stall_shader_calls[1] = 0; +} diff --git a/tools/fixtures/lighting_texture_diagnostics.inc b/tools/fixtures/lighting_texture_diagnostics.inc new file mode 100644 index 0000000000..24963939f4 --- /dev/null +++ b/tools/fixtures/lighting_texture_diagnostics.inc @@ -0,0 +1,25 @@ +/* Guest payload sizes describe retained cache entries, not driver allocations. */ +void lighting_texture_diagnostics(double seconds) +{ + static FILE *file; + unsigned long i, count = 0, bytes = 0, volumes = 0, volume_bytes = 0; + for (i = 0; i < TEXTURE_BUCKET_COUNT; i++) + { + struct texture_entry *entry; + for (entry = texture_buckets[i]; entry; entry = entry->next) + { + count++; bytes += entry->size; + if (entry->target == GL_TEXTURE_3D) { volumes++; volume_bytes += entry->size; } + } + } + if (!file) + { + file = fopen("textures.csv", "w"); + if (file) fprintf(file, "seconds,count,guest_bytes,volumes,volume_guest_bytes\n"); + } + if (file) + { + fprintf(file, "%.3f,%lu,%lu,%lu,%lu\n", seconds, count, bytes, volumes, volume_bytes); + fflush(file); + } +} diff --git a/tools/fixtures/lighting_trace_check.inc b/tools/fixtures/lighting_trace_check.inc new file mode 100644 index 0000000000..aaf8306457 --- /dev/null +++ b/tools/fixtures/lighting_trace_check.inc @@ -0,0 +1,71 @@ +/* Same rays and pose; no simulation step intervenes. Rotate timing order to + balance cache warming. Compare outputs outside the measured intervals. */ +#include +int lighting_trace_uncached, lighting_trace_unprepared; +static void trace_depths(real extent, real_point3d const *from, long ignore, int vehicles, int resolution, + real depths[6][OCC_SIZE * OCC_SIZE]) +{ + static FILE *file; + static unsigned long rays, mismatches, last, batches; + static double ticks[4]; + static unsigned long cache_mismatches, unprepared_mismatches; + real reference[6][OCC_SIZE * OCC_SIZE]; + real uncached[6][OCC_SIZE * OCC_SIZE]; + real unprepared[6][OCC_SIZE * OCC_SIZE]; + LARGE_INTEGER begin, end, frequency; + unsigned long now; + int face, cell, index, phase; + for (index = 0; index < 4; index++) + { + phase = (index + batches) % 4; + QueryPerformanceCounter(&begin); + switch (phase) + { + case 0: trace_depths_actual(extent, from, ignore, vehicles, resolution, depths); break; + case 1: trace_depths_reference(extent, from, ignore, vehicles, resolution, reference); break; + case 2: + lighting_trace_uncached = 1; + trace_depths_actual(extent, from, ignore, vehicles, resolution, uncached); + lighting_trace_uncached = 0; + break; + case 3: + lighting_trace_unprepared = 1; + trace_depths_actual(extent, from, ignore, vehicles, resolution, unprepared); + lighting_trace_unprepared = 0; + break; + } + QueryPerformanceCounter(&end); + ticks[phase] += (double)(end.QuadPart-begin.QuadPart); + } + batches++; + for (face = 0; face < 6; face++) + for (cell = 0; cell < OCC_SIZE * resolution; cell++) + { + if (cell % OCC_SIZE >= resolution) continue; + rays++; + cache_mismatches += depths[face][cell] != uncached[face][cell]; + unprepared_mismatches += depths[face][cell] != unprepared[face][cell]; + if (depths[face][cell] != reference[face][cell]) + { + mismatches++; + if (mismatches <= 10) fprintf(stderr, "TRACE mismatch %.9g %.9g face %d cell %d\n", + depths[face][cell], reference[face][cell], face, cell); + } + } + if (!file) + { + file = fopen("trace-check.csv", "w"); + if (file) fprintf(file, "milliseconds,rays,mismatches,batches,fast_ms,stock_ms,uncached_ms,cache_mismatches,unprepared_ms,unprepared_mismatches\n"); + } + now = GetTickCount(); + if (file && now-last >= 1000) + { + QueryPerformanceFrequency(&frequency); + fprintf(file, "%lu,%lu,%lu,%lu,%.6f,%.6f,%.6f,%lu,%.6f,%lu\n", now, rays, mismatches, batches, + ticks[0]*1000/(double)frequency.QuadPart, ticks[1]*1000/(double)frequency.QuadPart, + ticks[2]*1000/(double)frequency.QuadPart, cache_mismatches, + ticks[3]*1000/(double)frequency.QuadPart, unprepared_mismatches); + fflush(file); + last = now; + } +} diff --git a/tools/fixtures/opence_network_29.txt b/tools/fixtures/opence_network_29.txt new file mode 100644 index 0000000000..441fc28ebe --- /dev/null +++ b/tools/fixtures/opence_network_29.txt @@ -0,0 +1,277 @@ +version 29 +bound CHAT_TEXT_SIZE 64 +bound DISCORD_ID_SIZE 24 +bound DISCORD_NAME_SIZE 40 +bound DISTRIBUTED_INPUT_HISTORY 4 +bound DISTRIBUTED_RELAYED_ACTION_MAXIMUM_SIZE 14 + 2 * (DISTRIBUTED_INPUT_HISTORY - 1) +bound DISTRIBUTED_RELAYED_ACTION_MINIMUM_SIZE 14 +bound DISTRIBUTED_UNIT_STATE_MAXIMUM_SIZE 3 + 4 + (4 + 2) + (12 + 3 * 6) + 2 + 2 * 2 + 4 * 2 + 2 * NUMBER_OF_PLAYER_POWERUPS + 2 + 1 +bound DISTRIBUTED_UNIT_STATE_MINIMUM_SIZE 3 +bound GAME_ALLEGIANCE_BITVECTOR_LONGS 4 +bound LEVEL_NAME_BYTES 64 +bound MAP_SHARE_HASH_BYTES 32 +bound MAXIMUM_DEVICE_GROUPS 1024 +bound MAXIMUM_DEVICE_STATES_PER_MESSAGE 64 +bound MAXIMUM_ENTRIES_PER_MESSAGE 64 +bound MAXIMUM_OBJECT_LOOKS_PER_MESSAGE 64 +bound MAXIMUM_OBJECT_NAMES_PER_SCENARIO 0x200 +bound MAXIMUM_OBJECT_TRANSFORMS_PER_MESSAGE 64 +bound MAXIMUM_PINGS_PER_MESSAGE 128 +bound MAXIMUM_QUEUED_DAMAGE_ANIMATIONS 32 +bound MAXIMUM_QUEUED_EVENTS 128 +bound MAXIMUM_REGIONS_PER_OBJECT 8 +bound MAXIMUM_STATISTICS_PER_MESSAGE 64 +bound MAXIMUM_WEAPONS_PER_UNIT 4 +bound NUMBER_OF_ANGLES enum f0ce7d0319b6 +bound NUMBER_OF_OBJECT_CHANGE_COLORS enum b00724872e2d +bound NUMBER_OF_PLAYER_POWERUPS enum 43075f42087c +bound NUMBER_OF_UNIT_GRENADE_TYPES enum a0462dbcbdd9 +bound OBJECT_NAME_BYTES MAXIMUM_OBJECT_NAMES_PER_SCENARIO / 8 +bound P2P_PLAYER_KEY_HASH_SIZE 16 +define DISTRIBUTED_ANGULAR_VELOCITY_SCALE 4096.0f +define DISTRIBUTED_UNIT_SCALE 32767.0f +define DISTRIBUTED_VELOCITY_SCALE 1024.0f +enum _distributed_actor_camouflaged_bit 4 +enum _distributed_actor_impulse_aligned_bit 6 +enum _distributed_actor_rides_bit 0 +enum _distributed_actor_running_blindly_bit 7 +enum _distributed_actor_shield_charging_bit 2 +enum _distributed_actor_shield_depleted_bit 1 +enum _distributed_actor_shield_over_charging_bit 3 +enum _distributed_actor_super_camouflaged_bit 5 +enum _distributed_message_actor_damage 73 +enum _distributed_message_actor_states 64 +enum _distributed_message_batch 16 +enum _distributed_message_chat_config 89 +enum _distributed_message_chat_down 88 +enum _distributed_message_chat_up 87 +enum _distributed_message_client_identity 18 +enum _distributed_message_client_ready 9 +enum _distributed_message_coop_device_groups 68 +enum _distributed_message_coop_device_states 77 +enum _distributed_message_coop_events 71 +enum _distributed_message_coop_object_looks 74 +enum _distributed_message_coop_object_names 69 +enum _distributed_message_coop_object_transforms 72 +enum _distributed_message_coop_presentation 66 +enum _distributed_message_coop_screen_effect 76 +enum _distributed_message_coop_skip_vote 70 +enum _distributed_message_coop_sounds_retired 67 +enum _distributed_message_damage_animations 75 +enum _distributed_message_damage_events 10 +enum _distributed_message_game_state 7 +enum _distributed_message_hit_reports 11 +enum _distributed_message_inventories 4 +enum _distributed_message_map_share_offer 84 +enum _distributed_message_map_share_progress 86 +enum _distributed_message_map_share_request 83 +enum _distributed_message_map_share_sources 85 +enum _distributed_message_notice 17 +enum _distributed_message_object_changes 5 +enum _distributed_message_object_states 6 +enum _distributed_message_objects_synchronized 8 +enum _distributed_message_pickups 13 +enum _distributed_message_pings 19 +enum _distributed_message_player_inputs 14 +enum _distributed_message_player_prediction 1 +enum _distributed_message_player_statistics 3 +enum _distributed_message_relayed_actions 15 +enum _distributed_message_structure_bsp 65 +enum _distributed_message_unit_states 2 +enum _distributed_message_vehicle_prediction 12 +enum _distributed_message_voice_config 82 +enum _distributed_message_voice_down 81 +enum _distributed_message_voice_up 80 +enum _distributed_message_votekick 78 +enum _distributed_message_votekick_status 79 +enum _distributed_object_at_rest_bit 1 +enum _distributed_object_carried_bit 0 +enum _distributed_object_dead_bit 2 +enum _distributed_object_light_on_bit 5 +enum _distributed_object_light_sent_bit 4 +enum _distributed_object_predicted_bit 3 +enum _distributed_send_action_bit 1 +enum _distributed_send_sees_bit 2 +enum _distributed_send_state_bit 0 +enum _distributed_to_clients 0 +enum _distributed_to_clients_reliably 1 +enum _distributed_to_host 2 +enum _distributed_to_host_reliably 3 +enum _distributed_unit_alive_bit 0 +enum _distributed_unit_camouflaged_bit 0 +enum _distributed_unit_friendly_fire_bit 2 +enum _distributed_unit_killed_by_vehicle_bit 3 +enum _distributed_unit_part_camouflage_bit 4 +enum _distributed_unit_part_damage_bit 2 +enum _distributed_unit_part_killer_bit 5 +enum _distributed_unit_part_powerups_bit 3 +enum _distributed_unit_part_riding_bit 0 +enum _distributed_unit_part_up_bit 1 +enum _distributed_unit_placed_bit 1 +enum _distributed_unit_predicted_bit 7 +enum _distributed_unit_shield_charging_bit 5 +enum _distributed_unit_shield_depleted_bit 4 +enum _distributed_unit_shield_over_charging_bit 6 +enum _distributed_unit_super_camouflaged_bit 1 +enum _message_client_add_player_request_ingame 26 +enum _message_client_add_player_request_pregame 13 +enum _message_client_broadcast_game_search 0 +enum _message_client_game_start_request 17 +enum _message_client_game_update 25 +enum _message_client_graceful_game_exit_postgame 34 +enum _message_client_graceful_game_exit_pregame 18 +enum _message_client_host_crashed_cry_for_help 28 +enum _message_client_join_game_request 12 +enum _message_client_join_new_host 29 +enum _message_client_loaded 24 +enum _message_client_map_is_precached_pregame 19 +enum _message_client_ping 1 +enum _message_client_player_settings_request 16 +enum _message_client_remove_player_request_ingame 27 +enum _message_client_remove_player_request_postgame 32 +enum _message_client_remove_player_request_pregame 14 +enum _message_client_settings_request 15 +enum _message_client_switch_to_pregame 33 +enum _message_server_add_player_ingame 21 +enum _message_server_begin_game 8 +enum _message_server_game_advertise 2 +enum _message_server_game_over 23 +enum _message_server_game_settings_update 6 +enum _message_server_game_update 20 +enum _message_server_graceful_game_exit_postgame 31 +enum _message_server_graceful_game_exit_pregame 9 +enum _message_server_machine_accepted 4 +enum _message_server_machine_rejected 5 +enum _message_server_pong 3 +enum _message_server_postgame_keep_alive 11 +enum _message_server_pregame_countdown 7 +enum _message_server_pregame_keep_alive 10 +enum _message_server_remove_player_ingame 22 +enum _message_server_switch_to_pregame 30 +fields client_add_player_request_ingame 06ff007a9b35 +fields client_add_player_request_pregame 06ff007a9b35 +fields client_broadcast_game_search f31a5fac9a46 +fields client_game_start_request 758215ada4e1 +fields client_game_update 1134bf6a029b +fields client_graceful_game_exit_postgame 678699dea271 +fields client_graceful_game_exit_pregame 678699dea271 +fields client_host_crashed_cry_for_help 52eb2291ec03 +fields client_join_game_request 28f7514cbcd9 +fields client_join_new_host 52eb2291ec03 +fields client_loaded 678699dea271 +fields client_map_is_precached_pregame 0073b9d65051 +fields client_ping 0d113e26a89a +fields client_player_settings_request 06ff007a9b35 +fields client_remove_player_request_ingame 06ff007a9b35 +fields client_remove_player_request_postgame 06ff007a9b35 +fields client_remove_player_request_pregame 06ff007a9b35 +fields client_settings_request d6a7048d6284 +fields client_switch_to_pregame 678699dea271 +fields server_add_player_ingame 06ff007a9b35 +fields server_begin_game 678699dea271 +fields server_game_advertise 2d5f42b781a4 +fields server_game_over 678699dea271 +fields server_game_settings_update 4c2744d8b8e8 +fields server_game_update beee6fb1929d +fields server_graceful_game_exit_postgame 678699dea271 +fields server_graceful_game_exit_pregame 678699dea271 +fields server_machine_accepted 0d113e26a89a +fields server_machine_rejected 758215ada4e1 +fields server_pong 678699dea271 +fields server_postgame_keep_alive 758215ada4e1 +fields server_pregame_countdown 758215ada4e1 +fields server_pregame_keep_alive 758215ada4e1 +fields server_remove_player_ingame 1718d4189972 +fields server_switch_to_pregame 678699dea271 +size message_client_add_player_request_ingame 0x20 +size message_client_add_player_request_pregame 0x20 +size message_client_broadcast_game_search 0x0C +size message_client_game_start_request 0x02 +size message_client_game_update 0x88 +size message_client_graceful_game_exit_postgame 0x04 +size message_client_graceful_game_exit_pregame 0x04 +size message_client_host_crashed_cry_for_help 0x10 +size message_client_join_game_request 0x70 +size message_client_join_new_host 0x10 +size message_client_loaded 0x04 +size message_client_map_is_precached_pregame 0x100 +size message_client_ping 0x08 +size message_client_player_settings_request 0x20 +size message_client_remove_player_request_ingame 0x20 +size message_client_remove_player_request_postgame 0x20 +size message_client_remove_player_request_pregame 0x20 +size message_client_settings_request 0x44 +size message_client_switch_to_pregame 0x04 +size message_server_add_player_ingame 0x20 +size message_server_begin_game 0x04 +size message_server_game_advertise 0x114 +size message_server_game_over 0x04 +size message_server_game_settings_update 8 + HALO_PORT_NETWORK_GAME_SETTINGS_FRAGMENT_SIZE +size message_server_game_update 0x10 + HALO_PORT_MAXIMUM_NETWORK_PLAYERS * 0x20 +size message_server_graceful_game_exit_postgame 0x04 +size message_server_graceful_game_exit_pregame 0x04 +size message_server_machine_accepted 0x08 +size message_server_machine_rejected 0x02 +size message_server_pong 0x04 +size message_server_postgame_keep_alive 0x02 +size message_server_pregame_countdown 0x02 +size message_server_pregame_keep_alive 0x02 +size message_server_remove_player_ingame 0x24 +size message_server_switch_to_pregame 0x04 +struct distributed_actor_damage 96a57e13e2b8 +struct distributed_actor_damage_message f985e899a708 +struct distributed_actor_state 8bd5e771659d +struct distributed_actor_state_message 51a56e04a536 +struct distributed_chat_config dfa4e32efe1e +struct distributed_chat_line cdab1468ffe0 +struct distributed_client_identity 4d9e62025616 +struct distributed_coop_device_group 4aa3499be2cc +struct distributed_coop_device_groups_message b96ad0030ccc +struct distributed_coop_device_state 727444a5c79b +struct distributed_coop_device_states_message 48f17c3da6f5 +struct distributed_coop_event 62bbd76ba4af +struct distributed_coop_events_message 562bdd70bfae +struct distributed_coop_object_look 77cbae00e4ad +struct distributed_coop_object_looks_message 51dbb474aa17 +struct distributed_coop_object_names f3ecad927448 +struct distributed_coop_object_names_message 7d743ad3710e +struct distributed_coop_object_transform 055897bbff8f +struct distributed_coop_object_transforms_message de95468f7f6d +struct distributed_coop_presentation f34649b3fc6d +struct distributed_coop_presentation_message eb4c7a895272 +struct distributed_coop_screen_effect_message a0a226e0858e +struct distributed_coop_skip_vote c37a12a02932 +struct distributed_coop_skip_vote_message d21260f32711 +struct distributed_damage d2bdb398fb2b +struct distributed_damage_animation ae158e21c915 +struct distributed_damage_animations_message 863e25ca3614 +struct distributed_damage_event 659e4d49733b +struct distributed_damage_event_message c954363dcf26 +struct distributed_hit_report 9a44ca43a88b +struct distributed_hit_report_message 37279f2addca +struct distributed_inventory 05a279a76ba5 +struct distributed_inventory_message 11825a84dc29 +struct distributed_map_share_offer 4bea857123c2 +struct distributed_map_share_offer_file 204a3b73d193 +struct distributed_map_share_progress 2c3831013302 +struct distributed_map_share_request 3cdcbc8c3a49 +struct distributed_map_share_source 940f8a4c9849 +struct distributed_message_header 0e026a4933a1 +struct distributed_object_change 343e570cfa1d +struct distributed_object_change_message 4c3679cd4dae +struct distributed_object_state 1b656bbda892 +struct distributed_object_state_message 004c4b7aa530 +struct distributed_pickup 46e6f981ac40 +struct distributed_pings_message 35c6009dee29 +struct distributed_player_input b8d724b59f5c +struct distributed_player_ping 377e0e3045f4 +struct distributed_player_statistics 2a44afb8f96c +struct distributed_statistics_message 79134e6e9811 +struct distributed_structure_bsp 53f7d5067cc9 +struct distributed_structure_bsp_message 096278a05681 +struct distributed_vector e80d7f9fc970 +struct distributed_voice_config 665bdc14478b +struct distributed_voice_down e3751d692f16 +struct distributed_voice_up 3d74ee44e4cb +struct distributed_votekick_request d5f913f22d81 +struct distributed_votekick_status 966041386843 diff --git a/tools/fixtures/opence_network_32.txt b/tools/fixtures/opence_network_32.txt new file mode 100644 index 0000000000..4aa141519b --- /dev/null +++ b/tools/fixtures/opence_network_32.txt @@ -0,0 +1,279 @@ +version 32 +bound CHAT_TEXT_SIZE 64 +bound DISCORD_ID_SIZE 24 +bound DISCORD_NAME_SIZE 40 +bound DISTRIBUTED_INPUT_HISTORY 4 +bound DISTRIBUTED_RELAYED_ACTION_MAXIMUM_SIZE 14 + 2 * (DISTRIBUTED_INPUT_HISTORY - 1) +bound DISTRIBUTED_RELAYED_ACTION_MINIMUM_SIZE 14 +bound DISTRIBUTED_UNIT_STATE_MAXIMUM_SIZE 3 + 4 + (4 + 2) + (12 + 3 * 6) + 2 + 2 * 2 + 4 * 2 + 2 * NUMBER_OF_PLAYER_POWERUPS + 2 + 1 +bound DISTRIBUTED_UNIT_STATE_MINIMUM_SIZE 3 +bound GAME_ALLEGIANCE_BITVECTOR_LONGS 4 +bound LEVEL_NAME_BYTES 64 +bound MAP_SHARE_HASH_BYTES 32 +bound MAXIMUM_DEVICE_GROUPS 1024 +bound MAXIMUM_DEVICE_STATES_PER_MESSAGE 64 +bound MAXIMUM_ENTRIES_PER_MESSAGE 64 +bound MAXIMUM_OBJECT_LOOKS_PER_MESSAGE 64 +bound MAXIMUM_OBJECT_NAMES_PER_SCENARIO 0x200 +bound MAXIMUM_OBJECT_TRANSFORMS_PER_MESSAGE 64 +bound MAXIMUM_PINGS_PER_MESSAGE 128 +bound MAXIMUM_QUEUED_DAMAGE_ANIMATIONS 32 +bound MAXIMUM_QUEUED_EVENTS 128 +bound MAXIMUM_REGIONS_PER_OBJECT 8 +bound MAXIMUM_STATISTICS_PER_MESSAGE 64 +bound MAXIMUM_WEAPONS_PER_UNIT 4 +bound NUMBER_OF_ANGLES enum f0ce7d0319b6 +bound NUMBER_OF_OBJECT_CHANGE_COLORS enum b00724872e2d +bound NUMBER_OF_PLAYER_POWERUPS enum 43075f42087c +bound NUMBER_OF_UNIT_GRENADE_TYPES enum a0462dbcbdd9 +bound OBJECT_NAME_BYTES MAXIMUM_OBJECT_NAMES_PER_SCENARIO / 8 +bound P2P_PLAYER_KEY_HASH_SIZE 16 +define DISTRIBUTED_ANGULAR_VELOCITY_SCALE 4096.0f +define DISTRIBUTED_TIME_WINDOW_TICKS (15 * TICKS_PER_SECOND) +define DISTRIBUTED_UNIT_SCALE 32767.0f +define DISTRIBUTED_VELOCITY_SCALE 1024.0f +enum _distributed_actor_camouflaged_bit 4 +enum _distributed_actor_impulse_aligned_bit 6 +enum _distributed_actor_rides_bit 0 +enum _distributed_actor_running_blindly_bit 7 +enum _distributed_actor_shield_charging_bit 2 +enum _distributed_actor_shield_depleted_bit 1 +enum _distributed_actor_shield_over_charging_bit 3 +enum _distributed_actor_super_camouflaged_bit 5 +enum _distributed_message_actor_damage 73 +enum _distributed_message_actor_states 64 +enum _distributed_message_aim_assist_policy 90 +enum _distributed_message_batch 16 +enum _distributed_message_chat_config 89 +enum _distributed_message_chat_down 88 +enum _distributed_message_chat_up 87 +enum _distributed_message_client_identity 18 +enum _distributed_message_client_ready 9 +enum _distributed_message_coop_device_groups 68 +enum _distributed_message_coop_device_states 77 +enum _distributed_message_coop_events 71 +enum _distributed_message_coop_object_looks 74 +enum _distributed_message_coop_object_names 69 +enum _distributed_message_coop_object_transforms 72 +enum _distributed_message_coop_presentation 66 +enum _distributed_message_coop_screen_effect 76 +enum _distributed_message_coop_skip_vote 70 +enum _distributed_message_coop_sounds_retired 67 +enum _distributed_message_damage_animations 75 +enum _distributed_message_damage_events 10 +enum _distributed_message_game_state 7 +enum _distributed_message_hit_reports 11 +enum _distributed_message_inventories 4 +enum _distributed_message_map_share_offer 84 +enum _distributed_message_map_share_progress 86 +enum _distributed_message_map_share_request 83 +enum _distributed_message_map_share_sources 85 +enum _distributed_message_notice 17 +enum _distributed_message_object_changes 5 +enum _distributed_message_object_states 6 +enum _distributed_message_objects_synchronized 8 +enum _distributed_message_pickups 13 +enum _distributed_message_pings 19 +enum _distributed_message_player_inputs 14 +enum _distributed_message_player_prediction 1 +enum _distributed_message_player_statistics 3 +enum _distributed_message_relayed_actions 15 +enum _distributed_message_structure_bsp 65 +enum _distributed_message_unit_states 2 +enum _distributed_message_vehicle_prediction 12 +enum _distributed_message_voice_config 82 +enum _distributed_message_voice_down 81 +enum _distributed_message_voice_up 80 +enum _distributed_message_votekick 78 +enum _distributed_message_votekick_status 79 +enum _distributed_object_at_rest_bit 1 +enum _distributed_object_carried_bit 0 +enum _distributed_object_dead_bit 2 +enum _distributed_object_light_on_bit 5 +enum _distributed_object_light_sent_bit 4 +enum _distributed_object_predicted_bit 3 +enum _distributed_send_action_bit 1 +enum _distributed_send_sees_bit 2 +enum _distributed_send_state_bit 0 +enum _distributed_to_clients 0 +enum _distributed_to_clients_reliably 1 +enum _distributed_to_host 2 +enum _distributed_to_host_reliably 3 +enum _distributed_unit_alive_bit 0 +enum _distributed_unit_camouflaged_bit 0 +enum _distributed_unit_friendly_fire_bit 2 +enum _distributed_unit_killed_by_vehicle_bit 3 +enum _distributed_unit_part_camouflage_bit 4 +enum _distributed_unit_part_damage_bit 2 +enum _distributed_unit_part_killer_bit 5 +enum _distributed_unit_part_powerups_bit 3 +enum _distributed_unit_part_riding_bit 0 +enum _distributed_unit_part_up_bit 1 +enum _distributed_unit_placed_bit 1 +enum _distributed_unit_predicted_bit 7 +enum _distributed_unit_shield_charging_bit 5 +enum _distributed_unit_shield_depleted_bit 4 +enum _distributed_unit_shield_over_charging_bit 6 +enum _distributed_unit_super_camouflaged_bit 1 +enum _message_client_add_player_request_ingame 26 +enum _message_client_add_player_request_pregame 13 +enum _message_client_broadcast_game_search 0 +enum _message_client_game_start_request 17 +enum _message_client_game_update 25 +enum _message_client_graceful_game_exit_postgame 34 +enum _message_client_graceful_game_exit_pregame 18 +enum _message_client_host_crashed_cry_for_help 28 +enum _message_client_join_game_request 12 +enum _message_client_join_new_host 29 +enum _message_client_loaded 24 +enum _message_client_map_is_precached_pregame 19 +enum _message_client_ping 1 +enum _message_client_player_settings_request 16 +enum _message_client_remove_player_request_ingame 27 +enum _message_client_remove_player_request_postgame 32 +enum _message_client_remove_player_request_pregame 14 +enum _message_client_settings_request 15 +enum _message_client_switch_to_pregame 33 +enum _message_server_add_player_ingame 21 +enum _message_server_begin_game 8 +enum _message_server_game_advertise 2 +enum _message_server_game_over 23 +enum _message_server_game_settings_update 6 +enum _message_server_game_update 20 +enum _message_server_graceful_game_exit_postgame 31 +enum _message_server_graceful_game_exit_pregame 9 +enum _message_server_machine_accepted 4 +enum _message_server_machine_rejected 5 +enum _message_server_pong 3 +enum _message_server_postgame_keep_alive 11 +enum _message_server_pregame_countdown 7 +enum _message_server_pregame_keep_alive 10 +enum _message_server_remove_player_ingame 22 +enum _message_server_switch_to_pregame 30 +fields client_add_player_request_ingame 06ff007a9b35 +fields client_add_player_request_pregame 06ff007a9b35 +fields client_broadcast_game_search f31a5fac9a46 +fields client_game_start_request 758215ada4e1 +fields client_game_update 1134bf6a029b +fields client_graceful_game_exit_postgame 678699dea271 +fields client_graceful_game_exit_pregame 678699dea271 +fields client_host_crashed_cry_for_help 52eb2291ec03 +fields client_join_game_request 28f7514cbcd9 +fields client_join_new_host 52eb2291ec03 +fields client_loaded 678699dea271 +fields client_map_is_precached_pregame 0073b9d65051 +fields client_ping 0d113e26a89a +fields client_player_settings_request 06ff007a9b35 +fields client_remove_player_request_ingame 06ff007a9b35 +fields client_remove_player_request_postgame 06ff007a9b35 +fields client_remove_player_request_pregame 06ff007a9b35 +fields client_settings_request d6a7048d6284 +fields client_switch_to_pregame 678699dea271 +fields server_add_player_ingame 06ff007a9b35 +fields server_begin_game 87e5d5c7565c +fields server_game_advertise 2d5f42b781a4 +fields server_game_over 678699dea271 +fields server_game_settings_update 4c2744d8b8e8 +fields server_game_update beee6fb1929d +fields server_graceful_game_exit_postgame 678699dea271 +fields server_graceful_game_exit_pregame 678699dea271 +fields server_machine_accepted 0d113e26a89a +fields server_machine_rejected 758215ada4e1 +fields server_pong 678699dea271 +fields server_postgame_keep_alive 758215ada4e1 +fields server_pregame_countdown 758215ada4e1 +fields server_pregame_keep_alive 678699dea271 +fields server_remove_player_ingame 1718d4189972 +fields server_switch_to_pregame 678699dea271 +size message_client_add_player_request_ingame 0x20 +size message_client_add_player_request_pregame 0x20 +size message_client_broadcast_game_search 0x0C +size message_client_game_start_request 0x02 +size message_client_game_update 0x88 +size message_client_graceful_game_exit_postgame 0x04 +size message_client_graceful_game_exit_pregame 0x04 +size message_client_host_crashed_cry_for_help 0x10 +size message_client_join_game_request 0x70 +size message_client_join_new_host 0x10 +size message_client_loaded 0x04 +size message_client_map_is_precached_pregame 0x100 +size message_client_ping 0x08 +size message_client_player_settings_request 0x20 +size message_client_remove_player_request_ingame 0x20 +size message_client_remove_player_request_postgame 0x20 +size message_client_remove_player_request_pregame 0x20 +size message_client_settings_request 0x44 +size message_client_switch_to_pregame 0x04 +size message_server_add_player_ingame 0x20 +size message_server_begin_game 0x04 +size message_server_game_advertise 0x114 +size message_server_game_over 0x04 +size message_server_game_settings_update 8 + HALO_PORT_NETWORK_GAME_SETTINGS_FRAGMENT_SIZE +size message_server_game_update 0x10 + HALO_PORT_MAXIMUM_NETWORK_PLAYERS * 0x20 +size message_server_graceful_game_exit_postgame 0x04 +size message_server_graceful_game_exit_pregame 0x04 +size message_server_machine_accepted 0x08 +size message_server_machine_rejected 0x02 +size message_server_pong 0x04 +size message_server_postgame_keep_alive 0x02 +size message_server_pregame_countdown 0x02 +size message_server_pregame_keep_alive 0x04 +size message_server_remove_player_ingame 0x24 +size message_server_switch_to_pregame 0x04 +struct distributed_actor_damage 96a57e13e2b8 +struct distributed_actor_damage_message f985e899a708 +struct distributed_actor_state 8bd5e771659d +struct distributed_actor_state_message 51a56e04a536 +struct distributed_chat_config dfa4e32efe1e +struct distributed_chat_line cdab1468ffe0 +struct distributed_client_identity 4d9e62025616 +struct distributed_coop_device_group 4aa3499be2cc +struct distributed_coop_device_groups_message b96ad0030ccc +struct distributed_coop_device_state 727444a5c79b +struct distributed_coop_device_states_message 48f17c3da6f5 +struct distributed_coop_event 62bbd76ba4af +struct distributed_coop_events_message 562bdd70bfae +struct distributed_coop_object_look 77cbae00e4ad +struct distributed_coop_object_looks_message 51dbb474aa17 +struct distributed_coop_object_names f3ecad927448 +struct distributed_coop_object_names_message 7d743ad3710e +struct distributed_coop_object_transform 055897bbff8f +struct distributed_coop_object_transforms_message de95468f7f6d +struct distributed_coop_presentation f34649b3fc6d +struct distributed_coop_presentation_message eb4c7a895272 +struct distributed_coop_screen_effect_message a0a226e0858e +struct distributed_coop_skip_vote c37a12a02932 +struct distributed_coop_skip_vote_message d21260f32711 +struct distributed_damage d2bdb398fb2b +struct distributed_damage_animation ae158e21c915 +struct distributed_damage_animations_message 863e25ca3614 +struct distributed_damage_event 659e4d49733b +struct distributed_damage_event_message c954363dcf26 +struct distributed_hit_report 9a44ca43a88b +struct distributed_hit_report_message 37279f2addca +struct distributed_inventory 05a279a76ba5 +struct distributed_inventory_message 11825a84dc29 +struct distributed_map_share_offer 4bea857123c2 +struct distributed_map_share_offer_file 204a3b73d193 +struct distributed_map_share_progress 2c3831013302 +struct distributed_map_share_request 3cdcbc8c3a49 +struct distributed_map_share_source 940f8a4c9849 +struct distributed_message_header 0e026a4933a1 +struct distributed_object_change 343e570cfa1d +struct distributed_object_change_message 4c3679cd4dae +struct distributed_object_state 1b656bbda892 +struct distributed_object_state_message 004c4b7aa530 +struct distributed_pickup 46e6f981ac40 +struct distributed_pings_message 35c6009dee29 +struct distributed_player_input a0cf65a1197c +struct distributed_player_ping 377e0e3045f4 +struct distributed_player_statistics 2a44afb8f96c +struct distributed_statistics_message 79134e6e9811 +struct distributed_structure_bsp 53f7d5067cc9 +struct distributed_structure_bsp_message 096278a05681 +struct distributed_vector e80d7f9fc970 +struct distributed_voice_config 665bdc14478b +struct distributed_voice_down e3751d692f16 +struct distributed_voice_up 3d74ee44e4cb +struct distributed_votekick_request d5f913f22d81 +struct distributed_votekick_status 966041386843 diff --git a/tools/fixtures/opence_network_36.txt b/tools/fixtures/opence_network_36.txt new file mode 100644 index 0000000000..643b00a1c5 --- /dev/null +++ b/tools/fixtures/opence_network_36.txt @@ -0,0 +1,294 @@ +version 36 +bound CHAT_TEXT_SIZE 64 +bound DISCORD_ID_SIZE 24 +bound DISCORD_NAME_SIZE 40 +bound DISTRIBUTED_INPUT_HISTORY 4 +bound DISTRIBUTED_RELAYED_ACTION_MAXIMUM_SIZE 14 + 2 * (DISTRIBUTED_INPUT_HISTORY - 1) +bound DISTRIBUTED_RELAYED_ACTION_MINIMUM_SIZE 14 +bound DISTRIBUTED_UNIT_STATE_MAXIMUM_SIZE 3 + 4 + (4 + 2) + (12 + 3 * 6) + 2 + 2 * 2 + 4 * 2 + 2 * NUMBER_OF_PLAYER_POWERUPS + 2 + 1 +bound DISTRIBUTED_UNIT_STATE_MINIMUM_SIZE 3 +bound GAME_ALLEGIANCE_BITVECTOR_LONGS 4 +bound HALO_PORT_MAXIMUM_NETWORK_PLAYERS 128 +bound LEVEL_NAME_BYTES 64 +bound MAP_SHARE_HASH_BYTES 32 +bound MAXIMUM_DEVICE_GROUPS 1024 +bound MAXIMUM_DEVICE_STATES_PER_MESSAGE 64 +bound MAXIMUM_ENTRIES_PER_MESSAGE 64 +bound MAXIMUM_OBJECT_LOOKS_PER_MESSAGE 64 +bound MAXIMUM_OBJECT_NAMES_PER_SCENARIO 0x200 +bound MAXIMUM_OBJECT_TRANSFORMS_PER_MESSAGE 64 +bound MAXIMUM_PINGS_PER_MESSAGE 128 +bound MAXIMUM_QUEUED_DAMAGE_ANIMATIONS 32 +bound MAXIMUM_QUEUED_EVENTS 128 +bound MAXIMUM_REGIONS_PER_OBJECT 8 +bound MAXIMUM_STATISTICS_PER_MESSAGE 64 +bound MAXIMUM_WEAPONS_PER_UNIT 4 +bound NUMBER_OF_ANGLES enum f0ce7d0319b6 +bound NUMBER_OF_OBJECT_CHANGE_COLORS enum b00724872e2d +bound NUMBER_OF_PLAYER_POWERUPS enum 43075f42087c +bound NUMBER_OF_UNIT_GRENADE_TYPES enum a0462dbcbdd9 +bound OBJECT_NAME_BYTES MAXIMUM_OBJECT_NAMES_PER_SCENARIO / 8 +bound P2P_PLAYER_KEY_HASH_SIZE 16 +define DISTRIBUTED_ANGULAR_VELOCITY_SCALE 4096.0f +define DISTRIBUTED_TIME_WINDOW_TICKS (15 * TICKS_PER_SECOND) +define DISTRIBUTED_UNIT_SCALE 32767.0f +define DISTRIBUTED_VELOCITY_SCALE 1024.0f +enum _distributed_actor_camouflaged_bit 4 +enum _distributed_actor_impulse_aligned_bit 6 +enum _distributed_actor_rides_bit 0 +enum _distributed_actor_running_blindly_bit 7 +enum _distributed_actor_shield_charging_bit 2 +enum _distributed_actor_shield_depleted_bit 1 +enum _distributed_actor_shield_over_charging_bit 3 +enum _distributed_actor_super_camouflaged_bit 5 +enum _distributed_infection_active 2 +enum _distributed_infection_countdown 1 +enum _distributed_infection_finished 3 +enum _distributed_infection_role_human 1 +enum _distributed_infection_role_none 0 +enum _distributed_infection_role_zombie 2 +enum _distributed_infection_waiting 0 +enum _distributed_message_actor_damage 73 +enum _distributed_message_actor_states 64 +enum _distributed_message_aim_assist_policy 90 +enum _distributed_message_batch 16 +enum _distributed_message_chat_config 89 +enum _distributed_message_chat_down 88 +enum _distributed_message_chat_up 87 +enum _distributed_message_client_identity 18 +enum _distributed_message_client_ready 9 +enum _distributed_message_coop_device_groups 68 +enum _distributed_message_coop_device_states 77 +enum _distributed_message_coop_events 71 +enum _distributed_message_coop_object_looks 74 +enum _distributed_message_coop_object_names 69 +enum _distributed_message_coop_object_transforms 72 +enum _distributed_message_coop_presentation 66 +enum _distributed_message_coop_screen_effect 76 +enum _distributed_message_coop_skip_vote 70 +enum _distributed_message_coop_sounds_retired 67 +enum _distributed_message_damage_animations 75 +enum _distributed_message_damage_events 10 +enum _distributed_message_game_state 7 +enum _distributed_message_hit_reports 11 +enum _distributed_message_inventories 4 +enum _distributed_message_map_share_offer 84 +enum _distributed_message_map_share_progress 86 +enum _distributed_message_map_share_request 83 +enum _distributed_message_map_share_sources 85 +enum _distributed_message_notice 17 +enum _distributed_message_object_changes 5 +enum _distributed_message_object_states 6 +enum _distributed_message_objects_synchronized 8 +enum _distributed_message_pickups 13 +enum _distributed_message_pings 19 +enum _distributed_message_player_inputs 14 +enum _distributed_message_player_prediction 1 +enum _distributed_message_player_statistics 3 +enum _distributed_message_relayed_actions 15 +enum _distributed_message_shield_effects 91 +enum _distributed_message_structure_bsp 65 +enum _distributed_message_unit_states 2 +enum _distributed_message_vehicle_prediction 12 +enum _distributed_message_voice_config 82 +enum _distributed_message_voice_down 81 +enum _distributed_message_voice_up 80 +enum _distributed_message_votekick 78 +enum _distributed_message_votekick_status 79 +enum _distributed_object_at_rest_bit 1 +enum _distributed_object_carried_bit 0 +enum _distributed_object_dead_bit 2 +enum _distributed_object_light_on_bit 5 +enum _distributed_object_light_sent_bit 4 +enum _distributed_object_predicted_bit 3 +enum _distributed_send_action_bit 1 +enum _distributed_send_sees_bit 2 +enum _distributed_send_state_bit 0 +enum _distributed_to_clients 0 +enum _distributed_to_clients_reliably 1 +enum _distributed_to_host 2 +enum _distributed_to_host_reliably 3 +enum _distributed_unit_alive_bit 0 +enum _distributed_unit_camouflaged_bit 0 +enum _distributed_unit_friendly_fire_bit 2 +enum _distributed_unit_killed_by_vehicle_bit 3 +enum _distributed_unit_part_camouflage_bit 4 +enum _distributed_unit_part_damage_bit 2 +enum _distributed_unit_part_killer_bit 5 +enum _distributed_unit_part_powerups_bit 3 +enum _distributed_unit_part_riding_bit 0 +enum _distributed_unit_part_up_bit 1 +enum _distributed_unit_placed_bit 1 +enum _distributed_unit_predicted_bit 7 +enum _distributed_unit_shield_charging_bit 5 +enum _distributed_unit_shield_depleted_bit 4 +enum _distributed_unit_shield_over_charging_bit 6 +enum _distributed_unit_super_camouflaged_bit 1 +enum _message_client_add_player_request_ingame 26 +enum _message_client_add_player_request_pregame 13 +enum _message_client_broadcast_game_search 0 +enum _message_client_game_start_request 17 +enum _message_client_game_update 25 +enum _message_client_graceful_game_exit_postgame 34 +enum _message_client_graceful_game_exit_pregame 18 +enum _message_client_host_crashed_cry_for_help 28 +enum _message_client_join_game_request 12 +enum _message_client_join_new_host 29 +enum _message_client_loaded 24 +enum _message_client_map_is_precached_pregame 19 +enum _message_client_ping 1 +enum _message_client_player_settings_request 16 +enum _message_client_remove_player_request_ingame 27 +enum _message_client_remove_player_request_postgame 32 +enum _message_client_remove_player_request_pregame 14 +enum _message_client_settings_request 15 +enum _message_client_switch_to_pregame 33 +enum _message_server_add_player_ingame 21 +enum _message_server_begin_game 8 +enum _message_server_game_advertise 2 +enum _message_server_game_over 23 +enum _message_server_game_settings_update 6 +enum _message_server_game_update 20 +enum _message_server_graceful_game_exit_postgame 31 +enum _message_server_graceful_game_exit_pregame 9 +enum _message_server_machine_accepted 4 +enum _message_server_machine_rejected 5 +enum _message_server_pong 3 +enum _message_server_postgame_keep_alive 11 +enum _message_server_pregame_countdown 7 +enum _message_server_pregame_keep_alive 10 +enum _message_server_remove_player_ingame 22 +enum _message_server_switch_to_pregame 30 +fields client_add_player_request_ingame 06ff007a9b35 +fields client_add_player_request_pregame 06ff007a9b35 +fields client_broadcast_game_search f31a5fac9a46 +fields client_game_start_request 758215ada4e1 +fields client_game_update 1134bf6a029b +fields client_graceful_game_exit_postgame 678699dea271 +fields client_graceful_game_exit_pregame 678699dea271 +fields client_host_crashed_cry_for_help 52eb2291ec03 +fields client_join_game_request 28f7514cbcd9 +fields client_join_new_host 52eb2291ec03 +fields client_loaded 678699dea271 +fields client_map_is_precached_pregame 0073b9d65051 +fields client_ping 0d113e26a89a +fields client_player_settings_request 06ff007a9b35 +fields client_remove_player_request_ingame 06ff007a9b35 +fields client_remove_player_request_postgame 06ff007a9b35 +fields client_remove_player_request_pregame 06ff007a9b35 +fields client_settings_request d6a7048d6284 +fields client_switch_to_pregame 678699dea271 +fields server_add_player_ingame 06ff007a9b35 +fields server_begin_game 87e5d5c7565c +fields server_game_advertise 2d5f42b781a4 +fields server_game_over 678699dea271 +fields server_game_settings_update 4c2744d8b8e8 +fields server_game_update beee6fb1929d +fields server_graceful_game_exit_postgame 678699dea271 +fields server_graceful_game_exit_pregame 678699dea271 +fields server_machine_accepted 0d113e26a89a +fields server_machine_rejected 758215ada4e1 +fields server_pong 678699dea271 +fields server_postgame_keep_alive 758215ada4e1 +fields server_pregame_countdown 758215ada4e1 +fields server_pregame_keep_alive 678699dea271 +fields server_remove_player_ingame 1718d4189972 +fields server_switch_to_pregame 678699dea271 +layout HALO_PORT_NETWORK_GAME_LOCAL_DATA_OFFSET (HALO_PORT_NETWORK_GAME_PLAYERS_END + 0x36) +layout HALO_PORT_NETWORK_GAME_SIZE (HALO_PORT_NETWORK_GAME_PLAYERS_END + 0x3A) +layout HALO_PORT_NETWORK_GAME_VARIANT_OPTIONS_OFFSET (HALO_PORT_NETWORK_GAME_PLAYERS_END + 0xA) +size message_client_add_player_request_ingame 0x20 +size message_client_add_player_request_pregame 0x20 +size message_client_broadcast_game_search 0x0C +size message_client_game_start_request 0x02 +size message_client_game_update 0x88 +size message_client_graceful_game_exit_postgame 0x04 +size message_client_graceful_game_exit_pregame 0x04 +size message_client_host_crashed_cry_for_help 0x10 +size message_client_join_game_request 0x70 +size message_client_join_new_host 0x10 +size message_client_loaded 0x04 +size message_client_map_is_precached_pregame 0x100 +size message_client_ping 0x08 +size message_client_player_settings_request 0x20 +size message_client_remove_player_request_ingame 0x20 +size message_client_remove_player_request_postgame 0x20 +size message_client_remove_player_request_pregame 0x20 +size message_client_settings_request 0x44 +size message_client_switch_to_pregame 0x04 +size message_server_add_player_ingame 0x20 +size message_server_begin_game 0x04 +size message_server_game_advertise 0x114 +size message_server_game_over 0x04 +size message_server_game_settings_update 8 + HALO_PORT_NETWORK_GAME_SETTINGS_FRAGMENT_SIZE +size message_server_game_update 0x10 + HALO_PORT_MAXIMUM_NETWORK_PLAYERS * 0x20 +size message_server_graceful_game_exit_postgame 0x04 +size message_server_graceful_game_exit_pregame 0x04 +size message_server_machine_accepted 0x08 +size message_server_machine_rejected 0x02 +size message_server_pong 0x04 +size message_server_postgame_keep_alive 0x02 +size message_server_pregame_countdown 0x02 +size message_server_pregame_keep_alive 0x04 +size message_server_remove_player_ingame 0x24 +size message_server_switch_to_pregame 0x04 +struct distributed_actor_damage 96a57e13e2b8 +struct distributed_actor_damage_message f985e899a708 +struct distributed_actor_state 8bd5e771659d +struct distributed_actor_state_message 51a56e04a536 +struct distributed_chat_config dfa4e32efe1e +struct distributed_chat_line cdab1468ffe0 +struct distributed_client_identity 4d9e62025616 +struct distributed_coop_device_group 4aa3499be2cc +struct distributed_coop_device_groups_message b96ad0030ccc +struct distributed_coop_device_state 727444a5c79b +struct distributed_coop_device_states_message 48f17c3da6f5 +struct distributed_coop_event 62bbd76ba4af +struct distributed_coop_events_message 562bdd70bfae +struct distributed_coop_object_look 77cbae00e4ad +struct distributed_coop_object_looks_message 51dbb474aa17 +struct distributed_coop_object_names f3ecad927448 +struct distributed_coop_object_names_message 7d743ad3710e +struct distributed_coop_object_transform 055897bbff8f +struct distributed_coop_object_transforms_message de95468f7f6d +struct distributed_coop_presentation f34649b3fc6d +struct distributed_coop_presentation_message eb4c7a895272 +struct distributed_coop_screen_effect_message a0a226e0858e +struct distributed_coop_skip_vote c37a12a02932 +struct distributed_coop_skip_vote_message d21260f32711 +struct distributed_damage d2bdb398fb2b +struct distributed_damage_animation ae158e21c915 +struct distributed_damage_animations_message 863e25ca3614 +struct distributed_damage_event 659e4d49733b +struct distributed_damage_event_message c954363dcf26 +struct distributed_hit_report 9a44ca43a88b +struct distributed_hit_report_message 37279f2addca +struct distributed_infection_player d8b98eecf26b +struct distributed_infection_state 8a01c46945ad +struct distributed_inventory 05a279a76ba5 +struct distributed_inventory_message 11825a84dc29 +struct distributed_map_share_offer 4bea857123c2 +struct distributed_map_share_offer_file 204a3b73d193 +struct distributed_map_share_progress 2c3831013302 +struct distributed_map_share_request 3cdcbc8c3a49 +struct distributed_map_share_source 940f8a4c9849 +struct distributed_message_header 0e026a4933a1 +struct distributed_object_change 343e570cfa1d +struct distributed_object_change_message 4c3679cd4dae +struct distributed_object_state 1b656bbda892 +struct distributed_object_state_message 004c4b7aa530 +struct distributed_pickup 46e6f981ac40 +struct distributed_pings_message 35c6009dee29 +struct distributed_player_input a0cf65a1197c +struct distributed_player_ping 377e0e3045f4 +struct distributed_player_statistics 2a44afb8f96c +struct distributed_statistics_message 79134e6e9811 +struct distributed_structure_bsp 53f7d5067cc9 +struct distributed_structure_bsp_message 096278a05681 +struct distributed_vector e80d7f9fc970 +struct distributed_voice_config 665bdc14478b +struct distributed_voice_down e3751d692f16 +struct distributed_voice_up 3d74ee44e4cb +struct distributed_votekick_request d5f913f22d81 +struct distributed_votekick_status 966041386843 +struct game_variant_options 04868b5f4064 diff --git a/tools/fixtures/opence_network_38.txt b/tools/fixtures/opence_network_38.txt new file mode 100644 index 0000000000..a024528506 --- /dev/null +++ b/tools/fixtures/opence_network_38.txt @@ -0,0 +1,294 @@ +version 38 +bound CHAT_TEXT_SIZE 64 +bound DISCORD_ID_SIZE 24 +bound DISCORD_NAME_SIZE 40 +bound DISTRIBUTED_INPUT_HISTORY 4 +bound DISTRIBUTED_RELAYED_ACTION_MAXIMUM_SIZE 14 + 2 * (DISTRIBUTED_INPUT_HISTORY - 1) +bound DISTRIBUTED_RELAYED_ACTION_MINIMUM_SIZE 14 +bound DISTRIBUTED_UNIT_STATE_MAXIMUM_SIZE 3 + 4 + (4 + 2) + (12 + 3 * 6) + 2 + 2 * 2 + 4 * 2 + 2 * NUMBER_OF_PLAYER_POWERUPS + 2 + 1 +bound DISTRIBUTED_UNIT_STATE_MINIMUM_SIZE 3 +bound GAME_ALLEGIANCE_BITVECTOR_LONGS 4 +bound HALO_PORT_MAXIMUM_NETWORK_PLAYERS 128 +bound LEVEL_NAME_BYTES 64 +bound MAP_SHARE_HASH_BYTES 32 +bound MAXIMUM_DEVICE_GROUPS 1024 +bound MAXIMUM_DEVICE_STATES_PER_MESSAGE 64 +bound MAXIMUM_ENTRIES_PER_MESSAGE 64 +bound MAXIMUM_OBJECT_LOOKS_PER_MESSAGE 64 +bound MAXIMUM_OBJECT_NAMES_PER_SCENARIO 0x200 +bound MAXIMUM_OBJECT_TRANSFORMS_PER_MESSAGE 64 +bound MAXIMUM_PINGS_PER_MESSAGE 128 +bound MAXIMUM_QUEUED_DAMAGE_ANIMATIONS 32 +bound MAXIMUM_QUEUED_EVENTS 128 +bound MAXIMUM_REGIONS_PER_OBJECT 8 +bound MAXIMUM_STATISTICS_PER_MESSAGE 64 +bound MAXIMUM_WEAPONS_PER_UNIT 4 +bound NUMBER_OF_ANGLES enum f0ce7d0319b6 +bound NUMBER_OF_OBJECT_CHANGE_COLORS enum b00724872e2d +bound NUMBER_OF_PLAYER_POWERUPS enum 43075f42087c +bound NUMBER_OF_UNIT_GRENADE_TYPES enum a0462dbcbdd9 +bound OBJECT_NAME_BYTES MAXIMUM_OBJECT_NAMES_PER_SCENARIO / 8 +bound P2P_PLAYER_KEY_HASH_SIZE 16 +define DISTRIBUTED_ANGULAR_VELOCITY_SCALE 4096.0f +define DISTRIBUTED_TIME_WINDOW_TICKS (15 * TICKS_PER_SECOND) +define DISTRIBUTED_UNIT_SCALE 32767.0f +define DISTRIBUTED_VELOCITY_SCALE 1024.0f +enum _distributed_actor_camouflaged_bit 4 +enum _distributed_actor_impulse_aligned_bit 6 +enum _distributed_actor_rides_bit 0 +enum _distributed_actor_running_blindly_bit 7 +enum _distributed_actor_shield_charging_bit 2 +enum _distributed_actor_shield_depleted_bit 1 +enum _distributed_actor_shield_over_charging_bit 3 +enum _distributed_actor_super_camouflaged_bit 5 +enum _distributed_infection_active 2 +enum _distributed_infection_countdown 1 +enum _distributed_infection_finished 3 +enum _distributed_infection_role_human 1 +enum _distributed_infection_role_none 0 +enum _distributed_infection_role_zombie 2 +enum _distributed_infection_waiting 0 +enum _distributed_message_actor_damage 73 +enum _distributed_message_actor_states 64 +enum _distributed_message_aim_assist_policy 90 +enum _distributed_message_batch 16 +enum _distributed_message_chat_config 89 +enum _distributed_message_chat_down 88 +enum _distributed_message_chat_up 87 +enum _distributed_message_client_identity 18 +enum _distributed_message_client_ready 9 +enum _distributed_message_coop_device_groups 68 +enum _distributed_message_coop_device_states 77 +enum _distributed_message_coop_events 71 +enum _distributed_message_coop_object_looks 74 +enum _distributed_message_coop_object_names 69 +enum _distributed_message_coop_object_transforms 72 +enum _distributed_message_coop_presentation 66 +enum _distributed_message_coop_screen_effect 76 +enum _distributed_message_coop_skip_vote 70 +enum _distributed_message_coop_sounds_retired 67 +enum _distributed_message_damage_animations 75 +enum _distributed_message_damage_events 10 +enum _distributed_message_game_state 7 +enum _distributed_message_hit_reports 11 +enum _distributed_message_inventories 4 +enum _distributed_message_map_share_offer 84 +enum _distributed_message_map_share_progress 86 +enum _distributed_message_map_share_request 83 +enum _distributed_message_map_share_sources 85 +enum _distributed_message_notice 17 +enum _distributed_message_object_changes 5 +enum _distributed_message_object_states 6 +enum _distributed_message_objects_synchronized 8 +enum _distributed_message_pickups 13 +enum _distributed_message_pings 19 +enum _distributed_message_player_inputs 14 +enum _distributed_message_player_prediction 1 +enum _distributed_message_player_statistics 3 +enum _distributed_message_relayed_actions 15 +enum _distributed_message_shield_effects 91 +enum _distributed_message_structure_bsp 65 +enum _distributed_message_unit_states 2 +enum _distributed_message_vehicle_prediction 12 +enum _distributed_message_voice_config 82 +enum _distributed_message_voice_down 81 +enum _distributed_message_voice_up 80 +enum _distributed_message_votekick 78 +enum _distributed_message_votekick_status 79 +enum _distributed_object_at_rest_bit 1 +enum _distributed_object_carried_bit 0 +enum _distributed_object_dead_bit 2 +enum _distributed_object_light_on_bit 5 +enum _distributed_object_light_sent_bit 4 +enum _distributed_object_predicted_bit 3 +enum _distributed_send_action_bit 1 +enum _distributed_send_sees_bit 2 +enum _distributed_send_state_bit 0 +enum _distributed_to_clients 0 +enum _distributed_to_clients_reliably 1 +enum _distributed_to_host 2 +enum _distributed_to_host_reliably 3 +enum _distributed_unit_alive_bit 0 +enum _distributed_unit_camouflaged_bit 0 +enum _distributed_unit_friendly_fire_bit 2 +enum _distributed_unit_killed_by_vehicle_bit 3 +enum _distributed_unit_part_camouflage_bit 4 +enum _distributed_unit_part_damage_bit 2 +enum _distributed_unit_part_killer_bit 5 +enum _distributed_unit_part_powerups_bit 3 +enum _distributed_unit_part_riding_bit 0 +enum _distributed_unit_part_up_bit 1 +enum _distributed_unit_placed_bit 1 +enum _distributed_unit_predicted_bit 7 +enum _distributed_unit_shield_charging_bit 5 +enum _distributed_unit_shield_depleted_bit 4 +enum _distributed_unit_shield_over_charging_bit 6 +enum _distributed_unit_super_camouflaged_bit 1 +enum _message_client_add_player_request_ingame 26 +enum _message_client_add_player_request_pregame 13 +enum _message_client_broadcast_game_search 0 +enum _message_client_game_start_request 17 +enum _message_client_game_update 25 +enum _message_client_graceful_game_exit_postgame 34 +enum _message_client_graceful_game_exit_pregame 18 +enum _message_client_host_crashed_cry_for_help 28 +enum _message_client_join_game_request 12 +enum _message_client_join_new_host 29 +enum _message_client_loaded 24 +enum _message_client_map_is_precached_pregame 19 +enum _message_client_ping 1 +enum _message_client_player_settings_request 16 +enum _message_client_remove_player_request_ingame 27 +enum _message_client_remove_player_request_postgame 32 +enum _message_client_remove_player_request_pregame 14 +enum _message_client_settings_request 15 +enum _message_client_switch_to_pregame 33 +enum _message_server_add_player_ingame 21 +enum _message_server_begin_game 8 +enum _message_server_game_advertise 2 +enum _message_server_game_over 23 +enum _message_server_game_settings_update 6 +enum _message_server_game_update 20 +enum _message_server_graceful_game_exit_postgame 31 +enum _message_server_graceful_game_exit_pregame 9 +enum _message_server_machine_accepted 4 +enum _message_server_machine_rejected 5 +enum _message_server_pong 3 +enum _message_server_postgame_keep_alive 11 +enum _message_server_pregame_countdown 7 +enum _message_server_pregame_keep_alive 10 +enum _message_server_remove_player_ingame 22 +enum _message_server_switch_to_pregame 30 +fields client_add_player_request_ingame 06ff007a9b35 +fields client_add_player_request_pregame 06ff007a9b35 +fields client_broadcast_game_search f31a5fac9a46 +fields client_game_start_request 758215ada4e1 +fields client_game_update 1134bf6a029b +fields client_graceful_game_exit_postgame 678699dea271 +fields client_graceful_game_exit_pregame 678699dea271 +fields client_host_crashed_cry_for_help 52eb2291ec03 +fields client_join_game_request 28f7514cbcd9 +fields client_join_new_host 52eb2291ec03 +fields client_loaded 678699dea271 +fields client_map_is_precached_pregame 0073b9d65051 +fields client_ping 0d113e26a89a +fields client_player_settings_request 06ff007a9b35 +fields client_remove_player_request_ingame 06ff007a9b35 +fields client_remove_player_request_postgame 06ff007a9b35 +fields client_remove_player_request_pregame 06ff007a9b35 +fields client_settings_request d6a7048d6284 +fields client_switch_to_pregame 678699dea271 +fields server_add_player_ingame 06ff007a9b35 +fields server_begin_game 87e5d5c7565c +fields server_game_advertise 2d5f42b781a4 +fields server_game_over 678699dea271 +fields server_game_settings_update 4c2744d8b8e8 +fields server_game_update beee6fb1929d +fields server_graceful_game_exit_postgame 678699dea271 +fields server_graceful_game_exit_pregame 678699dea271 +fields server_machine_accepted 0d113e26a89a +fields server_machine_rejected 758215ada4e1 +fields server_pong 678699dea271 +fields server_postgame_keep_alive 758215ada4e1 +fields server_pregame_countdown 758215ada4e1 +fields server_pregame_keep_alive 678699dea271 +fields server_remove_player_ingame 1718d4189972 +fields server_switch_to_pregame 678699dea271 +layout HALO_PORT_NETWORK_GAME_LOCAL_DATA_OFFSET (HALO_PORT_NETWORK_GAME_PLAYERS_END + 0x36) +layout HALO_PORT_NETWORK_GAME_SIZE (HALO_PORT_NETWORK_GAME_PLAYERS_END + 0x3A) +layout HALO_PORT_NETWORK_GAME_VARIANT_OPTIONS_OFFSET (HALO_PORT_NETWORK_GAME_PLAYERS_END + 0xA) +size message_client_add_player_request_ingame 0x20 +size message_client_add_player_request_pregame 0x20 +size message_client_broadcast_game_search 0x0C +size message_client_game_start_request 0x02 +size message_client_game_update 0x88 +size message_client_graceful_game_exit_postgame 0x04 +size message_client_graceful_game_exit_pregame 0x04 +size message_client_host_crashed_cry_for_help 0x10 +size message_client_join_game_request 0x70 +size message_client_join_new_host 0x10 +size message_client_loaded 0x04 +size message_client_map_is_precached_pregame 0x100 +size message_client_ping 0x08 +size message_client_player_settings_request 0x20 +size message_client_remove_player_request_ingame 0x20 +size message_client_remove_player_request_postgame 0x20 +size message_client_remove_player_request_pregame 0x20 +size message_client_settings_request 0x44 +size message_client_switch_to_pregame 0x04 +size message_server_add_player_ingame 0x20 +size message_server_begin_game 0x04 +size message_server_game_advertise 0x114 +size message_server_game_over 0x04 +size message_server_game_settings_update 8 + HALO_PORT_NETWORK_GAME_SETTINGS_FRAGMENT_SIZE +size message_server_game_update 0x10 + HALO_PORT_MAXIMUM_NETWORK_PLAYERS * 0x20 +size message_server_graceful_game_exit_postgame 0x04 +size message_server_graceful_game_exit_pregame 0x04 +size message_server_machine_accepted 0x08 +size message_server_machine_rejected 0x02 +size message_server_pong 0x04 +size message_server_postgame_keep_alive 0x02 +size message_server_pregame_countdown 0x02 +size message_server_pregame_keep_alive 0x04 +size message_server_remove_player_ingame 0x24 +size message_server_switch_to_pregame 0x04 +struct distributed_actor_damage 96a57e13e2b8 +struct distributed_actor_damage_message f985e899a708 +struct distributed_actor_state 8bd5e771659d +struct distributed_actor_state_message 51a56e04a536 +struct distributed_chat_config dfa4e32efe1e +struct distributed_chat_line cdab1468ffe0 +struct distributed_client_identity 4d9e62025616 +struct distributed_coop_device_group 4aa3499be2cc +struct distributed_coop_device_groups_message b96ad0030ccc +struct distributed_coop_device_state 727444a5c79b +struct distributed_coop_device_states_message 48f17c3da6f5 +struct distributed_coop_event 62bbd76ba4af +struct distributed_coop_events_message 562bdd70bfae +struct distributed_coop_object_look 77cbae00e4ad +struct distributed_coop_object_looks_message 51dbb474aa17 +struct distributed_coop_object_names f3ecad927448 +struct distributed_coop_object_names_message 7d743ad3710e +struct distributed_coop_object_transform 055897bbff8f +struct distributed_coop_object_transforms_message de95468f7f6d +struct distributed_coop_presentation f34649b3fc6d +struct distributed_coop_presentation_message eb4c7a895272 +struct distributed_coop_screen_effect_message a0a226e0858e +struct distributed_coop_skip_vote c37a12a02932 +struct distributed_coop_skip_vote_message d21260f32711 +struct distributed_damage d2bdb398fb2b +struct distributed_damage_animation ae158e21c915 +struct distributed_damage_animations_message 863e25ca3614 +struct distributed_damage_event 659e4d49733b +struct distributed_damage_event_message c954363dcf26 +struct distributed_hit_report 9a44ca43a88b +struct distributed_hit_report_message 37279f2addca +struct distributed_infection_player d8b98eecf26b +struct distributed_infection_state 8a01c46945ad +struct distributed_inventory 05a279a76ba5 +struct distributed_inventory_message 11825a84dc29 +struct distributed_map_share_offer 4bea857123c2 +struct distributed_map_share_offer_file 204a3b73d193 +struct distributed_map_share_progress 2c3831013302 +struct distributed_map_share_request 3cdcbc8c3a49 +struct distributed_map_share_source 940f8a4c9849 +struct distributed_message_header 0e026a4933a1 +struct distributed_object_change 343e570cfa1d +struct distributed_object_change_message 4c3679cd4dae +struct distributed_object_state 1b656bbda892 +struct distributed_object_state_message 004c4b7aa530 +struct distributed_pickup 46e6f981ac40 +struct distributed_pings_message 35c6009dee29 +struct distributed_player_input a0cf65a1197c +struct distributed_player_ping 377e0e3045f4 +struct distributed_player_statistics 2a44afb8f96c +struct distributed_statistics_message 79134e6e9811 +struct distributed_structure_bsp 53f7d5067cc9 +struct distributed_structure_bsp_message 096278a05681 +struct distributed_vector e80d7f9fc970 +struct distributed_voice_config 665bdc14478b +struct distributed_voice_down e3751d692f16 +struct distributed_voice_up 3d74ee44e4cb +struct distributed_votekick_request d5f913f22d81 +struct distributed_votekick_status 966041386843 +struct game_variant_options 04868b5f4064 diff --git a/tools/fixtures/opence_network_39.txt b/tools/fixtures/opence_network_39.txt new file mode 100644 index 0000000000..c975f7d33a --- /dev/null +++ b/tools/fixtures/opence_network_39.txt @@ -0,0 +1,305 @@ +version 39 +bound CHAT_TEXT_SIZE 64 +bound DISCORD_ID_SIZE 24 +bound DISCORD_NAME_SIZE 40 +bound DISTRIBUTED_CLIENT_BUILD_FLAVOR_SIZE 16 +bound DISTRIBUTED_CLIENT_BUILD_MODS_SIZE 512 +bound DISTRIBUTED_CLIENT_BUILD_NUMBER_SIZE 12 +bound DISTRIBUTED_CLIENT_BUILD_REPOSITORY_SIZE 144 +bound DISTRIBUTED_CLIENT_BUILD_VERSION_SIZE 64 +bound DISTRIBUTED_INPUT_HISTORY 4 +bound DISTRIBUTED_RELAYED_ACTION_MAXIMUM_SIZE 14 + 2 * (DISTRIBUTED_INPUT_HISTORY - 1) +bound DISTRIBUTED_RELAYED_ACTION_MINIMUM_SIZE 14 +bound DISTRIBUTED_UNIT_STATE_MAXIMUM_SIZE 3 + 4 + (4 + 2) + (12 + 3 * 6) + 2 + 2 * 2 + 4 * 2 + 2 * NUMBER_OF_PLAYER_POWERUPS + 2 + 1 +bound DISTRIBUTED_UNIT_STATE_MINIMUM_SIZE 3 +bound GAME_ALLEGIANCE_BITVECTOR_LONGS 4 +bound HALO_PORT_MAXIMUM_NETWORK_PLAYERS 128 +bound LEVEL_NAME_BYTES 64 +bound MAP_SHARE_HASH_BYTES 32 +bound MAXIMUM_DEVICE_GROUPS 1024 +bound MAXIMUM_DEVICE_STATES_PER_MESSAGE 64 +bound MAXIMUM_ENTRIES_PER_MESSAGE 64 +bound MAXIMUM_LOCAL_PLAYERS 4 +bound MAXIMUM_OBJECT_LOOKS_PER_MESSAGE 64 +bound MAXIMUM_OBJECT_NAMES_PER_SCENARIO 0x200 +bound MAXIMUM_OBJECT_TRANSFORMS_PER_MESSAGE 64 +bound MAXIMUM_PINGS_PER_MESSAGE 128 +bound MAXIMUM_QUEUED_DAMAGE_ANIMATIONS 32 +bound MAXIMUM_QUEUED_EVENTS 128 +bound MAXIMUM_REGIONS_PER_OBJECT 8 +bound MAXIMUM_STATISTICS_PER_MESSAGE 64 +bound MAXIMUM_WEAPONS_PER_UNIT 4 +bound NUMBER_OF_ANGLES enum f0ce7d0319b6 +bound NUMBER_OF_OBJECT_CHANGE_COLORS enum b00724872e2d +bound NUMBER_OF_PLAYER_POWERUPS enum 43075f42087c +bound NUMBER_OF_UNIT_GRENADE_TYPES enum a0462dbcbdd9 +bound OBJECT_NAME_BYTES MAXIMUM_OBJECT_NAMES_PER_SCENARIO / 8 +bound P2P_PLAYER_KEY_HASH_SIZE 16 +define DISTRIBUTED_ANGULAR_VELOCITY_SCALE 4096.0f +define DISTRIBUTED_TIME_WINDOW_TICKS (15 * TICKS_PER_SECOND) +define DISTRIBUTED_UNIT_SCALE 32767.0f +define DISTRIBUTED_VELOCITY_SCALE 1024.0f +enum _distributed_actor_camouflaged_bit 4 +enum _distributed_actor_impulse_aligned_bit 6 +enum _distributed_actor_rides_bit 0 +enum _distributed_actor_running_blindly_bit 7 +enum _distributed_actor_shield_charging_bit 2 +enum _distributed_actor_shield_depleted_bit 1 +enum _distributed_actor_shield_over_charging_bit 3 +enum _distributed_actor_super_camouflaged_bit 5 +enum _distributed_infection_active 2 +enum _distributed_infection_countdown 1 +enum _distributed_infection_finished 3 +enum _distributed_infection_role_human 1 +enum _distributed_infection_role_none 0 +enum _distributed_infection_role_zombie 2 +enum _distributed_infection_waiting 0 +enum _distributed_message_actor_damage 73 +enum _distributed_message_actor_states 64 +enum _distributed_message_aim_assist_policy 90 +enum _distributed_message_batch 16 +enum _distributed_message_chat_config 89 +enum _distributed_message_chat_down 88 +enum _distributed_message_chat_up 87 +enum _distributed_message_client_build 92 +enum _distributed_message_client_identity 18 +enum _distributed_message_client_ready 9 +enum _distributed_message_coop_device_groups 68 +enum _distributed_message_coop_device_states 77 +enum _distributed_message_coop_events 71 +enum _distributed_message_coop_object_looks 74 +enum _distributed_message_coop_object_names 69 +enum _distributed_message_coop_object_transforms 72 +enum _distributed_message_coop_presentation 66 +enum _distributed_message_coop_screen_effect 76 +enum _distributed_message_coop_skip_vote 70 +enum _distributed_message_coop_sounds_retired 67 +enum _distributed_message_damage_animations 75 +enum _distributed_message_damage_events 10 +enum _distributed_message_fire_origins 93 +enum _distributed_message_game_state 7 +enum _distributed_message_hit_reports 11 +enum _distributed_message_inventories 4 +enum _distributed_message_map_share_offer 84 +enum _distributed_message_map_share_progress 86 +enum _distributed_message_map_share_request 83 +enum _distributed_message_map_share_sources 85 +enum _distributed_message_notice 17 +enum _distributed_message_object_changes 5 +enum _distributed_message_object_states 6 +enum _distributed_message_objects_synchronized 8 +enum _distributed_message_pickups 13 +enum _distributed_message_pings 19 +enum _distributed_message_player_inputs 14 +enum _distributed_message_player_prediction 1 +enum _distributed_message_player_statistics 3 +enum _distributed_message_relayed_actions 15 +enum _distributed_message_shield_effects 91 +enum _distributed_message_structure_bsp 65 +enum _distributed_message_unit_states 2 +enum _distributed_message_vehicle_prediction 12 +enum _distributed_message_voice_config 82 +enum _distributed_message_voice_down 81 +enum _distributed_message_voice_up 80 +enum _distributed_message_votekick 78 +enum _distributed_message_votekick_status 79 +enum _distributed_object_at_rest_bit 1 +enum _distributed_object_carried_bit 0 +enum _distributed_object_dead_bit 2 +enum _distributed_object_light_on_bit 5 +enum _distributed_object_light_sent_bit 4 +enum _distributed_object_predicted_bit 3 +enum _distributed_send_action_bit 1 +enum _distributed_send_sees_bit 2 +enum _distributed_send_state_bit 0 +enum _distributed_to_clients 0 +enum _distributed_to_clients_reliably 1 +enum _distributed_to_host 2 +enum _distributed_to_host_reliably 3 +enum _distributed_unit_alive_bit 0 +enum _distributed_unit_camouflaged_bit 0 +enum _distributed_unit_friendly_fire_bit 2 +enum _distributed_unit_killed_by_vehicle_bit 3 +enum _distributed_unit_part_camouflage_bit 4 +enum _distributed_unit_part_damage_bit 2 +enum _distributed_unit_part_killer_bit 5 +enum _distributed_unit_part_powerups_bit 3 +enum _distributed_unit_part_riding_bit 0 +enum _distributed_unit_part_up_bit 1 +enum _distributed_unit_placed_bit 1 +enum _distributed_unit_predicted_bit 7 +enum _distributed_unit_shield_charging_bit 5 +enum _distributed_unit_shield_depleted_bit 4 +enum _distributed_unit_shield_over_charging_bit 6 +enum _distributed_unit_super_camouflaged_bit 1 +enum _message_client_add_player_request_ingame 26 +enum _message_client_add_player_request_pregame 13 +enum _message_client_broadcast_game_search 0 +enum _message_client_game_start_request 17 +enum _message_client_game_update 25 +enum _message_client_graceful_game_exit_postgame 34 +enum _message_client_graceful_game_exit_pregame 18 +enum _message_client_host_crashed_cry_for_help 28 +enum _message_client_join_game_request 12 +enum _message_client_join_new_host 29 +enum _message_client_loaded 24 +enum _message_client_map_is_precached_pregame 19 +enum _message_client_ping 1 +enum _message_client_player_settings_request 16 +enum _message_client_remove_player_request_ingame 27 +enum _message_client_remove_player_request_postgame 32 +enum _message_client_remove_player_request_pregame 14 +enum _message_client_settings_request 15 +enum _message_client_switch_to_pregame 33 +enum _message_server_add_player_ingame 21 +enum _message_server_begin_game 8 +enum _message_server_game_advertise 2 +enum _message_server_game_over 23 +enum _message_server_game_settings_update 6 +enum _message_server_game_update 20 +enum _message_server_graceful_game_exit_postgame 31 +enum _message_server_graceful_game_exit_pregame 9 +enum _message_server_machine_accepted 4 +enum _message_server_machine_rejected 5 +enum _message_server_pong 3 +enum _message_server_postgame_keep_alive 11 +enum _message_server_pregame_countdown 7 +enum _message_server_pregame_keep_alive 10 +enum _message_server_remove_player_ingame 22 +enum _message_server_switch_to_pregame 30 +fields client_add_player_request_ingame 06ff007a9b35 +fields client_add_player_request_pregame 06ff007a9b35 +fields client_broadcast_game_search f31a5fac9a46 +fields client_game_start_request 758215ada4e1 +fields client_game_update 1134bf6a029b +fields client_graceful_game_exit_postgame 678699dea271 +fields client_graceful_game_exit_pregame 678699dea271 +fields client_host_crashed_cry_for_help 52eb2291ec03 +fields client_join_game_request 28f7514cbcd9 +fields client_join_new_host 52eb2291ec03 +fields client_loaded 678699dea271 +fields client_map_is_precached_pregame 0073b9d65051 +fields client_ping 0d113e26a89a +fields client_player_settings_request 06ff007a9b35 +fields client_remove_player_request_ingame 06ff007a9b35 +fields client_remove_player_request_postgame 06ff007a9b35 +fields client_remove_player_request_pregame 06ff007a9b35 +fields client_settings_request d6a7048d6284 +fields client_switch_to_pregame 678699dea271 +fields server_add_player_ingame 06ff007a9b35 +fields server_begin_game 87e5d5c7565c +fields server_game_advertise 2d5f42b781a4 +fields server_game_over 678699dea271 +fields server_game_settings_update 4c2744d8b8e8 +fields server_game_update beee6fb1929d +fields server_graceful_game_exit_postgame 678699dea271 +fields server_graceful_game_exit_pregame 678699dea271 +fields server_machine_accepted 0d113e26a89a +fields server_machine_rejected 758215ada4e1 +fields server_pong 678699dea271 +fields server_postgame_keep_alive 758215ada4e1 +fields server_pregame_countdown 758215ada4e1 +fields server_pregame_keep_alive 678699dea271 +fields server_remove_player_ingame 1718d4189972 +fields server_switch_to_pregame 678699dea271 +layout HALO_PORT_NETWORK_GAME_LOCAL_DATA_OFFSET (HALO_PORT_NETWORK_GAME_PLAYERS_END + 0x36) +layout HALO_PORT_NETWORK_GAME_SIZE (HALO_PORT_NETWORK_GAME_PLAYERS_END + 0x3A) +layout HALO_PORT_NETWORK_GAME_VARIANT_OPTIONS_OFFSET (HALO_PORT_NETWORK_GAME_PLAYERS_END + 0xA) +size message_client_add_player_request_ingame 0x20 +size message_client_add_player_request_pregame 0x20 +size message_client_broadcast_game_search 0x0C +size message_client_game_start_request 0x02 +size message_client_game_update 0x88 +size message_client_graceful_game_exit_postgame 0x04 +size message_client_graceful_game_exit_pregame 0x04 +size message_client_host_crashed_cry_for_help 0x10 +size message_client_join_game_request 0x70 +size message_client_join_new_host 0x10 +size message_client_loaded 0x04 +size message_client_map_is_precached_pregame 0x100 +size message_client_ping 0x08 +size message_client_player_settings_request 0x20 +size message_client_remove_player_request_ingame 0x20 +size message_client_remove_player_request_postgame 0x20 +size message_client_remove_player_request_pregame 0x20 +size message_client_settings_request 0x44 +size message_client_switch_to_pregame 0x04 +size message_server_add_player_ingame 0x20 +size message_server_begin_game 0x04 +size message_server_game_advertise 0x114 +size message_server_game_over 0x04 +size message_server_game_settings_update 8 + HALO_PORT_NETWORK_GAME_SETTINGS_FRAGMENT_SIZE +size message_server_game_update 0x10 + HALO_PORT_MAXIMUM_NETWORK_PLAYERS * 0x20 +size message_server_graceful_game_exit_postgame 0x04 +size message_server_graceful_game_exit_pregame 0x04 +size message_server_machine_accepted 0x08 +size message_server_machine_rejected 0x02 +size message_server_pong 0x04 +size message_server_postgame_keep_alive 0x02 +size message_server_pregame_countdown 0x02 +size message_server_pregame_keep_alive 0x04 +size message_server_remove_player_ingame 0x24 +size message_server_switch_to_pregame 0x04 +struct distributed_actor_damage 96a57e13e2b8 +struct distributed_actor_damage_message f985e899a708 +struct distributed_actor_state 8bd5e771659d +struct distributed_actor_state_message 51a56e04a536 +struct distributed_chat_config dfa4e32efe1e +struct distributed_chat_line cdab1468ffe0 +struct distributed_client_build 503e4474b798 +struct distributed_client_identity 4d9e62025616 +struct distributed_coop_device_group 4aa3499be2cc +struct distributed_coop_device_groups_message b96ad0030ccc +struct distributed_coop_device_state 727444a5c79b +struct distributed_coop_device_states_message 48f17c3da6f5 +struct distributed_coop_event 62bbd76ba4af +struct distributed_coop_events_message 562bdd70bfae +struct distributed_coop_object_look 77cbae00e4ad +struct distributed_coop_object_looks_message 51dbb474aa17 +struct distributed_coop_object_names f3ecad927448 +struct distributed_coop_object_names_message 7d743ad3710e +struct distributed_coop_object_transform 055897bbff8f +struct distributed_coop_object_transforms_message de95468f7f6d +struct distributed_coop_presentation f34649b3fc6d +struct distributed_coop_presentation_message eb4c7a895272 +struct distributed_coop_screen_effect_message a0a226e0858e +struct distributed_coop_skip_vote c37a12a02932 +struct distributed_coop_skip_vote_message d21260f32711 +struct distributed_damage d2bdb398fb2b +struct distributed_damage_animation ae158e21c915 +struct distributed_damage_animations_message 863e25ca3614 +struct distributed_damage_event 659e4d49733b +struct distributed_damage_event_message c954363dcf26 +struct distributed_fire_origin 700dfdb20582 +struct distributed_fire_origin_message 7613e8f9d43e +struct distributed_hit_report 9a44ca43a88b +struct distributed_hit_report_message 37279f2addca +struct distributed_infection_player d8b98eecf26b +struct distributed_infection_state 8a01c46945ad +struct distributed_inventory 05a279a76ba5 +struct distributed_inventory_message 11825a84dc29 +struct distributed_map_share_offer 4bea857123c2 +struct distributed_map_share_offer_file 204a3b73d193 +struct distributed_map_share_progress 2c3831013302 +struct distributed_map_share_request 3cdcbc8c3a49 +struct distributed_map_share_source 940f8a4c9849 +struct distributed_message_header 0e026a4933a1 +struct distributed_object_change 343e570cfa1d +struct distributed_object_change_message 4c3679cd4dae +struct distributed_object_state 1b656bbda892 +struct distributed_object_state_message 004c4b7aa530 +struct distributed_pickup 46e6f981ac40 +struct distributed_pings_message 35c6009dee29 +struct distributed_player_input a0cf65a1197c +struct distributed_player_ping 377e0e3045f4 +struct distributed_player_statistics 2a44afb8f96c +struct distributed_statistics_message 79134e6e9811 +struct distributed_structure_bsp 53f7d5067cc9 +struct distributed_structure_bsp_message 096278a05681 +struct distributed_vector e80d7f9fc970 +struct distributed_voice_config 665bdc14478b +struct distributed_voice_down e3751d692f16 +struct distributed_voice_up 3d74ee44e4cb +struct distributed_votekick_request d5f913f22d81 +struct distributed_votekick_status 966041386843 +struct game_variant_options 0e258e4cf85b diff --git a/tools/fixtures/opence_network_41.txt b/tools/fixtures/opence_network_41.txt new file mode 100644 index 0000000000..42e3ff54ed --- /dev/null +++ b/tools/fixtures/opence_network_41.txt @@ -0,0 +1,313 @@ +version 41 +bound CHAT_TEXT_SIZE 64 +bound DISCORD_ID_SIZE 24 +bound DISCORD_NAME_SIZE 40 +bound DISTRIBUTED_CLIENT_BUILD_FLAVOR_SIZE 16 +bound DISTRIBUTED_CLIENT_BUILD_MODS_SIZE 512 +bound DISTRIBUTED_CLIENT_BUILD_NUMBER_SIZE 12 +bound DISTRIBUTED_CLIENT_BUILD_REPOSITORY_SIZE 144 +bound DISTRIBUTED_CLIENT_BUILD_VERSION_SIZE 64 +bound DISTRIBUTED_INPUT_HISTORY 4 +bound DISTRIBUTED_RELAYED_ACTION_MAXIMUM_SIZE 14 + 2 * (DISTRIBUTED_INPUT_HISTORY - 1) +bound DISTRIBUTED_RELAYED_ACTION_MINIMUM_SIZE 14 +bound DISTRIBUTED_UNIT_STATE_MAXIMUM_SIZE 3 + 4 + (4 + 2) + (12 + 3 * 6) + 2 + 2 * 2 + 4 * 2 + 2 * NUMBER_OF_PLAYER_POWERUPS + 2 + 1 +bound DISTRIBUTED_UNIT_STATE_MINIMUM_SIZE 3 +bound GAME_ALLEGIANCE_BITVECTOR_LONGS 4 +bound HALO_PORT_MAXIMUM_NETWORK_PLAYERS 128 +bound LEVEL_NAME_BYTES 64 +bound MAP_SHARE_HASH_BYTES 32 +bound MAXIMUM_DEVICE_GROUPS 1024 +bound MAXIMUM_DEVICE_STATES_PER_MESSAGE 64 +bound MAXIMUM_ENTRIES_PER_MESSAGE 64 +bound MAXIMUM_LOCAL_PLAYERS 4 +bound MAXIMUM_OBJECT_LOOKS_PER_MESSAGE 64 +bound MAXIMUM_OBJECT_NAMES_PER_SCENARIO 0x200 +bound MAXIMUM_OBJECT_TRANSFORMS_PER_MESSAGE 64 +bound MAXIMUM_PINGS_PER_MESSAGE 128 +bound MAXIMUM_QUEUED_DAMAGE_ANIMATIONS 32 +bound MAXIMUM_QUEUED_EVENTS 128 +bound MAXIMUM_REGIONS_PER_OBJECT 8 +bound MAXIMUM_STATISTICS_PER_MESSAGE 64 +bound MAXIMUM_WEAPONS_PER_UNIT 4 +bound NETWORK_MAP_VOTE_GAMETYPE_SIZE 24 +bound NETWORK_MAP_VOTE_MAP_SIZE 32 +bound NETWORK_MAP_VOTE_MAXIMUM_CHOICES 8 +bound NUMBER_OF_ANGLES enum f0ce7d0319b6 +bound NUMBER_OF_OBJECT_CHANGE_COLORS enum b00724872e2d +bound NUMBER_OF_PLAYER_POWERUPS enum 43075f42087c +bound NUMBER_OF_UNIT_GRENADE_TYPES enum a0462dbcbdd9 +bound OBJECT_NAME_BYTES MAXIMUM_OBJECT_NAMES_PER_SCENARIO / 8 +bound P2P_PLAYER_KEY_HASH_SIZE 16 +define DISTRIBUTED_ANGULAR_VELOCITY_SCALE 4096.0f +define DISTRIBUTED_TIME_WINDOW_TICKS (15 * TICKS_PER_SECOND) +define DISTRIBUTED_UNIT_SCALE 32767.0f +define DISTRIBUTED_VELOCITY_SCALE 1024.0f +enum _distributed_actor_camouflaged_bit 4 +enum _distributed_actor_impulse_aligned_bit 6 +enum _distributed_actor_rides_bit 0 +enum _distributed_actor_running_blindly_bit 7 +enum _distributed_actor_shield_charging_bit 2 +enum _distributed_actor_shield_depleted_bit 1 +enum _distributed_actor_shield_over_charging_bit 3 +enum _distributed_actor_super_camouflaged_bit 5 +enum _distributed_infection_active 2 +enum _distributed_infection_countdown 1 +enum _distributed_infection_finished 3 +enum _distributed_infection_role_human 1 +enum _distributed_infection_role_none 0 +enum _distributed_infection_role_zombie 2 +enum _distributed_infection_waiting 0 +enum _distributed_message_actor_damage 73 +enum _distributed_message_actor_states 64 +enum _distributed_message_aim_assist_policy 90 +enum _distributed_message_batch 16 +enum _distributed_message_chat_config 89 +enum _distributed_message_chat_down 88 +enum _distributed_message_chat_up 87 +enum _distributed_message_client_build 92 +enum _distributed_message_client_identity 18 +enum _distributed_message_client_ready 9 +enum _distributed_message_coop_device_groups 68 +enum _distributed_message_coop_device_states 77 +enum _distributed_message_coop_events 71 +enum _distributed_message_coop_object_looks 74 +enum _distributed_message_coop_object_names 69 +enum _distributed_message_coop_object_transforms 72 +enum _distributed_message_coop_presentation 66 +enum _distributed_message_coop_screen_effect 76 +enum _distributed_message_coop_skip_vote 70 +enum _distributed_message_coop_sounds_retired 67 +enum _distributed_message_damage_animations 75 +enum _distributed_message_damage_events 10 +enum _distributed_message_fire_origins 93 +enum _distributed_message_game_state 7 +enum _distributed_message_hit_reports 11 +enum _distributed_message_inventories 4 +enum _distributed_message_map_share_offer 84 +enum _distributed_message_map_share_progress 86 +enum _distributed_message_map_share_request 83 +enum _distributed_message_map_share_sources 85 +enum _distributed_message_map_vote 94 +enum _distributed_message_map_vote_choice 95 +enum _distributed_message_notice 17 +enum _distributed_message_object_changes 5 +enum _distributed_message_object_states 6 +enum _distributed_message_objects_synchronized 8 +enum _distributed_message_pickups 13 +enum _distributed_message_pings 19 +enum _distributed_message_player_inputs 14 +enum _distributed_message_player_prediction 1 +enum _distributed_message_player_statistics 3 +enum _distributed_message_relayed_actions 15 +enum _distributed_message_shield_effects 91 +enum _distributed_message_structure_bsp 65 +enum _distributed_message_unit_states 2 +enum _distributed_message_vehicle_prediction 12 +enum _distributed_message_voice_config 82 +enum _distributed_message_voice_down 81 +enum _distributed_message_voice_up 80 +enum _distributed_message_votekick 78 +enum _distributed_message_votekick_status 79 +enum _distributed_object_at_rest_bit 1 +enum _distributed_object_carried_bit 0 +enum _distributed_object_dead_bit 2 +enum _distributed_object_light_on_bit 5 +enum _distributed_object_light_sent_bit 4 +enum _distributed_object_predicted_bit 3 +enum _distributed_send_action_bit 1 +enum _distributed_send_sees_bit 2 +enum _distributed_send_state_bit 0 +enum _distributed_to_clients 0 +enum _distributed_to_clients_reliably 1 +enum _distributed_to_host 2 +enum _distributed_to_host_reliably 3 +enum _distributed_unit_alive_bit 0 +enum _distributed_unit_camouflaged_bit 0 +enum _distributed_unit_friendly_fire_bit 2 +enum _distributed_unit_killed_by_vehicle_bit 3 +enum _distributed_unit_part_camouflage_bit 4 +enum _distributed_unit_part_damage_bit 2 +enum _distributed_unit_part_killer_bit 5 +enum _distributed_unit_part_powerups_bit 3 +enum _distributed_unit_part_riding_bit 0 +enum _distributed_unit_part_up_bit 1 +enum _distributed_unit_placed_bit 1 +enum _distributed_unit_predicted_bit 7 +enum _distributed_unit_shield_charging_bit 5 +enum _distributed_unit_shield_depleted_bit 4 +enum _distributed_unit_shield_over_charging_bit 6 +enum _distributed_unit_super_camouflaged_bit 1 +enum _message_client_add_player_request_ingame 26 +enum _message_client_add_player_request_pregame 13 +enum _message_client_broadcast_game_search 0 +enum _message_client_game_start_request 17 +enum _message_client_game_update 25 +enum _message_client_graceful_game_exit_postgame 34 +enum _message_client_graceful_game_exit_pregame 18 +enum _message_client_host_crashed_cry_for_help 28 +enum _message_client_join_game_request 12 +enum _message_client_join_new_host 29 +enum _message_client_loaded 24 +enum _message_client_map_is_precached_pregame 19 +enum _message_client_ping 1 +enum _message_client_player_settings_request 16 +enum _message_client_remove_player_request_ingame 27 +enum _message_client_remove_player_request_postgame 32 +enum _message_client_remove_player_request_pregame 14 +enum _message_client_settings_request 15 +enum _message_client_switch_to_pregame 33 +enum _message_server_add_player_ingame 21 +enum _message_server_begin_game 8 +enum _message_server_game_advertise 2 +enum _message_server_game_over 23 +enum _message_server_game_settings_update 6 +enum _message_server_game_update 20 +enum _message_server_graceful_game_exit_postgame 31 +enum _message_server_graceful_game_exit_pregame 9 +enum _message_server_machine_accepted 4 +enum _message_server_machine_rejected 5 +enum _message_server_pong 3 +enum _message_server_postgame_keep_alive 11 +enum _message_server_pregame_countdown 7 +enum _message_server_pregame_keep_alive 10 +enum _message_server_remove_player_ingame 22 +enum _message_server_switch_to_pregame 30 +fields client_add_player_request_ingame 06ff007a9b35 +fields client_add_player_request_pregame 06ff007a9b35 +fields client_broadcast_game_search f31a5fac9a46 +fields client_game_start_request 758215ada4e1 +fields client_game_update 1134bf6a029b +fields client_graceful_game_exit_postgame 678699dea271 +fields client_graceful_game_exit_pregame 678699dea271 +fields client_host_crashed_cry_for_help 52eb2291ec03 +fields client_join_game_request 20da8c4f815f +fields client_join_new_host 52eb2291ec03 +fields client_loaded 678699dea271 +fields client_map_is_precached_pregame 0073b9d65051 +fields client_ping 0d113e26a89a +fields client_player_settings_request 06ff007a9b35 +fields client_remove_player_request_ingame 06ff007a9b35 +fields client_remove_player_request_postgame 06ff007a9b35 +fields client_remove_player_request_pregame 06ff007a9b35 +fields client_settings_request d6a7048d6284 +fields client_switch_to_pregame 678699dea271 +fields server_add_player_ingame 06ff007a9b35 +fields server_begin_game 87e5d5c7565c +fields server_game_advertise 2d5f42b781a4 +fields server_game_over 678699dea271 +fields server_game_settings_update 4c2744d8b8e8 +fields server_game_update beee6fb1929d +fields server_graceful_game_exit_postgame 678699dea271 +fields server_graceful_game_exit_pregame 678699dea271 +fields server_machine_accepted 0d113e26a89a +fields server_machine_rejected 758215ada4e1 +fields server_pong 678699dea271 +fields server_postgame_keep_alive 758215ada4e1 +fields server_pregame_countdown 758215ada4e1 +fields server_pregame_keep_alive 678699dea271 +fields server_remove_player_ingame 1718d4189972 +fields server_switch_to_pregame 678699dea271 +layout HALO_PORT_NETWORK_GAME_LOCAL_DATA_OFFSET (HALO_PORT_NETWORK_GAME_PLAYERS_END + 0x36) +layout HALO_PORT_NETWORK_GAME_SIZE (HALO_PORT_NETWORK_GAME_PLAYERS_END + 0x3A) +layout HALO_PORT_NETWORK_GAME_VARIANT_OPTIONS_OFFSET (HALO_PORT_NETWORK_GAME_PLAYERS_END + 0xA) +size message_client_add_player_request_ingame 0x20 +size message_client_add_player_request_pregame 0x20 +size message_client_broadcast_game_search 0x0C +size message_client_game_start_request 0x02 +size message_client_game_update 0x88 +size message_client_graceful_game_exit_postgame 0x04 +size message_client_graceful_game_exit_pregame 0x04 +size message_client_host_crashed_cry_for_help 0x10 +size message_client_join_game_request 0x70 + 170 + 64 +size message_client_join_new_host 0x10 +size message_client_loaded 0x04 +size message_client_map_is_precached_pregame 0x100 +size message_client_ping 0x08 +size message_client_player_settings_request 0x20 +size message_client_remove_player_request_ingame 0x20 +size message_client_remove_player_request_postgame 0x20 +size message_client_remove_player_request_pregame 0x20 +size message_client_settings_request 0x44 +size message_client_switch_to_pregame 0x04 +size message_server_add_player_ingame 0x20 +size message_server_begin_game 0x04 +size message_server_game_advertise 0x114 +size message_server_game_over 0x04 +size message_server_game_settings_update 8 + HALO_PORT_NETWORK_GAME_SETTINGS_FRAGMENT_SIZE +size message_server_game_update 0x10 + HALO_PORT_MAXIMUM_NETWORK_PLAYERS * 0x20 +size message_server_graceful_game_exit_postgame 0x04 +size message_server_graceful_game_exit_pregame 0x04 +size message_server_machine_accepted 0x08 +size message_server_machine_rejected 0x02 +size message_server_pong 0x04 +size message_server_postgame_keep_alive 0x02 +size message_server_pregame_countdown 0x02 +size message_server_pregame_keep_alive 0x04 +size message_server_remove_player_ingame 0x24 +size message_server_switch_to_pregame 0x04 +struct distributed_actor_damage 96a57e13e2b8 +struct distributed_actor_damage_message f985e899a708 +struct distributed_actor_state 8bd5e771659d +struct distributed_actor_state_message 51a56e04a536 +struct distributed_chat_config dfa4e32efe1e +struct distributed_chat_line cdab1468ffe0 +struct distributed_client_build 503e4474b798 +struct distributed_client_identity 4d9e62025616 +struct distributed_coop_device_group 4aa3499be2cc +struct distributed_coop_device_groups_message b96ad0030ccc +struct distributed_coop_device_state 727444a5c79b +struct distributed_coop_device_states_message 48f17c3da6f5 +struct distributed_coop_event 62bbd76ba4af +struct distributed_coop_events_message 562bdd70bfae +struct distributed_coop_object_look 77cbae00e4ad +struct distributed_coop_object_looks_message 51dbb474aa17 +struct distributed_coop_object_names f3ecad927448 +struct distributed_coop_object_names_message 7d743ad3710e +struct distributed_coop_object_transform 055897bbff8f +struct distributed_coop_object_transforms_message de95468f7f6d +struct distributed_coop_presentation f34649b3fc6d +struct distributed_coop_presentation_message eb4c7a895272 +struct distributed_coop_screen_effect_message a0a226e0858e +struct distributed_coop_skip_vote c37a12a02932 +struct distributed_coop_skip_vote_message d21260f32711 +struct distributed_damage d2bdb398fb2b +struct distributed_damage_animation ae158e21c915 +struct distributed_damage_animations_message 863e25ca3614 +struct distributed_damage_event 659e4d49733b +struct distributed_damage_event_message c954363dcf26 +struct distributed_fire_origin 700dfdb20582 +struct distributed_fire_origin_message 7613e8f9d43e +struct distributed_hit_report 9a44ca43a88b +struct distributed_hit_report_message 37279f2addca +struct distributed_infection_player d8b98eecf26b +struct distributed_infection_state 8a01c46945ad +struct distributed_inventory 05a279a76ba5 +struct distributed_inventory_message 11825a84dc29 +struct distributed_map_share_offer 4bea857123c2 +struct distributed_map_share_offer_file 204a3b73d193 +struct distributed_map_share_progress 2c3831013302 +struct distributed_map_share_request 3cdcbc8c3a49 +struct distributed_map_share_source 940f8a4c9849 +struct distributed_map_vote_choice e0aa3fb40224 +struct distributed_map_vote_choice_entry b8e5a595dbad +struct distributed_map_vote_status 524c63fc37e2 +struct distributed_message_header 0e026a4933a1 +struct distributed_object_change 343e570cfa1d +struct distributed_object_change_message 4c3679cd4dae +struct distributed_object_state 1b656bbda892 +struct distributed_object_state_message 004c4b7aa530 +struct distributed_pickup 46e6f981ac40 +struct distributed_pings_message 35c6009dee29 +struct distributed_player_input a0cf65a1197c +struct distributed_player_ping 377e0e3045f4 +struct distributed_player_statistics 2a44afb8f96c +struct distributed_statistics_message 79134e6e9811 +struct distributed_structure_bsp 53f7d5067cc9 +struct distributed_structure_bsp_message 096278a05681 +struct distributed_vector e80d7f9fc970 +struct distributed_voice_config 665bdc14478b +struct distributed_voice_down e3751d692f16 +struct distributed_voice_up 3d74ee44e4cb +struct distributed_votekick_request 7e29ffd54bd1 +struct distributed_votekick_status b94458cdc180 +struct game_variant_options 0e258e4cf85b diff --git a/tools/fixtures/opence_network_43.txt b/tools/fixtures/opence_network_43.txt new file mode 100644 index 0000000000..91ff66b546 --- /dev/null +++ b/tools/fixtures/opence_network_43.txt @@ -0,0 +1,374 @@ +version 43 +bound CHAT_TEXT_SIZE 64 +bound DISCORD_ID_SIZE 24 +bound DISCORD_NAME_SIZE 40 +bound DISTRIBUTED_CLIENT_BUILD_FLAVOR_SIZE 16 +bound DISTRIBUTED_CLIENT_BUILD_MODS_SIZE 512 +bound DISTRIBUTED_CLIENT_BUILD_NUMBER_SIZE 12 +bound DISTRIBUTED_CLIENT_BUILD_REPOSITORY_SIZE 144 +bound DISTRIBUTED_CLIENT_BUILD_VERSION_SIZE 64 +bound DISTRIBUTED_DECK_SIZE 4 + 2 + 12 + 6 + 1 + 1 + 2 +bound DISTRIBUTED_INPUT_HISTORY 4 +bound DISTRIBUTED_RELAYED_ACTION_MAXIMUM_SIZE 14 + 2 * (DISTRIBUTED_INPUT_HISTORY - 1) +bound DISTRIBUTED_RELAYED_ACTION_MINIMUM_SIZE 14 +bound DISTRIBUTED_UNIT_STATE_MAXIMUM_SIZE 3 + 4 + (4 + 2) + (12 + 3 * 6) + DISTRIBUTED_DECK_SIZE + 2 + 2 * 2 + 4 * 2 + 2 * NUMBER_OF_PLAYER_POWERUPS + 2 + 1 + NUMBER_OF_DISTRIBUTED_POSE_VECTORS * 6 +bound DISTRIBUTED_UNIT_STATE_MINIMUM_SIZE 3 +bound GAME_ALLEGIANCE_BITVECTOR_LONGS 4 +bound HALO_PORT_MAXIMUM_NETWORK_PLAYERS 128 +bound LEVEL_NAME_BYTES 64 +bound MAP_SHARE_HASH_BYTES 32 +bound MAXIMUM_DEVICE_GROUPS 1024 +bound MAXIMUM_DEVICE_STATES_PER_MESSAGE 64 +bound MAXIMUM_ENTRIES_PER_MESSAGE 64 +bound MAXIMUM_LOCAL_PLAYERS 4 +bound MAXIMUM_OBJECT_LOOKS_PER_MESSAGE 64 +bound MAXIMUM_OBJECT_NAMES_PER_SCENARIO 0x200 +bound MAXIMUM_OBJECT_TRANSFORMS_PER_MESSAGE 64 +bound MAXIMUM_PINGS_PER_MESSAGE 128 +bound MAXIMUM_QUEUED_DAMAGE_ANIMATIONS 32 +bound MAXIMUM_QUEUED_EVENTS 128 +bound MAXIMUM_REGIONS_PER_OBJECT 8 +bound MAXIMUM_STATISTICS_PER_MESSAGE 64 +bound MAXIMUM_WEAPONS_PER_UNIT 4 +bound NETWORK_MAP_VOTE_GAMETYPE_SIZE 24 +bound NETWORK_MAP_VOTE_MAP_SIZE 32 +bound NETWORK_MAP_VOTE_MAXIMUM_CHOICES 8 +bound NUMBER_OF_ANGLES enum f0ce7d0319b6 +bound NUMBER_OF_DISTRIBUTED_POSE_VECTORS enum 5538f02632fd +bound NUMBER_OF_OBJECT_CHANGE_COLORS enum b00724872e2d +bound NUMBER_OF_PLAYER_POWERUPS enum 43075f42087c +bound NUMBER_OF_UNIT_GRENADE_TYPES enum a0462dbcbdd9 +bound OBJECT_NAME_BYTES MAXIMUM_OBJECT_NAMES_PER_SCENARIO / 8 +bound P2P_PLAYER_KEY_HASH_SIZE 16 +define DISTRIBUTED_ANGULAR_VELOCITY_SCALE 4096.0f +define DISTRIBUTED_TIME_WINDOW_TICKS (15 * TICKS_PER_SECOND) +define DISTRIBUTED_UNIT_SCALE 32767.0f +define DISTRIBUTED_VELOCITY_SCALE 1024.0f +define MCC_ADMISSION_DEADLINE 120000u +define MCC_ADMISSION_GRACE 15000u +define MCC_ADMISSION_HEARD 20000u +define MCC_ADMISSION_MACHINES 128 +define MCC_ADMISSION_PULSE 5000u +define MCC_LOAD_NETWORK_EARN 3u +define MCC_LOAD_NETWORK_HOLD_GAP 1000u +define MCC_LOAD_NETWORK_IDLE 30000u +define MCC_LOAD_NETWORK_LIMIT 240000u +define MCC_LOAD_NETWORK_PULSE 5000u +define MCC_SHARE_CHUNK_BYTES 3072 +define MCC_SHARE_CREDIT_SIZE 64 +define MCC_SHARE_LEAF_SIZE 128 +define MCC_SHARE_LEVEL_SIZE 64 +define MCC_SHARE_MANIFEST_PAGE 16 +define MCC_SHARE_MAXIMUM_CREDITS 4 +define MCC_SHARE_MAXIMUM_CREDIT_BYTES 0x10000u +define MCC_SHARE_MAXIMUM_FILE_BYTES 0x30000000u +define MCC_SHARE_MAXIMUM_JSON_BYTES (256u * 1024u) +define MCC_SHARE_MAXIMUM_METADATA_BYTES (32u * 1024u * 1024u) +define MCC_SHARE_MAXIMUM_PNG_BYTES (8u * 1024u * 1024u) +define MCC_SHARE_MAXIMUM_TOTAL_BYTES 0x40000000u +define MCC_SHARE_STAGE_FILES 168 +define MCC_WORKSHOP_WIRE_OFFSET 64 +define MCC_WORKSHOP_WIRE_SIZE 64 +define MCC_WORKSHOP_WIRE_VERSION 1 +enum VEHICLE_RIDING_DECK_VERDICT_SHIFT 1 +enum _distributed_actor_camouflaged_bit 4 +enum _distributed_actor_impulse_aligned_bit 6 +enum _distributed_actor_rides_bit 0 +enum _distributed_actor_running_blindly_bit 7 +enum _distributed_actor_shield_charging_bit 2 +enum _distributed_actor_shield_depleted_bit 1 +enum _distributed_actor_shield_over_charging_bit 3 +enum _distributed_actor_super_camouflaged_bit 5 +enum _distributed_infection_active 2 +enum _distributed_infection_countdown 1 +enum _distributed_infection_finished 3 +enum _distributed_infection_role_human 1 +enum _distributed_infection_role_none 0 +enum _distributed_infection_role_zombie 2 +enum _distributed_infection_waiting 0 +enum _distributed_message_actor_damage 73 +enum _distributed_message_actor_states 64 +enum _distributed_message_aim_assist_policy 90 +enum _distributed_message_batch 16 +enum _distributed_message_chat_config 89 +enum _distributed_message_chat_down 88 +enum _distributed_message_chat_up 87 +enum _distributed_message_checkpoint 96 +enum _distributed_message_client_build 92 +enum _distributed_message_client_identity 18 +enum _distributed_message_client_ready 9 +enum _distributed_message_coop_device_groups 68 +enum _distributed_message_coop_device_states 77 +enum _distributed_message_coop_events 71 +enum _distributed_message_coop_object_looks 74 +enum _distributed_message_coop_object_names 69 +enum _distributed_message_coop_object_transforms 72 +enum _distributed_message_coop_presentation 66 +enum _distributed_message_coop_screen_effect 76 +enum _distributed_message_coop_skip_vote 70 +enum _distributed_message_coop_sounds_retired 67 +enum _distributed_message_damage_animations 75 +enum _distributed_message_damage_events 10 +enum _distributed_message_fire_origins 93 +enum _distributed_message_game_state 7 +enum _distributed_message_hit_reports 11 +enum _distributed_message_inventories 4 +enum _distributed_message_map_share_offer 84 +enum _distributed_message_map_share_progress 86 +enum _distributed_message_map_share_request 83 +enum _distributed_message_map_share_sources 85 +enum _distributed_message_map_vote 94 +enum _distributed_message_map_vote_choice 95 +enum _distributed_message_mcc_admission 105 +enum _distributed_message_mcc_campaign 98 +enum _distributed_message_mcc_game_speed 100 +enum _distributed_message_mcc_grenades 97 +enum _distributed_message_mcc_load_progress 106 +enum _distributed_message_mcc_object_names 99 +enum _distributed_message_mcc_share_request 103 +enum _distributed_message_mcc_share_response 104 +enum _distributed_message_notice 17 +enum _distributed_message_object_changes 5 +enum _distributed_message_object_states 6 +enum _distributed_message_objects_synchronized 8 +enum _distributed_message_pickups 13 +enum _distributed_message_pings 19 +enum _distributed_message_player_inputs 14 +enum _distributed_message_player_prediction 1 +enum _distributed_message_player_statistics 3 +enum _distributed_message_relayed_actions 15 +enum _distributed_message_shield_effects 91 +enum _distributed_message_structure_bsp 65 +enum _distributed_message_unit_states 2 +enum _distributed_message_vehicle_prediction 12 +enum _distributed_message_vehicle_riding_map 107 +enum _distributed_message_voice_config 82 +enum _distributed_message_voice_down 81 +enum _distributed_message_voice_up 80 +enum _distributed_message_votekick 78 +enum _distributed_message_votekick_status 79 +enum _distributed_object_at_rest_bit 1 +enum _distributed_object_carried_bit 0 +enum _distributed_object_dead_bit 2 +enum _distributed_object_light_on_bit 5 +enum _distributed_object_light_sent_bit 4 +enum _distributed_object_predicted_bit 3 +enum _distributed_pose_aiming 1 +enum _distributed_pose_current_aiming 3 +enum _distributed_pose_current_looking 4 +enum _distributed_pose_facing 0 +enum _distributed_pose_looking 2 +enum _distributed_send_action_bit 1 +enum _distributed_send_sees_bit 2 +enum _distributed_send_state_bit 0 +enum _distributed_to_clients 0 +enum _distributed_to_clients_reliably 1 +enum _distributed_to_host 2 +enum _distributed_to_host_reliably 3 +enum _distributed_unit_alive_bit 0 +enum _distributed_unit_camouflaged_bit 0 +enum _distributed_unit_friendly_fire_bit 2 +enum _distributed_unit_killed_by_vehicle_bit 3 +enum _distributed_unit_part_camouflage_bit 4 +enum _distributed_unit_part_damage_bit 2 +enum _distributed_unit_part_deck_bit 7 +enum _distributed_unit_part_killer_bit 5 +enum _distributed_unit_part_powerups_bit 3 +enum _distributed_unit_part_riding_bit 0 +enum _distributed_unit_part_scripted_pose_bit 6 +enum _distributed_unit_part_up_bit 1 +enum _distributed_unit_placed_bit 1 +enum _distributed_unit_predicted_bit 7 +enum _distributed_unit_shield_charging_bit 5 +enum _distributed_unit_shield_depleted_bit 4 +enum _distributed_unit_shield_over_charging_bit 6 +enum _distributed_unit_super_camouflaged_bit 1 +enum _distributed_unit_suspended_bit 2 +enum _message_client_add_player_request_ingame 26 +enum _message_client_add_player_request_pregame 13 +enum _message_client_broadcast_game_search 0 +enum _message_client_game_start_request 17 +enum _message_client_game_update 25 +enum _message_client_graceful_game_exit_postgame 34 +enum _message_client_graceful_game_exit_pregame 18 +enum _message_client_host_crashed_cry_for_help 28 +enum _message_client_join_game_request 12 +enum _message_client_join_new_host 29 +enum _message_client_loaded 24 +enum _message_client_map_is_precached_pregame 19 +enum _message_client_ping 1 +enum _message_client_player_settings_request 16 +enum _message_client_remove_player_request_ingame 27 +enum _message_client_remove_player_request_postgame 32 +enum _message_client_remove_player_request_pregame 14 +enum _message_client_settings_request 15 +enum _message_client_switch_to_pregame 33 +enum _message_server_add_player_ingame 21 +enum _message_server_begin_game 8 +enum _message_server_game_advertise 2 +enum _message_server_game_over 23 +enum _message_server_game_settings_update 6 +enum _message_server_game_update 20 +enum _message_server_graceful_game_exit_postgame 31 +enum _message_server_graceful_game_exit_pregame 9 +enum _message_server_machine_accepted 4 +enum _message_server_machine_rejected 5 +enum _message_server_pong 3 +enum _message_server_postgame_keep_alive 11 +enum _message_server_pregame_countdown 7 +enum _message_server_pregame_keep_alive 10 +enum _message_server_remove_player_ingame 22 +enum _message_server_switch_to_pregame 30 +enum _vehicle_riding_deck_cabin_bit 3 +enum _vehicle_riding_deck_falling_bit 0 +enum mcc_admission_op 8a8312ea736e +enum mcc_share_file_kind 0ae653ab8b6d +enum mcc_share_op ae61837ba751 +enum mcc_share_result c8f57489625d +fields client_add_player_request_ingame 06ff007a9b35 +fields client_add_player_request_pregame 06ff007a9b35 +fields client_broadcast_game_search f31a5fac9a46 +fields client_game_start_request 758215ada4e1 +fields client_game_update 1134bf6a029b +fields client_graceful_game_exit_postgame 678699dea271 +fields client_graceful_game_exit_pregame 678699dea271 +fields client_host_crashed_cry_for_help 52eb2291ec03 +fields client_join_game_request d7dd965724e6 +fields client_join_new_host 52eb2291ec03 +fields client_loaded 678699dea271 +fields client_map_is_precached_pregame 0073b9d65051 +fields client_ping 0d113e26a89a +fields client_player_settings_request 06ff007a9b35 +fields client_remove_player_request_ingame 06ff007a9b35 +fields client_remove_player_request_postgame 06ff007a9b35 +fields client_remove_player_request_pregame 06ff007a9b35 +fields client_settings_request d6a7048d6284 +fields client_switch_to_pregame 678699dea271 +fields server_add_player_ingame 06ff007a9b35 +fields server_begin_game 87e5d5c7565c +fields server_game_advertise 2d5f42b781a4 +fields server_game_over 678699dea271 +fields server_game_settings_update 4c2744d8b8e8 +fields server_game_update beee6fb1929d +fields server_graceful_game_exit_postgame 678699dea271 +fields server_graceful_game_exit_pregame 678699dea271 +fields server_machine_accepted 0d113e26a89a +fields server_machine_rejected 758215ada4e1 +fields server_pong 678699dea271 +fields server_postgame_keep_alive 758215ada4e1 +fields server_pregame_countdown 758215ada4e1 +fields server_pregame_keep_alive 678699dea271 +fields server_remove_player_ingame 1718d4189972 +fields server_switch_to_pregame 678699dea271 +layout HALO_PORT_NETWORK_GAME_LOCAL_DATA_OFFSET (HALO_PORT_NETWORK_GAME_PLAYERS_END + 0x36) +layout HALO_PORT_NETWORK_GAME_SIZE (HALO_PORT_NETWORK_GAME_PLAYERS_END + 0x3A + 64) /* MCC content and metadata SHA-256 */ +layout HALO_PORT_NETWORK_GAME_VARIANT_OPTIONS_OFFSET (HALO_PORT_NETWORK_GAME_PLAYERS_END + 0xA) +size message_client_add_player_request_ingame 0x20 +size message_client_add_player_request_pregame 0x20 +size message_client_broadcast_game_search 0x0C +size message_client_game_start_request 0x02 +size message_client_game_update 0x88 +size message_client_graceful_game_exit_postgame 0x04 +size message_client_graceful_game_exit_pregame 0x04 +size message_client_host_crashed_cry_for_help 0x10 +size message_client_join_game_request 0x70 + 170 + 64 + 2 +size message_client_join_new_host 0x10 +size message_client_loaded 0x04 +size message_client_map_is_precached_pregame 0x100 +size message_client_ping 0x08 +size message_client_player_settings_request 0x20 +size message_client_remove_player_request_ingame 0x20 +size message_client_remove_player_request_postgame 0x20 +size message_client_remove_player_request_pregame 0x20 +size message_client_settings_request 0x44 +size message_client_switch_to_pregame 0x04 +size message_server_add_player_ingame 0x20 +size message_server_begin_game 0x04 +size message_server_game_advertise 0x114 +size message_server_game_over 0x04 +size message_server_game_settings_update 8 + HALO_PORT_NETWORK_GAME_SETTINGS_FRAGMENT_SIZE +size message_server_game_update 0x10 + HALO_PORT_MAXIMUM_NETWORK_PLAYERS * 0x20 +size message_server_graceful_game_exit_postgame 0x04 +size message_server_graceful_game_exit_pregame 0x04 +size message_server_machine_accepted 0x08 +size message_server_machine_rejected 0x02 +size message_server_pong 0x04 +size message_server_postgame_keep_alive 0x02 +size message_server_pregame_countdown 0x02 +size message_server_pregame_keep_alive 0x04 +size message_server_remove_player_ingame 0x24 +size message_server_switch_to_pregame 0x04 +struct distributed_actor_damage 96a57e13e2b8 +struct distributed_actor_damage_message f985e899a708 +struct distributed_actor_state 8bd5e771659d +struct distributed_actor_state_message 51a56e04a536 +struct distributed_chat_config dfa4e32efe1e +struct distributed_chat_line cdab1468ffe0 +struct distributed_client_build 503e4474b798 +struct distributed_client_identity 4d9e62025616 +struct distributed_coop_device_group 4aa3499be2cc +struct distributed_coop_device_groups_message b96ad0030ccc +struct distributed_coop_device_state 727444a5c79b +struct distributed_coop_device_states_message 48f17c3da6f5 +struct distributed_coop_event 62bbd76ba4af +struct distributed_coop_events_message 562bdd70bfae +struct distributed_coop_object_look 77cbae00e4ad +struct distributed_coop_object_looks_message 51dbb474aa17 +struct distributed_coop_object_names f3ecad927448 +struct distributed_coop_object_names_message 7d743ad3710e +struct distributed_coop_object_transform 055897bbff8f +struct distributed_coop_object_transforms_message de95468f7f6d +struct distributed_coop_presentation f34649b3fc6d +struct distributed_coop_presentation_message eb4c7a895272 +struct distributed_coop_screen_effect_message a0a226e0858e +struct distributed_coop_skip_vote c37a12a02932 +struct distributed_coop_skip_vote_message d21260f32711 +struct distributed_damage d2bdb398fb2b +struct distributed_damage_animation ae158e21c915 +struct distributed_damage_animations_message 863e25ca3614 +struct distributed_damage_event 659e4d49733b +struct distributed_damage_event_message c954363dcf26 +struct distributed_fire_origin 700dfdb20582 +struct distributed_fire_origin_message 7613e8f9d43e +struct distributed_hit_report 9a44ca43a88b +struct distributed_hit_report_message 37279f2addca +struct distributed_infection_player d8b98eecf26b +struct distributed_infection_state 8a01c46945ad +struct distributed_inventory 05a279a76ba5 +struct distributed_inventory_message 11825a84dc29 +struct distributed_map_share_offer 4bea857123c2 +struct distributed_map_share_offer_file 204a3b73d193 +struct distributed_map_share_progress 2c3831013302 +struct distributed_map_share_request 3cdcbc8c3a49 +struct distributed_map_share_source 940f8a4c9849 +struct distributed_map_vote_choice e0aa3fb40224 +struct distributed_map_vote_choice_entry b8e5a595dbad +struct distributed_map_vote_status 524c63fc37e2 +struct distributed_message_header 5bc35a4ad92a +struct distributed_object_change 343e570cfa1d +struct distributed_object_change_message 4c3679cd4dae +struct distributed_object_state 1b656bbda892 +struct distributed_object_state_message 004c4b7aa530 +struct distributed_pickup 46e6f981ac40 +struct distributed_pings_message 35c6009dee29 +struct distributed_player_input a0cf65a1197c +struct distributed_player_ping 377e0e3045f4 +struct distributed_player_statistics 2a44afb8f96c +struct distributed_riding_latched 3d13fb412582 +struct distributed_riding_map_message 01a360e89e36 +struct distributed_statistics_message 79134e6e9811 +struct distributed_structure_bsp 53f7d5067cc9 +struct distributed_structure_bsp_message 096278a05681 +struct distributed_vector e80d7f9fc970 +struct distributed_voice_config 665bdc14478b +struct distributed_voice_down e3751d692f16 +struct distributed_voice_up 3d74ee44e4cb +struct distributed_votekick_request 7e29ffd54bd1 +struct distributed_votekick_status b94458cdc180 +struct game_variant_options 0e258e4cf85b +struct mcc_admission_identity ba88dfe0091d +struct mcc_admission_message 0a2136c026a5 +struct mcc_load_message 587f305ba598 +struct mcc_share_entry 66c2657ada44 +struct mcc_share_request 327320bc7edb +struct mcc_share_response 3c288efa85b1 diff --git a/tools/fixtures/plasma_lighting_capture.c b/tools/fixtures/plasma_lighting_capture.c new file mode 100644 index 0000000000..78a47c1468 --- /dev/null +++ b/tools/fixtures/plasma_lighting_capture.c @@ -0,0 +1,909 @@ +/* Test-build-only fixture. The visual runner installs and removes this file. + Creates real plasma projectiles; never linked into the normal game. */ +#include "cseries.h" +#include +#include "objects/objects.h" +#include "objects/object_definitions.h" +#include "objects/damage.h" +#include "physics/collisions.h" +#include "items/projectiles.h" +#include "items/projectile_definitions.h" +#include "items/weapons.h" +#include "camera/observer.h" +#include "tag_files/tag_groups.h" +#include "rasterizer/rasterizer.h" +#include "rasterizer/rasterizer_lights.h" +#include "plasma_lighting.h" +#include "game/players.h" +#include "game/game.h" +#include "units/units.h" +#include "units/bipeds.h" +#include "units/vehicles.h" +#include "devices/devices.h" +#include "cache/cache_files.h" +#include "cutscene/cinematics.h" +#include "game/cheats.h" +#include "ai/ai.h" +#include "scenario/scenario.h" +#include +#include + +void platform_log(const char *format, ...); +int config_boolean(const char *name); +long light_port_glow_definition_get(void); +real render_interpolation_fraction(void); +static long capture_ticks, capture_projectile = NONE, capture_last_time; +static struct observer_result capture_camera; +static int capture_model, capture_probe, capture_burst = 1; +static long capture_bolts[32], capture_door = NONE; +static int capture_combat, capture_toggle; +static long capture_target = NONE; +static long capture_emitter = NONE; +static long capture_emitter_holder = NONE; +static long capture_vehicle = NONE; +static int capture_emitter_attached; +int plasma_capture_skip_cinematic(void) +{ + return cinematic_globals && cinematic_in_progress(); +} + +int plasma_capture_turret_fire(void) +{ + return capture_ticks >= 75 && capture_ticks % 30 < 23; +} + +int plasma_capture_scorpion_fire(void) +{ + if (capture_ticks < 75 || capture_ticks > 240) return 0; + if (capture_ticks < 120) return 2; + if (capture_ticks < 170) return 1; + return 3; +} + +/* Render-only exterior view: the seated player's ordinary controls still aim + and fire the turret. Keep the chassis and adjacent ground in the picture. */ +void plasma_capture_camera(void) +{ + struct observer_result *camera; + struct object_datum *vehicle; + struct object_marker marker; + real_point3d target; + real_vector3d right; + int scorpion = getenv("HALO_SCORPION_CAPTURE") != NULL; + if (getenv("HALO_EMITTER_CAPTURE_COUNTER_DETAIL") && capture_emitter != NONE && + object_try_and_get(capture_emitter) && + object_get_marker_by_name(capture_emitter, "primary trigger", &marker, 1)) + { + /* Look over the holder's shoulder at the world-model display. This + changes only the capture camera, never the material or light. */ + camera = (struct observer_result *)observer_get_camera(0); + target = marker.matrix.position; + target.x -= 0.18f * marker.matrix.forward.i; + target.y -= 0.18f * marker.matrix.forward.j; + target.z -= 0.18f * marker.matrix.forward.k; + cross_product3d(&marker.matrix.forward, &marker.matrix.up, &right); + camera->position.x = target.x - 0.55f * marker.matrix.forward.i + 0.35f * right.i + 0.35f * marker.matrix.up.i; + camera->position.y = target.y - 0.55f * marker.matrix.forward.j + 0.35f * right.j + 0.35f * marker.matrix.up.j; + camera->position.z = target.z - 0.55f * marker.matrix.forward.k + 0.35f * right.k + 0.35f * marker.matrix.up.k; + vector_from_points3d(&camera->position, &target, &camera->forward); + normalize3d(&camera->forward); + observer_up_from_forward(&camera->forward, &camera->up); + scenario_location_from_point(&camera->location, &camera->position); + return; + } + if ((!getenv("HALO_WARTHOG_CAPTURE_EXTERIOR") && !scorpion) || capture_vehicle == NONE || + !(vehicle = object_try_and_get(capture_vehicle))) + return; + camera = (struct observer_result *)observer_get_camera(0); + target = vehicle->object.position; + target.z += 0.6f; + cross_product3d(&capture_camera.forward, &capture_camera.up, &right); + camera->position = vehicle->object.position; + camera->position.x += (scorpion ? 6.0f : 3.0f) * right.i - (scorpion ? 2.5f : 1.5f) * capture_camera.forward.i; + camera->position.y += (scorpion ? 6.0f : 3.0f) * right.j - (scorpion ? 2.5f : 1.5f) * capture_camera.forward.j; + camera->position.z += scorpion ? 2.4f : 1.1f; + vector_from_points3d(&camera->position, &target, &camera->forward); + normalize3d(&camera->forward); + observer_up_from_forward(&camera->forward, &camera->up); + scenario_location_from_point(&camera->location, &camera->position); +} + +/* Apply after ordinary camera interpolation, so the capture sees the same + vehicle pose as the renderer instead of having its observer edit replaced. */ +struct observer_result const *plasma_capture_view(struct observer_result const *source) +{ + static struct observer_result view; + struct object_datum *vehicle; + real_point3d target; + real_vector3d right; + real distance; + const char *kind = getenv("HALO_AMBIENT_CAPTURE"); + if (!kind || capture_vehicle == NONE || !(vehicle = object_try_and_get(capture_vehicle))) return source; + view = *source; + target = vehicle->object.position; + target.z += !strcmp(kind, "dropship") ? -0.5f : 0.4f; + distance = !strcmp(kind,"dropship") ? 9.0f : !strcmp(kind,"scorpion") ? 5.0f : 3.0f; + cross_product3d(&vehicle->object.forward, &vehicle->object.up, &right); + view.position.x = target.x + distance * vehicle->object.forward.i + distance * .6f * right.i; + view.position.y = target.y + distance * vehicle->object.forward.j + distance * .6f * right.j; + view.position.z = target.z + (!strcmp(kind,"dropship") ? 0.0f : 1.0f); + vector_from_points3d(&view.position, &target, &view.forward); + normalize3d(&view.forward); + observer_up_from_forward(&view.forward, &view.up); + scenario_location_from_point(&view.location, &view.position); + return &view; +} + +static void capture_ground(real_point3d *position) +{ + struct collision_result ground; + real_vector3d down = {0, 0, -8}; + real_point3d from = *position; + from.z = capture_camera.position.z + 1.0f; + if (collision_test_vector(FLAG(_collision_test_structure_bit) | + FLAG(_collision_test_front_facing_surfaces_bit), &from, &down, NONE, &ground)) + position->z = ground.point.z + 0.03f; +} + +/* Create ordinary objects; exercise their stock functions and deletion. */ +static void ambient_capture_tick(const char *kind) +{ + static const struct { const char *kind, *name, *alternate; long group; } profiles[] = { + {"ghost", "vehicles\\ghost\\ghost_mp", "vehicles\\ghost\\ghost", 'vehi'}, + {"banshee", "vehicles\\banshee\\banshee_mp", "vehicles\\banshee\\banshee", 'vehi'}, + {"dropship", "vehicles\\c_dropship\\c_dropship", NULL, 'vehi'}, + {"warthog", "vehicles\\warthog\\mp_warthog", "vehicles\\warthog\\warthog", 'vehi'}, + {"scorpion", "vehicles\\scorpion\\scorpion_mp", "vehicles\\scorpion\\scorpion", 'vehi'}, + {"overshield", "powerups\\over shield", NULL, 'eqip'}, + {"camo", "powerups\\active camouflage", NULL, 'eqip'}, + {"teleporter", "scenery\\teleporter_shield\\teleporter", NULL, 'scen'}, + }; + int i; + for (i = 0; i < NUMBEROF(profiles); i++) + if (!strcmp(kind, profiles[i].kind)) break; + if (i == NUMBEROF(profiles)) return; + if (capture_ticks == 65) + { + struct object_placement_data placement; + long tag = tag_loaded(profiles[i].group, profiles[i].name); + if (tag == NONE && profiles[i].alternate) tag = tag_loaded(profiles[i].group, profiles[i].alternate); + if (tag == NONE) { platform_log("AMBIENT missing %s", kind); return; } + object_placement_data_new(&placement, tag, NONE); + placement.position = capture_camera.position; + placement.position.x += capture_camera.forward.i * (!strcmp(kind, "dropship") ? 9 : 3); + placement.position.y += capture_camera.forward.j * (!strcmp(kind, "dropship") ? 9 : 3); + capture_ground(&placement.position); + if (!strcmp(kind, "dropship")) placement.position.z += 3.0f; + placement.forward = capture_camera.forward; + placement.forward.i = -placement.forward.i; + placement.forward.j = -placement.forward.j; + placement.forward.k = 0; + normalize3d(&placement.forward); + observer_up_from_forward(&placement.forward, &placement.up); + capture_emitter = object_new(&placement); + platform_log("AMBIENT created %ld %s", capture_emitter, kind); + if (capture_emitter != NONE && profiles[i].group == 'vehi') + { + capture_vehicle = capture_emitter; + vehicle_hover(capture_vehicle, TRUE); + /* Use a real driver so engine functions and headlights remain on. */ + if (strcmp(kind, "dropship")) + { + long driver_tag = tag_loaded('bipd', "characters\\cyborg\\cyborg"); + if (driver_tag != NONE) + { + object_placement_data_new(&placement, driver_tag, NONE); + placement.position = object_get(capture_vehicle)->object.position; + capture_emitter_holder = object_new(&placement); + unit_scripting_enter_vehicle(capture_emitter_holder, capture_vehicle, + !strcmp(kind,"ghost") ? "G-driver" : !strcmp(kind,"banshee") ? "B-driver" : + !strcmp(kind,"scorpion") ? "scorpion-driver" : "W-driver"); + platform_log("AMBIENT driver %ld parent %ld", capture_emitter_holder, object_get(capture_emitter_holder)->object.parent_object_index); + } + } + } + } + if (capture_emitter != NONE && object_try_and_get(capture_emitter)) + { + if (capture_ticks % 30 == 0) + { + struct object_datum *object = object_get(capture_emitter); + platform_log("AMBIENT functions %ld %.4f %.4f %.4f %.4f", capture_ticks, + object->object.outgoing_function_values[0], object->object.outgoing_function_values[1], + object->object.outgoing_function_values[2], object->object.outgoing_function_values[3]); + } + if (capture_ticks == 200 && profiles[i].group == 'vehi') vehicle_hover(capture_emitter, FALSE); + if (capture_ticks == 225) { object_delete(capture_emitter); capture_emitter = capture_vehicle = NONE; platform_log("AMBIENT deleted"); } + } +} + +static void ammo_capture_tick(const char *kind) +{ + struct object_placement_data placement; + long tag, holder; + int i; + int sword = !strncmp(kind, "sword-", 6); + int needler = !strncmp(kind, "needler-", 8); + const char *pose = sword ? kind + 6 : needler ? kind + 8 : kind + 5; + if (capture_ticks == 65) + { + holder = player_control_get_unit_index(0); + if (strcmp(pose, "fp")) + { + tag = tag_loaded('bipd', !strcmp(pose, "elite") ? "characters\\elite\\elite" : + !strcmp(pose, "marine") ? "characters\\marine_armored\\marine_armored" : + !strcmp(pose, "grunt") ? "characters\\grunt\\grunt" : "characters\\cyborg\\cyborg"); + if (tag == NONE) { platform_log("EMITTER missing actor"); return; } + object_placement_data_new(&placement, tag, NONE); + placement.position = capture_camera.position; + placement.position.x += capture_camera.forward.i * 1.5f; + placement.position.y += capture_camera.forward.j * 1.5f; + placement.position.z -= 0.6f; + if (getenv("HALO_EMITTER_CAPTURE_GROUNDED")) + capture_ground(&placement.position); + placement.forward = capture_camera.forward; + placement.forward.k = 0; + if (getenv("HALO_EMITTER_CAPTURE_FACE_CAMERA")) + { + placement.forward.i = -placement.forward.i; + placement.forward.j = -placement.forward.j; + } + normalize3d(&placement.forward); + observer_up_from_forward(&placement.forward, &placement.up); + holder = object_new(&placement); + } + tag = tag_loaded('weap', sword ? "weapons\\energy sword\\energy sword" : needler ? "weapons\\needler\\needler" : "weapons\\assault rifle\\assault rifle"); + if (holder == NONE || tag == NONE) return; + capture_emitter_holder = holder; + unit_drop_current_weapon(holder, TRUE); + unit_drop_current_weapon(holder, TRUE); + object_placement_data_new(&placement, tag, NONE); + placement.position = object_get(holder)->object.position; + capture_emitter = object_new(&placement); + if (capture_emitter != NONE && unit_add_weapon_to_inventory(holder, capture_emitter, TRUE)) + { + if (!strcmp(pose, "fp")) + for (i = 0; i < MAXIMUM_WEAPONS_PER_UNIT; i++) + if (unit_inventory_get_weapon(holder, (short)i) == capture_emitter) + player_control_set_desired_weapon(holder, (short)i); + platform_log("EMITTER created %ld tag ammo holder %ld mode %s", capture_emitter, holder, kind); + } + } + if (capture_emitter_holder != NONE && object_try_and_get(capture_emitter_holder)) + { + if (getenv("HALO_EMITTER_CAPTURE_GROUNDED") && strcmp(pose, "fp") && capture_ticks == 80) + { + real_vector3d facing; + real_point3d target = object_get(capture_emitter_holder)->object.position; + target.z += !strcmp(pose, "grunt") ? 0.25f : 0.4f; + vector_from_points3d(&observer_get_camera(0)->position, &target, &facing); + normalize3d(&facing); + player_control_set_facing(0, &facing); + } + if (getenv("HALO_EMITTER_CAPTURE_CROUCH") && capture_ticks == 85) + { + /* An unowned fixture starts alert; only the combat stance has a crouch seat. */ + unit_get(capture_emitter_holder)->unit.animation.desired_state = _unit_animation_state_in_combat; + unit_persistent_control(capture_emitter_holder, 90, FLAG(_unit_control_crouch_modifier_bit)); + } + if (capture_ticks == 100 || capture_ticks == 140 || capture_ticks == 190) + { + struct biped_datum *biped = (struct biped_datum *)object_get(capture_emitter_holder); + platform_log("EMITTER holder tick %ld crouch %.4f position %.4f %.4f %.4f", capture_ticks, + biped->biped.crouch, biped->object.position.x, biped->object.position.y, biped->object.position.z); + } + } + if (capture_ticks == 200 && capture_emitter_holder != NONE) + { + unit_drop_current_weapon(capture_emitter_holder, TRUE); + platform_log("EMITTER ammo dropped"); + } +} +static void emitter_capture_tick(void) +{ + const char *kind = getenv("HALO_EMITTER_CAPTURE"); + struct object_placement_data placement; + long tag; + if (!strncmp(kind, "ammo-", 5) || !strncmp(kind, "needler-", 8) || !strncmp(kind, "sword-", 6)) + { + ammo_capture_tick(kind); + return; + } + if (capture_ticks == 65) + { + const char *name = !strcmp(kind, "stationary") ? "scenery\\c_field_generator\\c_field_generator" : + !strcmp(kind, "fuel") ? "weapons\\fuel rod gun\\fuel rod" : + !strcmp(kind, "hunter") ? "characters\\hunter\\hunter" : + !strcmp(kind, "major") ? "characters\\jackal\\jackal major" : "characters\\jackal\\jackal"; + capture_emitter_attached = FALSE; + tag = tag_loaded(!strcmp(kind, "stationary") ? 'scen' : !strcmp(kind, "fuel") ? 'weap' : 'bipd', name); + if (tag == NONE) { platform_log("EMITTER missing tag %s", name); return; } + object_placement_data_new(&placement, tag, NONE); + placement.position = capture_camera.position; + placement.position.x += capture_camera.forward.i * 2.5f; + placement.position.y += capture_camera.forward.j * 2.5f; + placement.position.z -= 0.65f; + if (!strcmp(kind, "stationary") || !strcmp(kind, "hunter")) + { + struct collision_result ground; + real_vector3d down = {0, 0, -5}; + real_point3d from = placement.position; + from.z = capture_camera.position.z + 0.5f; + if (collision_test_vector(FLAG(_collision_test_structure_bit) | + FLAG(_collision_test_front_facing_surfaces_bit), &from, &down, NONE, &ground)) + placement.position.z = ground.point.z + 0.03f; + } + placement.forward = capture_camera.forward; + placement.forward.i = -placement.forward.i; + placement.forward.j = -placement.forward.j; + placement.forward.k = 0; + if (!strcmp(kind, "stationary")) + { + placement.forward.i = -capture_camera.forward.j; + placement.forward.j = capture_camera.forward.i; + } + normalize3d(&placement.forward); + observer_up_from_forward(&placement.forward, &placement.up); + capture_emitter = object_new(&placement); + platform_log("EMITTER created %ld tag %s", capture_emitter, name); + if (!strcmp(kind, "fuel")) + { + tag = tag_loaded('bipd', "characters\\grunt\\grunt"); + if (tag != NONE) + { + struct object_placement_data holder; + object_placement_data_new(&holder, tag, NONE); + holder.position = placement.position; + holder.forward = placement.forward; + holder.up = placement.up; + capture_emitter_holder = object_new(&holder); + if (capture_emitter_holder != NONE && capture_emitter != NONE) + { + int held = unit_add_weapon_to_inventory(capture_emitter_holder, capture_emitter, TRUE); + /* This fixture creates the gun loose before attaching it. Clear + that spawn-time detonation; the later stock drop stays live. */ + if (held) weapon_get(capture_emitter)->item.detonation_ticks = 0; + platform_log("EMITTER held %d", held); + } + } + } + } + if (capture_emitter != NONE && object_try_and_get(capture_emitter)) + { + if (strcmp(kind, "fuel") && strcmp(kind, "hunter") && (capture_ticks == 100 || capture_ticks == 112 || + capture_ticks == 140 || capture_ticks == 160 || capture_ticks == 195)) + { + struct object_datum *object = object_get(capture_emitter); + platform_log("EMITTER shield tick %ld flash %.5f vitality %.5f depleted %d", capture_ticks, + object->object.outgoing_function_values[0], object->object.shield_vitality, + TEST_FLAG(object->object.damage_flags, _object_shield_depleted_bit)); + } + if (!strcmp(kind, "fuel") && !capture_emitter_attached && + object_get(capture_emitter)->object.parent_object_index == capture_emitter_holder) + { + /* Inventory insertion precedes the actual hand attachment. The + loose spawn can arm itself until that animation completes. */ + weapon_get(capture_emitter)->item.detonation_ticks = 0; + capture_emitter_attached = TRUE; + platform_log("EMITTER attached"); + } + if (capture_ticks == 110 && strcmp(kind, "fuel") && strcmp(kind, "hunter")) + { + struct damage_network_state state; + damage_get_network_state(capture_emitter, &state); + state.current_shield_damage = 1.0f; + state.recent_shield_damage = 0.5f; + state.shield_vitality = 0.75f; + damage_set_network_state(capture_emitter, &state); + platform_log("EMITTER hit %ld", capture_emitter); + } + if (capture_ticks == 150 && strcmp(kind, "fuel") && strcmp(kind, "hunter")) + { + object_deplete_shield(capture_emitter); + platform_log("EMITTER depleted %ld", capture_emitter); + } + if (capture_ticks == 180 && strcmp(kind, "fuel") && strcmp(kind, "hunter")) + { + struct damage_network_state state; + damage_get_network_state(capture_emitter, &state); + state.shield_depleted = FALSE; + state.shield_vitality = 1.0f; + damage_set_network_state(capture_emitter, &state); + platform_log("EMITTER recovered %ld", capture_emitter); + } + if (capture_ticks == 150 && !strcmp(kind, "fuel") && capture_emitter_holder != NONE) + { + unit_drop_current_weapon(capture_emitter_holder, TRUE); + platform_log("EMITTER dropped"); + } + if (capture_ticks == 225) + { + object_delete(capture_emitter); + capture_emitter = NONE; + platform_log("EMITTER deleted"); + } + } +} +static const char *capture_projectile_tags[] = { + "weapons\\plasma rifle\\bolt", "weapons\\plasma pistol\\bolt", + "weapons\\plasma rifle\\charged bolt", "weapons\\rocket launcher\\rocket", + "weapons\\needler\\needle", + "vehicles\\ghost\\ghost bolt", + "vehicles\\banshee\\banshee bolt", + "vehicles\\banshee\\banshee fuel rod", + "vehicles\\c gun turret\\c gun turret", + "weapons\\fuel rod gun\\fuel rod", + "vehicles\\wraith\\wraith mortar", + "weapons\\needler\\mp_needle", + "vehicles\\banshee\\mp_banshee fuel rod", + "vehicles\\c gun turret\\mp gun turret", + "weapons\\plasma_cannon\\plasma_cannon", + "weapons\\plasma grenade\\plasma grenade" +}; +static int capture_kind(void) +{ + const char *kind = getenv("HALO_PLASMA_CAPTURE_KIND"); + if (kind && !strcmp(kind, "pistol")) return 1; + if (kind && !strcmp(kind, "charged")) return 2; + if (kind && !strcmp(kind, "rocket")) return 3; + if (kind && !strcmp(kind, "needle")) return 4; + if (kind && !strcmp(kind, "ghost")) return 5; + if (kind && !strcmp(kind, "banshee")) return 6; + if (kind && !strcmp(kind, "banshee-fuel")) return 7; + if (kind && !strcmp(kind, "shade")) return 8; + if (kind && !strcmp(kind, "fuel")) return 9; + if (kind && !strcmp(kind, "wraith")) return 10; + if (kind && !strcmp(kind, "mp-needle")) return 11; + if (kind && !strcmp(kind, "mp-banshee-fuel")) return 12; + if (kind && !strcmp(kind, "mp-shade")) return 13; + if (kind && !strcmp(kind, "ce-fuel")) return 14; + if (kind && !strcmp(kind, "grenade")) return 15; + return 0; +} +int config_write_boolean(const char *name, int value); +static real capture_distance, capture_height, capture_receiver_distance, capture_span; +static real capture_option(const char *name, real fallback) +{ + const char *value = getenv(name); + return value ? (real)atof(value) : fallback; +} +static unsigned long capture_model_draws, capture_specular_draws; +static int capture_specular_selected; +void plasma_capture_model_draw(unsigned int mask) +{ + if (mask) + capture_model_draws++; +} +void plasma_capture_specular_begin(long index) +{ + capture_specular_selected = plasma_lighting_selected(index); +} +void plasma_capture_specular_draw(void) +{ + if (capture_specular_selected) + capture_specular_draws++; +} + +int plasma_capture_hold_projectile(long index) +{ + int n; + for (n = 0; n < capture_burst; n++) + if (capture_probe && index == capture_bolts[n]) + return 1; + return 0; +} +/* Shield-only acceptance: controlled charge, layer loss, hit and recharge. + These writes exist exclusively in this test executable. */ +static void shield_capture_tick(void) +{ + const char *mode = getenv("HALO_SHIELD_CAPTURE"); + struct object_placement_data placement; + struct unit_datum *unit; + long tag; + if (capture_ticks == 65) + { + if (!strcmp(mode, "fp")) capture_target = player_control_get_unit_index(0); + else + { + tag = tag_loaded('bipd', !strcmp(mode, "elite") ? "characters\\elite\\elite" : "characters\\cyborg\\cyborg"); + if (tag == NONE) { platform_log("SHIELD missing actor"); return; } + object_placement_data_new(&placement, tag, NONE); + placement.position = capture_camera.position; + placement.position.x += capture_camera.forward.i * 2.f; + placement.position.y += capture_camera.forward.j * 2.f; + capture_ground(&placement.position); + placement.forward = capture_camera.forward; + placement.forward.i = -placement.forward.i; placement.forward.j = -placement.forward.j; placement.forward.k = 0; + normalize3d(&placement.forward); + observer_up_from_forward(&placement.forward, &placement.up); + capture_target = object_new(&placement); + } + platform_log("SHIELD created %ld mode %s", capture_target, mode); + } + if (capture_target == NONE || !(unit = unit_try_and_get(capture_target))) return; + if (!strcmp(mode, "charge") || !strcmp(mode, "fp")) + { + SET_FLAG(unit->object.damage_flags, _object_shield_over_charging_bit, capture_ticks >= 90 && capture_ticks < 150); + unit->object.shield_vitality = capture_ticks < 90 ? 1.f : capture_ticks < 150 ? 1.f + (capture_ticks - 90) / 30.f : capture_ticks < 180 ? 3.f : capture_ticks < 220 ? 1.8f : 1.f; + } + else + { + if (capture_ticks == 100 || capture_ticks == 130) + { + unit->object.recent_shield_damage = 1.f; + unit->object.current_shield_damage = 1.f; + unit->object.shield_damage_decay_timer = 0; + unit->object.shield_vitality = .45f; + } + if (capture_ticks >= 160 && capture_ticks < 210) + { + SET_FLAG(unit->object.damage_flags, _object_shield_charging_bit, TRUE); + unit->object.shield_stun_ticks = 0; + unit->object.shield_vitality = .1f + .9f * (capture_ticks - 160) / 50.f; + } + } + if (getenv("HALO_EMITTER_CAPTURE_CROUCH") && capture_ticks == 110) + { + unit->unit.animation.desired_state = _unit_animation_state_in_combat; + unit_persistent_control(capture_target, 65, FLAG(_unit_control_crouch_modifier_bit)); + } + if (capture_ticks % 10 == 0) + platform_log("SHIELD state tick %ld vitality %.4f values %.4f %.4f %.4f %.4f", capture_ticks, unit->object.shield_vitality, + unit->object.outgoing_function_values[0], unit->object.outgoing_function_values[1], unit->object.outgoing_function_values[2], unit->object.outgoing_function_values[3]); +} + +void plasma_capture_tick(void) +{ + struct object_placement_data placement; + real_vector3d right; + long tag, i, bolt; + long now = game_time_get(); + if (now < capture_last_time) + { + capture_ticks = 0; + capture_projectile = capture_door = capture_target = NONE; + capture_emitter = capture_emitter_holder = NONE; + capture_vehicle = NONE; + for (i = 0; i < 32; i++) + capture_bolts[i] = NONE; + } + capture_last_time = now; + if (!game_in_progress() || game_time_menu_scene()) + return; + if ((getenv("HALO_PLASMA_CAPTURE_DOOR") || getenv("HALO_COVENANT_CAPTURE_CAMPAIGN")) && cinematic_in_progress()) + return; + /* Keep campaign captures reproducible without AI attacks or reloads from + the fixture's nearby explosions. Projectile flight/effects remain live. */ + if (getenv("HALO_COVENANT_CAPTURE_CAMPAIGN")) + { + ai_globals_ai_active(FALSE); + cheat.deathless_player = TRUE; + } + capture_ticks++; + if (getenv("HALO_WEAPON_GLOW") && capture_ticks % 15 == 0) + { + long holder = player_control_get_unit_index(0); + struct unit_datum *unit = unit_try_and_get(holder); + if (unit && unit->unit.current_weapon_index >= 0 && unit->unit.current_weapon_index < MAXIMUM_WEAPONS_PER_UNIT) + { + struct weapon_datum *weapon = weapon_try_and_get(unit_inventory_get_weapon(holder, unit->unit.current_weapon_index)); + if (weapon) platform_log("EMITTER weapon tick %ld heat %.4f charged %.4f state %d effect %ld", capture_ticks, + weapon->weapon.heat, weapon->weapon.overcharged, weapon->weapon.triggers[0].state, weapon->weapon.overheated_effect_index); + } + } + + if ((getenv("HALO_WARTHOG_CAPTURE_EXTERIOR") || getenv("HALO_SCORPION_CAPTURE")) && capture_vehicle != NONE && + object_try_and_get(capture_vehicle)) + { + real_vector3d facing = object_get(capture_vehicle)->object.forward; + if (capture_ticks >= 170) + { + facing.i = -facing.i; + facing.j = -facing.j; + } + else if (capture_ticks >= 120) + { + real x = facing.i; + facing.i = -facing.j; + facing.j = x; + } + facing.k = -0.15f; + normalize3d(&facing); + player_control_set_facing(0, &facing); + if (capture_ticks == 110 || capture_ticks == 160 || capture_ticks == 210) + { + struct object_marker marker; + if (object_get_marker_by_name(capture_vehicle, "primary trigger", &marker, 1)) + platform_log("WARTHOG aim tick %ld forward %.4f %.4f %.4f", capture_ticks, + marker.matrix.forward.i, marker.matrix.forward.j, marker.matrix.forward.k); + } + } + if (capture_ticks == 60) + { + capture_camera = *observer_get_camera(0); + capture_combat = getenv("HALO_PLASMA_CAPTURE_COMBAT") != NULL; + capture_toggle = getenv("HALO_PLASMA_CAPTURE_TOGGLE") != NULL; + capture_model = getenv("HALO_PLASMA_CAPTURE_MODEL") != NULL; + capture_burst = (int)capture_option("HALO_PLASMA_CAPTURE_BURST", 1); + if (capture_burst < 1 || capture_burst > 32) + capture_burst = 1; + for (i = 0; i < 32; i++) + capture_bolts[i] = NONE; + capture_probe = getenv("HALO_PLASMA_CAPTURE_PROBE") != NULL; + capture_span = capture_option("HALO_PLASMA_CAPTURE_SPAN", 2.0f); + capture_distance = capture_option("HALO_PLASMA_CAPTURE_DISTANCE", capture_model ? 2.2f : 3.0f); + capture_height = capture_option("HALO_PLASMA_CAPTURE_HEIGHT", capture_model ? -0.2f : -0.6f); + capture_receiver_distance = capture_option("HALO_PLASMA_CAPTURE_RECEIVER_DISTANCE", 2.8f); + platform_log("PLASMA camera %.4f %.4f %.4f forward %.4f %.4f %.4f", capture_camera.position.x, + capture_camera.position.y, capture_camera.position.z, capture_camera.forward.i, + capture_camera.forward.j, capture_camera.forward.k); + } + if (getenv("HALO_AMBIENT_CAPTURE")) { ambient_capture_tick(getenv("HALO_AMBIENT_CAPTURE")); return; } + if (getenv("HALO_SHIELD_CAPTURE")) { shield_capture_tick(); return; } + if (getenv("HALO_EMITTER_CAPTURE")) + { + emitter_capture_tick(); + return; + } + if (capture_ticks == 65 && capture_combat) + { + long unit = player_control_get_unit_index(0); + const char *role = getenv("HALO_NETWORK_TEST"); + if (getenv("HALO_WARTHOG_CAPTURE") || getenv("HALO_SCORPION_CAPTURE")) + { + long vehicle; + int scorpion = getenv("HALO_SCORPION_CAPTURE") != NULL; + if (role && !strncmp(role, "join", 4)) return; + tag = tag_loaded('vehi', scorpion ? "vehicles\\scorpion\\scorpion_mp" : "vehicles\\warthog\\warthog"); + if (tag == NONE && scorpion) tag = tag_loaded('vehi', "vehicles\\scorpion\\scorpion"); + if (tag == NONE || unit == NONE) return; + object_placement_data_new(&placement, tag, NONE); + placement.position = capture_camera.position; + placement.position.x += capture_camera.forward.i * 4.0f; + placement.position.y += capture_camera.forward.j * 4.0f; + placement.position.z -= 0.5f; + placement.forward = capture_camera.forward; + placement.forward.k = 0; + normalize3d(&placement.forward); + observer_up_from_forward(&placement.forward, &placement.up); + vehicle = object_new(&placement); + capture_vehicle = vehicle; + if (vehicle != NONE) + { + unit_scripting_enter_vehicle(unit, vehicle, scorpion ? "scorpion-driver" : "W-gunner"); + platform_log("WARTHOG seat vehicle %ld parent %ld", vehicle, object_get(unit)->object.parent_object_index); + if (object_get(unit)->object.parent_object_index == vehicle) + platform_log("PLASMA combat equipped %s %ld", scorpion ? "Scorpion" : "Warthog", vehicle); + } + return; + } + tag = tag_loaded('weap', capture_kind() == 3 ? "weapons\\rocket launcher\\rocket launcher" : capture_kind() ? "weapons\\plasma pistol\\plasma pistol" : "weapons\\plasma rifle\\plasma rifle"); + if (getenv("HALO_MUZZLE_CAPTURE_WEAPON")) + tag = tag_loaded('weap', getenv("HALO_MUZZLE_CAPTURE_WEAPON")); + if (unit == NONE || tag == NONE) + platform_log("PLASMA combat unavailable unit %ld weapon tag %ld", unit, tag); + if (unit != NONE && tag != NONE && (!role || strncmp(role, "join", 4))) + { + long weapon; + if (role && !strncmp(role, "host", 4)) + { + struct data_iterator players; + struct player_datum *player; + data_iterator_new(&players, player_data); + while ((player = (struct player_datum *)data_iterator_next(&players)) != NULL) + if (player->unit_index != NONE && player->unit_index != unit) + { + real_point3d position = object_get(unit)->object.position; + position.x += capture_camera.forward.i * 4; + position.y += capture_camera.forward.j * 4; + object_set_position(player->unit_index, &position, NULL, NULL); + platform_log("PLASMA combat target %ld", player->unit_index); + } + } + unit_drop_current_weapon(unit, TRUE); + unit_drop_current_weapon(unit, TRUE); + object_placement_data_new(&placement, tag, NONE); + placement.position = capture_camera.position; + weapon = object_new(&placement); + if (weapon != NONE && unit_add_weapon_to_inventory(unit, weapon, TRUE)) + { + for (i = 0; i < MAXIMUM_WEAPONS_PER_UNIT; i++) + if (unit_inventory_get_weapon(unit, (short)i) == weapon) + player_control_set_desired_weapon(unit, (short)i); + platform_log("PLASMA combat equipped %ld tag %s", weapon, tag_get_name(tag)); + } + else + platform_log("PLASMA combat inventory rejected weapon %ld tag %s", weapon, tag_get_name(tag)); + } + } + if (capture_ticks == 70 && getenv("HALO_PLASMA_CAPTURE_DOOR")) + { + struct tag_iterator iterator; + tag_iterator_new(&iterator, 'mach'); + while ((tag = tag_iterator_next(&iterator)) != NONE) + if (strstr(tag_get_name(tag), "door")) + { + object_placement_data_new(&placement, tag, NONE); + placement.position = capture_camera.position; + placement.position.x += capture_camera.forward.i * 2.5f; + placement.position.y += capture_camera.forward.j * 2.5f; + placement.position.z -= 0.6f; + placement.forward = capture_camera.forward; + observer_up_from_forward(&placement.forward, &placement.up); + capture_door = object_new(&placement); + if (capture_door != NONE) + { + struct scenario_device_datum info; + info.power_group_index = info.position_group_index = NONE; + info.flags = 0; + device_add_scenario_information(capture_door, &info); + device_operates_automatically_set(capture_door, FALSE); + device_set_power(capture_door, 1); + device_set_actual_position(capture_door, 0); + } + platform_log("PLASMA door %ld tag %s", capture_door, tag_get_name(tag)); + break; + } + } + if (capture_door != NONE && object_try_and_get(capture_door) && capture_ticks % 30 == 0) + { + device_set_desired_position(capture_door, (capture_ticks / 30) % 2 ? 1.0f : 0.0f); + platform_log("PLASMA door position %.3f", device_get_position(capture_door)); + } + if (capture_toggle && capture_ticks >= 100 && capture_ticks <= 220 && capture_ticks % 10 == 0) + { + config_write_boolean("display.plasma_occlusion", (capture_ticks / 10) % 2); + platform_log("PLASMA toggle %d", config_boolean("display.plasma_occlusion")); + } + if (capture_combat) + return; + if (capture_ticks == 65 && capture_model) + { + tag = tag_loaded('bipd', "characters\\cyborg_mp\\cyborg_mp"); + if (tag == NONE) + tag = tag_loaded('bipd', "characters\\cyborg\\cyborg"); + if (tag != NONE) + { + object_placement_data_new(&placement, tag, NONE); + placement.position.x = + capture_camera.position.x + capture_receiver_distance * capture_camera.forward.i; + placement.position.y = + capture_camera.position.y + capture_receiver_distance * capture_camera.forward.j; + placement.position.z = capture_camera.position.z - 0.6f; + placement.forward = capture_camera.forward; + placement.forward.i = -placement.forward.i; + placement.forward.j = -placement.forward.j; + observer_up_from_forward(&placement.forward, &placement.up); + capture_target = object_new(&placement); + platform_log("PLASMA receiver model %ld tag %s", capture_target, tag_get_name(tag)); + } + else + platform_log("PLASMA receiver missing"); + } + for (bolt = 0; bolt < capture_burst; bolt++) + if (capture_probe && capture_bolts[bolt] != NONE && object_try_and_get(capture_bolts[bolt])) + { + real_point3d position; + real lateral = -capture_span + 2 * capture_span * (capture_ticks % 60 - 30) / 28.0f; + cross_product3d(&capture_camera.forward, &capture_camera.up, &right); + position.x = capture_camera.position.x + capture_distance * capture_camera.forward.i + + lateral * right.i + capture_height * capture_camera.up.i; + position.y = capture_camera.position.y + capture_distance * capture_camera.forward.j + + lateral * right.j + capture_height * capture_camera.up.j; + position.z = capture_camera.position.z + capture_distance * capture_camera.forward.k + + lateral * right.k + capture_height * capture_camera.up.k; + if (capture_ticks % 60 >= 59 || capture_ticks % 60 < 30) + { + object_delete(capture_bolts[bolt]); + capture_bolts[bolt] = NONE; + } + else + { + position.z += bolt * 0.025f; + object_set_position(capture_bolts[bolt], &position, NULL, NULL); + } + } + if (capture_ticks < 90 || capture_ticks > 210 || capture_ticks % 60 != 30) + return; + tag = tag_loaded(PROJECTILE_DEFINITION_TAG, capture_projectile_tags[capture_kind()]); + if (tag == NONE) + { + platform_log("PLASMA missing projectile tag"); + return; + } + cross_product3d(&capture_camera.forward, &capture_camera.up, &right); + object_placement_data_new(&placement, tag, NONE); + placement.position.x = capture_camera.position.x + capture_distance * capture_camera.forward.i - + (capture_probe ? capture_span : 1.2f) * right.i + + capture_height * capture_camera.up.i; + placement.position.y = capture_camera.position.y + capture_distance * capture_camera.forward.j - + (capture_probe ? capture_span : 1.2f) * right.j + + capture_height * capture_camera.up.j; + placement.position.z = capture_camera.position.z + capture_distance * capture_camera.forward.k - + (capture_probe ? capture_span : 1.2f) * right.k + + capture_height * capture_camera.up.k; + placement.forward = right; + placement.forward.k -= capture_option("HALO_PLASMA_CAPTURE_DROP", 0.12f); + normalize3d(&placement.forward); + observer_up_from_forward(&placement.forward, &placement.up); + for (bolt = 0; bolt < capture_burst; bolt++) + { + placement.position.z += 0.025f; + if (getenv("HALO_PLASMA_CAPTURE_MIXED")) + placement.definition_index = tag_loaded(PROJECTILE_DEFINITION_TAG, capture_projectile_tags[bolt % (capture_kind() == 3 ? 4 : 3)]); + capture_bolts[bolt] = object_new(&placement); + if (capture_bolts[bolt] != NONE && capture_target != NONE && (capture_kind() == 2 || capture_kind() == 4 || capture_kind() == 11) && !capture_probe) + { + projectile_set_target_object_index(capture_bolts[bolt], capture_target); + platform_log("PLASMA homing %ld target %ld", capture_bolts[bolt], capture_target); + } + } + capture_projectile = capture_bolts[0]; + platform_log("PLASMA shot tick %ld object %ld", capture_ticks, capture_projectile); + if (capture_projectile != NONE) + { + struct object_datum *object = object_get(capture_projectile); + struct object_definition *definition = object_definition_get(tag); + platform_log("PLASMA tag %s type %d nodes %ld flags %lx", tag_get_name(tag), object->object.type, object->object.node_matrices.size, object->object.flags); + if (capture_kind() == 3 || capture_kind() == 4 || capture_kind() == 10 || capture_kind() == 11) + { + long glow = light_port_glow_definition_get(); + if (glow != NONE) + { + long *light = tag_get('ligh', glow); + platform_log("PLASMA glow template %s flags %lx", tag_get_name(glow), light[0]); + } + } + for (i = 0; i < definition->object.attachments.count; i++) + { + struct object_attachment_definition *attachment = + TAG_BLOCK_GET_ELEMENT(&definition->object.attachments, i, struct object_attachment_definition); + if (attachment->type.group_tag == 'ligh' && attachment->type.index != NONE) + { + long *light = tag_get('ligh', attachment->type.index); + platform_log("PLASMA enabled %d light flags %lx radius %.4f", + config_boolean("display.plasma_lighting"), light[0], ((real *)light)[1]); + } + } + for (i = 0; i < MAXIMUM_NUMBER_OF_ATTACHMENTS_PER_OBJECT; i++) + platform_log("PLASMA attachment %ld type %d index %ld", i, object->object.attachment_types[i], + object->object.attachment_indices[i]); + } +} + +void plasma_capture_frame(void) +{ + long index, selected = 0; + real_matrix4x3 *matrix; + if (!game_in_progress() || game_time_menu_scene() || capture_ticks < 85 || capture_ticks > 240) + return; + platform_log("PLASMA draws model %lu specular %lu", capture_model_draws, capture_specular_draws); + capture_model_draws = capture_specular_draws = 0; + for (index = 0; index < rasterizer_lights.light_count; index++) + selected += plasma_lighting_selected(index); + if (capture_projectile != NONE && object_try_and_get(capture_projectile)) + { + matrix = object_get_node_matrix(capture_projectile, 0); + platform_log("PLASMA frame %lu tick %ld fraction %.5f position %.5f %.5f %.5f selected %ld", + GetTickCount(), capture_ticks, render_interpolation_fraction(), matrix->position.x, + matrix->position.y, matrix->position.z, selected); + } + else + platform_log("PLASMA frame %lu tick %ld no projectile selected %ld", GetTickCount(), capture_ticks, + selected); +} + +int plasma_capture_should_capture(void) +{ + static long shield_captured_tick = -1; + if (getenv("HALO_SHIELD_CAPTURE") || getenv("HALO_LIGHTING_CAPTURE_SPARSE")) + { + if (getenv("HALO_PLASMA_CAPTURE_NO_IMAGES") || capture_ticks < 85 || capture_ticks > 240 || + capture_ticks % (getenv("HALO_LIGHTING_CAPTURE_SPARSE") ? (int)capture_option("HALO_LIGHTING_CAPTURE_IMAGE_STEP", 3) : 5) || shield_captured_tick == capture_ticks) return FALSE; + shield_captured_tick = capture_ticks; + return TRUE; + } + return !getenv("HALO_PLASMA_CAPTURE_NO_IMAGES") && capture_ticks >= 85 && capture_ticks <= 240 && + ((capture_ticks % 60 >= 28 && capture_ticks % 60 <= 58) || + (getenv("HALO_EMITTER_CAPTURE_CROUCH") && capture_ticks >= 180 && capture_ticks < 200)); +} diff --git a/tools/fixtures/shader_prepare_check.c b/tools/fixtures/shader_prepare_check.c new file mode 100644 index 0000000000..b163ce65b2 --- /dev/null +++ b/tools/fixtures/shader_prepare_check.c @@ -0,0 +1,142 @@ +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#include +#else +#include +#endif +typedef unsigned int GLuint; +typedef int GLint; +typedef uint64_t Uint64; +typedef void (*PFNGLGETSHADERSOURCEPROC)(GLuint,GLint,GLint *,char *); +typedef void (*PFNGLDETACHSHADERPROC)(GLuint,GLuint); +#define GL_VERTEX_SHADER 1 +#define GL_FRAGMENT_SHADER 2 +#define GL_PROGRAM_BINARY_RETRIEVABLE_HINT 3 +#define GL_LINK_STATUS 4 +#define GL_SHADER_SOURCE_LENGTH 5 +#define GL_TRUE 1 +static char sources[4096][128]; +static unsigned next_id=10,deleted,compiled,linked,stored,loaded,polls,detached; +static int enabled=1,cached,failed,no_shader; +static int config_boolean(char const *key) {(void)key;return enabled;} +static char const *platform_save_root(void) {return ".";} +static void platform_log(char const *format,...) {(void)format;} +static void posix_make_directory(char const *path) { +#ifdef _WIN32 + _mkdir(path); +#else + mkdir(path,0700); +#endif +} +static void get_source(GLuint shader,GLint size,GLint *length,char *out) { + snprintf(out,size,"%s",sources[shader]);if(length)*length=(GLint)strlen(out); +} +static void detach_shader(GLuint program,GLuint shader) {(void)program;(void)shader;detached++;} +static void (*SDL_GL_GetProcAddress(char const *name))(void) { + return !strcmp(name,"glGetShaderSource") ? (void (*)(void))get_source : (void (*)(void))detach_shader; +} +static int SDL_GL_ExtensionSupported(char const *name) {(void)name;return 1;} +static Uint64 SDL_GetTicksNS(void) {static Uint64 now;return ++now;} +static void SDL_Delay(unsigned ms) {(void)ms;} +static GLuint glCreateShader(unsigned type) {(void)type;return no_shader ? 0 : ++next_id;} +static GLuint glCreateProgram(void) {return ++next_id;} +static void glDeleteProgram(GLuint id) {assert(id);deleted++;} +static void glDeleteShader(GLuint id) {(void)id;} +static void glShaderSource(GLuint shader,int count,char const *const *source,GLint const *length) { + (void)count;(void)length;snprintf(sources[shader],sizeof(sources[shader]),"%s",*source); +} +static void glCompileShader(GLuint shader) {(void)shader;compiled++;} +static void glAttachShader(GLuint program,GLuint shader) {(void)program;(void)shader;} +static void glProgramParameteri(GLuint program,unsigned name,int value) {(void)program;(void)name;(void)value;} +static void glLinkProgram(GLuint program) {(void)program;linked++;} +static void glGetProgramiv(GLuint program,unsigned name,GLint *value) { + (void)program; + if(name==GL_LINK_STATUS)*value=!failed; + else {*value=++polls>1;} +} +static void glGetShaderiv(GLuint shader,unsigned name,GLint *value) { + assert(name==GL_SHADER_SOURCE_LENGTH);*value=(GLint)strlen(sources[shader])+1; +} +#include "under_test.inc" +static unsigned load(shader_prepare_hash a,shader_prepare_hash b) {(void)a;(void)b;if(cached){loaded++;return glCreateProgram();}return 0;} +static void store(unsigned p,shader_prepare_hash a,shader_prepare_hash b) {(void)p;(void)a;(void)b;stored++;} +int main(int argc,char **argv) { + shader_prepare_hash a,b; + char path[512]; + GLuint program; + assert(argc==2); + strcpy(sources[1],"vertex source");strcpy(sources[2],"fragment source"); + a=prepare_hash(sources[1]);b=prepare_hash(sources[2]); + if(!strcmp(argv[1],"disabled")) { + enabled=0;shader_prepare_begin("custom_maps/a",load,store); + shader_prepare_record(1,2,a,b);assert(!prepare.active && !prepare.count && !compiled); + shader_prepare_end();return 0; + } + shader_prepare_begin("custom_maps/a",load,store); + shader_prepare_record(1,2,a,b);shader_prepare_record(1,2,a,b); + assert(prepare.count==1 && !compiled); + strcpy(path,prepare.path);shader_prepare_end(); + if(!strcmp(argv[1],"invalid")) { + FILE *file=fopen(path,"wb");fputs("truncated",file);fclose(file); + shader_prepare_begin("custom_maps/a",load,store); + assert(prepare.active && !prepare.count && !compiled); + shader_prepare_record(1,2,a,b);shader_prepare_end(); + shader_prepare_begin("custom_maps/a",load,store);assert(prepare.count==1 && linked==1); + } else if(!strncmp(argv[1],"malformed_",10)) { + FILE *file=fopen(path,"r+b"); + struct prepare_header header; + struct prepare_pair pair; + char const *kind=argv[1]+10; + assert(file && fread(&header,sizeof(header),1,file)==1 && fread(&pair,sizeof(pair),1,file)==1); + if(!strcmp(kind,"length")) { + pair.vertex_bytes=PREPARE_SOURCE+1; + fseek(file,sizeof(header),SEEK_SET);fwrite(&pair,sizeof(pair),1,file); + } else if(!strcmp(kind,"hash")) { + pair.vertex^=1; + fseek(file,sizeof(header),SEEK_SET);fwrite(&pair,sizeof(pair),1,file); + } else if(!strcmp(kind,"terminator")) { + fseek(file,sizeof(header)+sizeof(pair)+pair.vertex_bytes-1,SEEK_SET);fputc('x',file); + } else if(!strcmp(kind,"embedded_nul")) { + fseek(file,sizeof(header)+sizeof(pair),SEEK_SET);fputc(0,file); + } else if(!strcmp(kind,"trailing")) { + fseek(file,0,SEEK_END);fputc('x',file); + } else if(!strcmp(kind,"duplicate")) { + header.count=2;fseek(file,0,SEEK_SET);fwrite(&header,sizeof(header),1,file); + fseek(file,0,SEEK_END);fwrite(&pair,sizeof(pair),1,file); + fwrite(sources[1],pair.vertex_bytes,1,file);fwrite(sources[2],pair.fragment_bytes,1,file); + } else assert(0); + fclose(file);shader_prepare_begin("custom_maps/a",load,store); + assert(prepare.active && !prepare.count && !compiled && !linked); + } else if(!strcmp(argv[1],"ownership")) { + shader_prepare_begin("custom_maps/a",load,store); + assert(prepare.count==1 && compiled==2 && linked==1 && stored==1 && detached==2); + program=shader_prepare_take(a,b);assert(program && !shader_prepare_take(a,b)); + shader_prepare_end();assert(!deleted);glDeleteProgram(program); + shader_prepare_begin("mcc_maps/a",load,store);assert(!prepare.count); + } else if(!strcmp(argv[1],"cached")) { + cached=1;shader_prepare_begin("custom_maps/a",load,store); + assert(loaded==1 && !compiled && !linked && !stored); + shader_prepare_end();assert(deleted==1); + } else if(!strcmp(argv[1],"failed")) { + failed=1;shader_prepare_begin("custom_maps/a",load,store); + assert(linked==1 && !stored && !shader_prepare_take(a,b) && deleted==1); + } else if(!strcmp(argv[1],"allocation")) { + no_shader=1;shader_prepare_begin("custom_maps/a",load,store); + assert(!linked && !stored && !polls && !shader_prepare_take(a,b) && deleted==1); + } else if(!strcmp(argv[1],"bounds")) { + FILE *file=fopen(path,"wb");struct prepare_header header={PREPARE_MAGIC,PREPARE_COUNT+1,prepare_hash("custom_maps/a")}; + fwrite(&header,sizeof(header),1,file);fclose(file); + shader_prepare_begin("custom_maps/a",load,store);assert(!prepare.count && !compiled); + prepare.bytes=PREPARE_BYTES;shader_prepare_record(1,2,a,b);assert(!prepare.count); + } else if(!strcmp(argv[1],"toggle")) { + shader_prepare_begin("custom_maps/a",load,store); + enabled=0;shader_prepare_begin("custom_maps/b",load,store); + assert(!shader_prepare_take(a,b) && !prepare.active && deleted==1); + } else assert(0); + shader_prepare_end();return 0; +} diff --git a/tools/fixtures/shield_glow_test.c b/tools/fixtures/shield_glow_test.c new file mode 100644 index 0000000000..ad87df49ae --- /dev/null +++ b/tools/fixtures/shield_glow_test.c @@ -0,0 +1,122 @@ +/* A fake rendered world exercising the complete shield light implementation. */ +#include +#include +#include +#pragma clang diagnostic ignored "-Wunused-parameter" +#pragma clang diagnostic ignored "-Wunused-function" +typedef int boolean; +typedef float real; +typedef unsigned char byte; +typedef struct {real red,green,blue;} real_rgb_color; +typedef struct {real x,y,z;} real_point3d; +typedef struct {real i,j,k;} real_vector3d; +typedef struct {real_point3d position;} real_matrix4x3; +#define TRUE 1 +#define FALSE 0 +#define NONE (-1) +#define MAX(a,b) ((a)>(b)?(a):(b)) +#define MIN(a,b) ((a)<(b)?(a):(b)) +#define PIN(a,b,c) MIN(MAX(a,b),c) +#define TEST_FLAG(a,b) ((a)&(1<<(b))) +#define _object_invisible_bit 0 +#define _object_dead_bit 0 +#define _object_mask_unit 1 +#define CHECK(x) do {if (!(x)) {printf("line %d\n",__LINE__);return 1;}} while(0) +static real_rgb_color black={0,0,0}, white={1,1,1}; +static real_rgb_color const *global_real_rgb_black=&black,*global_real_rgb_white=&white; +static real_vector3d forward={1,0,0}; +static real_vector3d const *global_forward3d=&forward; +struct object_fields {unsigned flags,damage_flags;real_point3d bounding_sphere_center;real outgoing_function_values[4];real_rgb_color outgoing_change_colors[4];struct{int size;}node_matrices;}; +struct object_datum {long definition_index;struct object_fields object;}; +struct unit_datum {long definition_index;struct object_fields object;struct{real active_camouflage;}unit;}; +static struct unit_datum units[12]; +static real_matrix4x3 poses[12][2]; +struct object_definition {struct{struct{long index;}modifier_shader;}object;}; +static struct object_definition definition; +struct shader {struct{int type;}base;}; +struct render_model_effect {struct shader *modifier_shader;struct{real const *values;real_rgb_color const *colors;}modifier_animation;}; +struct observer_result {real_point3d position;}; +static struct observer_result camera; +struct object_iterator {long index;}; +static int unit_count=1,on=1,selected_look,os; +static short policy=NONE; +static real clock_time,coverage=1; +static unsigned long changes; +static int allocations,deletions,disconnects,submissions,resets; +static int valid_lights[128]; +static real_rgb_color last_color[128]; +static real_point3d last_position[128]; +static real last_radius[128]; +static char const *intensity="default"; +int config_boolean(char const *name){return on;} +char const *config_string(char const *name){return intensity;} +unsigned long config_changes(void){return changes;} +static short network_shield_effects(void){return policy;} +static void overshield_effect_reset(void){resets++;} +static real render_interpolation_game_time_sec(long t){return clock_time;} +static long game_time_get(void){return (long)(clock_time*30);} +static long light_port_glow_definition_get(void){return 9;} +static boolean light_port_glow_set(long l,long o,real_rgb_color const *c,real r){if(l<0||l>=128||!valid_lights[l])return 0;last_color[l]=*c;last_radius[l]=r;return 1;} +static boolean light_port_glow_move(long l,real_point3d const *p){if(l<0||l>=128||!valid_lights[l])return 0;last_position[l]=*p;return 1;} +static long light_new_unattached(long d,long o,int n,real_point3d const *p,real_vector3d const *f,real t){int l=++allocations;valid_lights[l]=1;return l;} +static void light_delete(long l){valid_lights[l]=0;deletions++;} +static void light_disconnect_from_map(long l){disconnects++;} +static void plasma_occlusion_submit(long l,long r){submissions++;} +static void object_iterator_new(struct object_iterator *i,int mask,int f){i->index=-1;} +static int object_iterator_next(struct object_iterator *i){return ++i->index=0&&ix-b->x,y=a->y-b->y,z=a->z-b->z;return (real)sqrt(x*x+y*y+z*z);} +static int valid_real(real x){return isfinite(x);} +static struct shader *shader_definition_get(long i); +static struct shader *shield_look_body(long i,struct shader *s); +static boolean shield_look_colors(struct shader const *s,real_rgb_color const *c,real_rgb_color *a,real_rgb_color *b){return 0;} +static void shield_recharge_prepare(long i,struct render_model_effect const *e,boolean a){} +static void shield_recharge_draw(struct shader const *s,real const *v,real *i,real *o){} +static boolean overshield_effect_light_sample(long i,real_rgb_color *c,real *v){if(!os)return 0;*v=coverage;c->red=os==1?.306f:.992f;c->green=os==1?.992f:.306f;c->blue=.455f;return 1;} +#include "shield_under_test.inc" +static struct {struct shader shader;struct shield_glow_plasma plasma;} original, appearance; +static struct shader *shader_definition_get(long i){return &original.shader;} +static struct shader *shield_look_body(long i,struct shader *s){return selected_look?&appearance.shader:s;} +static int close_to(real a,real b){return fabs(a-b)<.0001;} +int main(void) +{ + int i,rate,step;real result[3];long light;struct shield_glow_sample sample; + original.shader.base.type=appearance.shader.base.type=10; + original.plasma.intensity_exponent_source=appearance.plasma.intensity_exponent_source=1; + original.plasma.intensity_exponent=appearance.plasma.intensity_exponent=1; + original.plasma.perpendicular_color=white; + appearance.plasma.perpendicular_color.red=.2f;appearance.plasma.perpendicular_color.green=.4f;appearance.plasma.perpendicular_color.blue=1; + for(i=0;i<12;i++){units[i].object.node_matrices.size=sizeof(poses[i]);poses[i][1].position.z=.9f;units[i].object.outgoing_function_values[0]=1;units[i].object.outgoing_change_colors[0]=white;units[i].object.bounding_sphere_center.x=20-i;} + shield_glow_reset();shield_glow_update();CHECK(allocations==1); + light=shield_glows[0].light_index;CHECK(last_radius[light]>1&&close_to(last_position[light].z,.45f)); + shield_glow_submitted(light,3);CHECK(shield_glow_selected(3)&&submissions==1); + shield_glow_frame_end();CHECK(disconnects==1&&!shield_glow_selected(3)&&last_radius[light]==0); + selected_look=1;clock_time+=.1f;shield_glow_update();CHECK(last_color[light].blue>last_color[light].red); + os=1;shield_glow_update();CHECK(last_color[light].green>last_color[light].red); + os=2;shield_glow_update();CHECK(last_color[light].red>last_color[light].green); + coverage=.2f;CHECK(shield_glow_sample(0,&sample)&&close_to(sample.position.z,.09f)); + os=0;selected_look=0;original.plasma.color_source=1;units[0].object.outgoing_change_colors[0].green=.1f; + CHECK(shield_glow_sample(0,&sample)&&sample.color.greenlight_index;shield_glow_update();CHECK(shield_glow_find(11)->light_index==light); + on=0;changes++;shield_glow_update();for(i=0;i<8;i++)CHECK(shield_glows[i].unit_index==NONE); + policy=_shield_effects_glow;CHECK(shield_glow_enabled());shield_glow_update();CHECK(shield_glow_find(11)); + policy=_shield_effects_stock;on=1;changes++;shield_glow_frame_end();CHECK(!shield_glow_enabled()&&!shield_glow_find(11)); + shield_glow_reset();CHECK(resets>0);return 0; +} diff --git a/tools/frontend_legacy.py b/tools/frontend_legacy.py new file mode 100644 index 0000000000..b504898845 --- /dev/null +++ b/tools/frontend_legacy.py @@ -0,0 +1,92 @@ +"""Xbox-only footer instances over the existing settings services. + +The original definitions and callbacks stay intact. Glyphs use the native map +bitmaps when present, with the existing Xbox redraws for gameplay caches. +""" +from copy import deepcopy +import json +import xml.etree.ElementTree as ET + +from frontend_multiplayer import ROOT, inventory + + +def append(doc): + routes = [] + for name, original in inventory().items(): + leaf = name.rsplit('/', 1)[-1] + if not (name.startswith('main_menu/settings_select/player_setup/player_profile_edit/') + or name in ('common_button_cancel', 'common_button_back')): + continue + kind = {'button_defaults': ('x', '=DEFAULTS'), 'button_ok': ('a', '=OK'), + 'common_button_cancel': ('b', '=CANCEL'), 'common_button_back': ('b', '=BACK')}.get(leaf) + if not kind: + continue + glyph, caption = kind + replacement = 'frontend_legacy/footer/' + name + widget = deepcopy(original) + for key in ('bitmap', 'string_list', 'strings', 'string_index'): + widget.attrib.pop(key, None) + widget.attrib.update(name=replacement, text=caption, height='28', + font='ui\\large_ui', color='#FF2896FF', align='left', text_x='22', text_y='0') + if leaf == 'button_defaults': + widget.set('width', '180') + doc.append(widget) + routes.append((name, replacement, glyph)) + for glyph in ('a', 'b', 'x'): + ET.SubElement(doc, 'widget', name='frontend_legacy/footer_glyph_' + glyph, + controller='1', width='21', height='26', bitmap='ui\\shell\\bitmaps\\' + glyph + '_butn') + ET.SubElement(doc, 'widget', name='frontend_legacy/footer_glyph_' + glyph + '_fallback', + controller='1', width='21', height='26', bitmap='frontend_legacy/glyph_' + glyph) + bitmap = ET.SubElement(doc, 'bitmap', name='frontend_legacy/glyph_' + glyph) + ET.SubElement(bitmap, 'frame', png='modern/xbox_' + glyph + '.png', width='21', height='26') + # Gameplay caches need not contain the main-menu Xbox profile screen. + # A feature-owned entry keeps its layout and delegates to trusted editors. + base = 'frontend_legacy/paused/' + profile = 'main_menu/settings_select/player_setup/player_profile_edit/' + screen = ET.SubElement(doc, 'widget', name=base+'settings', width='640', height='480', + bitmap='bitmaps/gradient', flags='pass_unhandled_to_focused_child pause_game') + for event in ('b', 'back'): + ET.SubElement(screen, 'on', event=event, run='player profile end editing', back='true') + ET.SubElement(screen, 'child', widget=profile+'header_profile_settings') + ET.SubElement(screen, 'child', widget=base+'options') + ET.SubElement(screen, 'child', widget=base+'back', x='440', y='414') + footer = ET.SubElement(doc, 'widget', name=base+'back', type='text', controller='1', + width='160', height='28', text='=BACK', text_x='22', + font='ui\\large_ui', color='#FF2896FF') + ET.SubElement(footer, 'child', widget='frontend_legacy/footer_glyph_b') + options = ET.SubElement(doc, 'widget', name=base+'options', type='column_list', width='640', height='480', + flags='pass_unhandled_to_focused_child up_down_tabs_items') + for index, (caption, target) in enumerate(( + ('CONTROLLER SETUP', 'gamepad_setup/gamepad_setup_screen'), + ('KEYBOARD BINDINGS', 'controls_setup/controls_settings_screen'), + ('MOUSE SETUP', 'mouse_settings/mouse_settings_screen'), + ('AUDIO SETUP', 'audio_settings/audio_settings_screen'), + ('VIDEO SETUP', 'video_settings/video_settings_screen'), + ('NETWORK SETUP', 'network_setup/in_game/in_game_network_settings_screen'), + ('CONTROLLER REMAPPING', 'controller_remapping/controller_remapping_screen'), + ('BUTTON GLYPHS', 'controller_appearance/controller_appearance_screen'))): + key = base+'row_'+str(index) + ET.SubElement(options, 'child', widget=key) + row = ET.SubElement(doc, 'widget', name=key, type='text', left='64', top=str(78+33*index), + width='512', height='30', bitmap='bitmaps/list_item_bkd', text=caption, + font='ui\\large_ui', color='#FF2896FF', text_x='13', text_y='5') + for event in ('a','start'): + ET.SubElement(row, 'on', event=event, open=profile+target) + ET.SubElement(row, 'on', event='left_mouse', run='mouse emit accept event') + return routes + + +def copy_art(target): + for glyph in ('a', 'b', 'x'): + (target / ('xbox_' + glyph + '.png')).write_bytes( + (ROOT / 'port/assets/buttons' / (glyph + '_butn__0.png')).read_bytes()) + + +def write_metadata(routes): + text = '/* Generated by tools/frontend_menu.py. Xbox-only footer replacements. */\n' + text += 'static struct { char const *native, *replacement, *glyph; } const frontend_legacy_footers[] = {\n' + for native, replacement, glyph in routes: + text += ' {' + ', '.join(json.dumps('pc\\' + path.replace('/', '\\')) + for path in (native, replacement, 'frontend_legacy/footer_glyph_' + glyph)) + '},\n' + text += '};\n' + (ROOT / 'port/linux/game/frontend_legacy_footers.inl').write_text(text, encoding='utf-8') diff --git a/tools/frontend_menu.py b/tools/frontend_menu.py new file mode 100644 index 0000000000..d52e6bd3fc --- /dev/null +++ b/tools/frontend_menu.py @@ -0,0 +1,300 @@ +"""Generate GulchCE's opt-in Settings frontend; never rewrite CE menus. + +Layout inspiration: OpenH1/OpenH1 df16d2e56c3b69be46f964f741a23fd2d3b4f57a. +Original GulchCE implementation and geometric art; no upstream code/assets copied. +""" +import json +from copy import deepcopy +from pathlib import Path +import xml.etree.ElementTree as ET + +from PIL import Image, ImageDraw, ImageFont + +ROOT = Path(__file__).resolve().parents[1] +MENUS = ROOT / "port/assets/menus" +BASE = "modern" +# Reuse the maintained setting inventory, without changing the CE generator. +from port_settings import SCREENS +import frontend_navigation +import frontend_multiplayer +import frontend_legacy +import mcc_xbox_menu + +# Each page: key, tab, parent, heading, source inventories. Page zero is the +# stable entry tag used by the main-menu policy. +PAGES = [ + ("", 0, 0, "DISPLAY", ["video_settings"]), + ("audio", 1, 1, "AUDIO", ["audio_settings", "audio_settings/sound_processing"]), + ("controls", 2, 2, "MOUSE AND KEYBOARD", ["mouse_settings"]), + ("online", 3, 3, "ONLINE", ["network_setup"]), + ("interface", 4, 4, "INTERFACE", ["controller_appearance"]), + ("profile", 5, 5, "PLAYER PROFILE", ["gamepad_setup"]), + ("graphics", 0, 0, "ADVANCED GRAPHICS", ["video_settings/graphics"]), + ("first_person", 0, 0, "FIRST PERSON", ["video_settings/fov_viewmodels"]), + ("lighting", 0, 6, "LIGHTING AND SHIELDS", ["video_settings/dynamic_lighting"]), + ("bots", 3, 3, "BOTS", ["network_setup/bots"]), + ("sharing", 3, 3, "MAP SHARING", ["network_setup/map_sharing"]), + ("browser", 3, 3, "SERVER BROWSER", ["network_setup/server_browser"]), + ("hud", 4, 4, "MULTIPLAYER HUD", ["network_setup/multiplayer_hud"]), + ("streamer", 4, 4, "STREAMER MODE", ["network_setup/streamer_mode"]), + ("touch", 2, 2, "TOUCH CONTROLS", ["gamepad_setup/android", "gamepad_setup/gyro"]), + ("third_person", 0, 0, "THIRD PERSON", ["video_settings/shoulder_camera"]), + ("extra_effects", 0, 6, "EXTRA EFFECTS", ["video_settings/extra_effects"]), + ("mcc_packages", 3, 10, "MCC PACKAGES", ["network_setup/mcc_packages"]), +] +TABS = ("VIDEO", "AUDIO", "CONTROLS", "ONLINE", "INTERFACE", "PROFILE") +LINKS = {0: [(6, None), (7, None), (15, None)], 6: [(8, "desktop web"), (16, None)], + 3: [(9, None), (10, None), (11, None)], 4: [(12, None), (13, None)], + 2: [(14, "android")], 10: [(17, None)]} +STYLE = ("MENU STYLE", "display.menu_frontend", + [("MODERN", "modern"), ("CLASSIC PC", "pc"), ("XBOX", "xbox"), ("STOCK", "off")], + "Choose the Settings and submenu style. Saved changes take effect on return to the main menu. The starting menu, pause menu and map UI keep their existing layout.", None) +INTERFACE_RENDERING = ("display.high_res_text", "display.high_res_hud") +EDITORS = { + 3: [("discord", "DISCORD ACCOUNT", "Manage account linking in its existing editor. That editor's OK saves changes independently of these Settings.")], + 10: [("mcc_downloads", "MCC DOWNLOADS", "View storage and remove copies received from hosts. Original packages and saves are kept.")], + 2: [("keyboard", "KEYBOARD BINDINGS", "Set the base game's keyboard and mouse bindings in its existing editor. That editor's OK saves bindings independently of these Settings."), + ("dead_zones", "STICK DEAD ZONES", "Adjust each stick's dead zone in its existing editor. That editor's OK saves changes independently of these Settings."), + ("gamepad", "CONTROLLER REMAPPING", "Remap each player's controller. Camera Perspective binds third-person toggling and shoulder swapping. The editor's OK saves bindings independently of these Settings.")], + 5: [("profiles", "SELECT PROFILE", "Select or create a player profile using the existing profile manager. Save or cancel any profile edits before changing profiles."), + ("name", "PLAYER NAME", "Edit the selected profile's name. Settings OK saves the profile; Cancel discards its pending changes."), + ("color", "PLAYER COLOR", "Edit the selected profile's multiplayer color. Settings OK saves the profile; Cancel discards its pending changes.")], +} + +# The stock UI fonts have very different widths. Measure against the narrowest +# supported layout so captions never run into arrows at 4:3. +# Keep the original Windows generator's basic layout on runners that also +# provide RAQM. Its optional shaping backend otherwise changes title pixels. +FONTS = {size: ImageFont.truetype(str(ROOT / "port/assets/fonts" / file), 128, layout_engine=ImageFont.Layout.BASIC) + for size, file in ((13, "Overpass-900.ttf"), (10, "Overpass-750.ttf"))} + +def text_width(value, size): + font = FONTS[size] + box = font.getbbox("H") + return font.getlength(value) * size / (box[3] - box[1]) * .98 + +def value_caption(value): + if text_width(value, 10) <= 136: return value + while value and text_width(value + "...", 10) > 136: value = value[:-1] + return value.rstrip() + "..." + +SHORT_LABELS = { + "network.mcc_map_share": "SHARE MCC MAPS", + "display.plasma_prong_lighting": "PLASMA PRONGS", + "display.widescreen_loading": "WIDE LOADING", + "input.mouse_sensitivity": "HORIZONTAL SENS.", "input.mouse_vertical_sensitivity": "VERTICAL SENS.", + "input.invert_mouse": "INVERT MOUSE", "network.allow_upnp": "UPNP FORWARDING", + "network.join_from_clipboard": "CLIPBOARD INVITES", "input.auto_button_detection": "AUTO DETECTION", + "display.passenger_third_person": "PASSENGER VIEW", "display.muzzle_lighting": "MUZZLE LIGHTS", + "network.browser_show_empty": "EMPTY SERVERS", "display.scoreboard_team_layout": "SCOREBOARD STYLE", + "input.gyro_sensitivity_horizontal": "HORIZONTAL SENS.", "input.gyro_sensitivity_vertical": "VERTICAL SENS.", + "display.menu_button_glyphs": "STOCK MENU GLYPHS", + "display.hud_button_style": "MANUAL STYLE", "display.hud_button_style_xbox": "XBOX STYLE", + "display.hud_button_style_ps": "PLAYSTATION STYLE", "display.hud_button_style_switch": "SWITCH STYLE", +} + +def page_base(index): + return "modern" + ("/" + PAGES[index][0] if PAGES[index][0] else "") + + +def document(): + doc = ET.Element("menus") + def widget(path, **attrs): + return ET.SubElement(doc, "widget", name=path, **{k: str(v) for k, v in attrs.items() if v is not None}) + def child(parent, path, x=0, y=0, platform=None): + attrs = dict(widget=path, x=str(x), y=str(y)) + if platform: attrs["platform"] = platform + ET.SubElement(parent, "child", **attrs) + def event(parent, key, callback): + ET.SubElement(parent, "on", event=key, run=callback) + def activate(parent, callback): + for key in ("a", "start"): event(parent, key, callback) + event(parent, "left_mouse", "mouse emit accept event") + def text(path, value, width, height=24, **attrs): + return widget(path, type="text", text=value, width=width, height=height, + font="ui\\large_ui", color="#FF2896FF", **attrs) + def strings(path, values): + node = ET.SubElement(doc, "strings", name=path) + for value in values: + ET.SubElement(node, "string", text=" ".join(value.split())) + + for page, (_, tab, parent, heading, inventories) in enumerate(PAGES): + base = page_base(page) + w = lambda name, **attrs: widget(base + "/" + name, **attrs) + c = lambda node, name, *args, **attrs: child(node, base + "/" + name, *args, **attrs) + screen = w("settings", width=640, height=480, bitmap="modern/panel", flags="pass_unhandled_to_focused_child") + ET.SubElement(screen, "on", event="created", run="main menu intialize", label="ring_loop") + event(screen, "created", "port frontend init") + for key in ("b", "back"): event(screen, key, "port frontend back") + event(screen, "y", "port frontend next tab") + for name, x, y in (("title",70,40), ("section",32,108), ("rule_display",28,130), + ("help_panel",380,106), ("options",0,0), ("help_title",396,119), + ("help_value",396,138), ("status",28,389), ("prompts",28,450)): + c(screen, name, x, y) + w("title", width=200, height=28, bitmap="modern/title", controller=1) + text(base+"/section", heading,336,controller=1).set("color", "#FF80A2C0") + w("rule_display",width=336,height=1,bitmap="modern/rule",controller=1) + w("help_panel",width=232,height=294,bitmap="modern/help_panel",controller=1,flags="nifty_fx") + w("help_title",type="text",controller=1,width=200,height=22,string_list=base+"/labels",font="ui\\large_ui",color="#FF80A2C0") + w("help_value",type="text",controller=1,width=200,height=46,font="ui\\large_ui",color="#FFDDDDDD") + w("status",type="text",controller=1,width=336,height=20,font="ui\\small_ui",color="#FF80A2C0") + text(base+"/prompts"," ",580,22).set("font","ui\\small_ui") + w("help",type="text",controller=1,left=396,top=193,width=200,height=194,string_list=base+"/help_strings",font="ui\\large_ui",color="#FF2896FF") + options=w("options",type="column_list",width=640,height=480,flags="pass_unhandled_to_focused_child up_down_tabs_children",description=base+"/help") + ET.SubElement(options,"data",input="port frontend update") + c(options,"tabs",28,76) + tabs=w("tabs",type="column_list",width=584,height=26,flags="pass_unhandled_to_focused_child left_right_tabs_items") + for number, caption in enumerate(TABS): + c(tabs,f"tab_{number}",number*98) + button=text(base+f"/tab_{number}",caption,94,26,align="center",text_y=3, + bitmap="modern/tab" if number==tab else None,flags="nifty_fx") + # Six tabs fit 4:3 without reducing the approved control height. + button.set("font","ui\\small_ui") + activate(button,"port frontend page") + rows=[] + if page==15: + rows.append(next(row for row in SCREENS["video_settings/fov_viewmodels"]["rows"] if row[1]=="display.third_person")) + if page==4: + rows.append(STYLE) + rows.extend(next(row for row in SCREENS["video_settings/graphics"]["rows"] if row[1] == key) + for key in INTERFACE_RENDERING) + for inventory in inventories: + rows.extend(row for row in SCREENS[inventory]["rows"] if row[1] not in (*INTERFACE_RENDERING, "display.menu_frontend", "display.third_person")) + # Labels/help are local to each page; dynamic spinner captions come from + # the real instance, including enumerated monitors and audio devices. + labels=[]; helps=["OK saves pending settings across pages. Defaults resets this page. Cancel discards pending settings. Tab or Y changes tabs."] + for index, (label, setting, choices, help_text, platform, *_) in enumerate(rows): + key = "style" if setting=="display.menu_frontend" else setting.replace(".","_")+str(index) + if setting == "display.detected_button_style": key = "detected_button_style" + label = SHORT_LABELS.get(setting, label).rstrip(":") + if setting == "input.auto_button_detection" or setting.startswith("display.hud_button_style"): + help_text = help_text.replace("Requires High-Res HUD in Graphics.", "Keyboard and controller glyphs require High-Res HUD.").replace("Requires High-Res HUD.", "Keyboard and controller glyphs require High-Res HUD.") + labels.append(label.rstrip(":")); helps.append(help_text) + c(options,f"row_{key}",28,137+index*30,platform=platform) + row=w(f"row_{key}",width=336,height=26,bitmap="modern/row",platform=platform,flags="pass_unhandled_to_focused_child nifty_fx") + wide_value = setting == "display.shield_look" + value_width = 198 if wide_value else 140 + c(row,f"label_{key}",12,3); c(row,f"spinner_{key}",122 if wide_value else 180,3) + w(f"label_{key}",type="text",controller=1,width=94 if wide_value else 152,height=24,string_list=base+"/labels",string_index=index,font="ui\\large_ui",color="#FF2896FF") + + if choices is None: + row.remove(row.findall("child")[1]) + if setting == "display.detected_button_style": + # A display-only row must never save over the manual preference. + c(row,"detected_button_style_value",180,3) + w("detected_button_style_value",type="text",text="KEYBOARD",controller=1,width=140,height=20,font="ui\\large_ui",color="#FFDDDDDD",align="center") + else: + # Reuse the existing read-only master-server status service. + c(row,"master_servers_value",180,3) + w("master_servers_value",type="text",controller=1,width=140,height=20,font="ui\\large_ui",color="#FFDDDDDD",align="center") + continue + spinner=w(f"spinner_{key}",type="spinner",width=value_width,height=20,flags="pass_unhandled_to_focused_child left_right_tabs_items", + strings="|".join(caption if wide_value else value_caption(caption) for caption,_ in choices),values="|".join(value for _,value in choices),setting=setting, + font="ui\\large_ui",color="#FF2896FF",align="center", + header_bitmap="bitmaps/arrow_sm_left",footer_bitmap="bitmaps/arrow_sm_right",header_bounds="4 -10 16 -4",footer_bounds=f"4 {value_width+4} 16 {value_width+10}") + event(spinner,"created","port setting load") + actions=[(f"link_{target}",PAGES[target][3]+" >",f"Open {PAGES[target][3].lower()} settings. Pending changes stay until OK or Cancel.",platform,"port frontend page") for target,platform in LINKS.get(page,[])] + actions += [(key,caption+" >",help_text,None,"port frontend editor") for key,caption,help_text in EDITORS.get(page,[])] + if page>=6: actions.append((f"link_{parent}","< BACK","Return to the parent page, keeping pending changes.",None,"port frontend page")) + for key,label,help_text,platform,callback in actions: + index=len(labels); labels.append(label); helps.append(help_text) + c(options,"row_"+key,28,137+index*30,platform=platform) + row=w("row_"+key,width=336,height=26,bitmap="modern/row",platform=platform,flags="nifty_fx") + activate(row,callback) + c(row,"label_"+key,12,3) + w("label_"+key,type="text",controller=1,width=312,height=24,string_list=base+"/labels",string_index=index,font="ui\\large_ui",color="#FF2896FF") + strings(base+"/labels",labels); strings(base+"/help_strings",helps) + c(options,"button_bar",26,414) + bar=w("button_bar",type="column_list",width=588,height=26,flags="pass_unhandled_to_focused_child left_right_tabs_items") + for key,caption,x in (("defaults","DEFAULTS",0),("apply","OK",332),("cancel","CANCEL",462)): + c(bar,"button_"+key,x) + button=text(base+"/button_"+key,caption,124,26,align="center",text_y=3,bitmap="modern/button",flags="nifty_fx") + activate(button,"port frontend "+key) + paused = deepcopy(screen) + paused.set("name", screen.get("name").replace("modern/", "modern/paused/", 1)) + paused.set("flags", paused.get("flags") + " pause_game") + for handler in list(paused.findall("on")): + if handler.get("run") == "main menu intialize": paused.remove(handler) + doc.append(paused) + frontend_navigation.append(doc) + frontend_navigation.append_legacy(doc) + frontend_legacy.append(doc) + mcc_xbox_menu.append(doc) + frontend_multiplayer.append(doc) + for name,width,height in ART: + bitmap=ET.SubElement(doc,"bitmap",name="modern/"+name) + for frame in range(1 if name in ("panel","help_panel","rule") or name.startswith("title") else 2): + ET.SubElement(bitmap,"frame",png=f"modern/{name}_{frame}.png",width=str(width),height=str(height)) + ET.indent(doc,space="\t") + return ET.tostring(doc,encoding="unicode")+"\n" + + +ART = (("panel", 640, 480), ("help_panel", 232, 294), ("row", 336, 26), + ("button", 124, 26), ("tab", 94, 26), ("title", 200, 28), ("rule", 336, 1), + ("title_multiplayer", 300, 28), ("title_host", 300, 28)) + tuple( + (name, 300, 28) for name in frontend_multiplayer.TITLES) + + +def generate(folder=MENUS): + target = folder / "modern" + target.mkdir(parents=True, exist_ok=True) + frontend_legacy.copy_art(target) + mcc_xbox_menu.generate_art(target) + (target / "settings.xml").write_text('\n\n' + document(), encoding="utf-8") + if Path(folder).resolve() == MENUS.resolve(): + frontend_multiplayer.write_metadata(*frontend_multiplayer.append(ET.Element("menus"))) + frontend_legacy.write_metadata(frontend_legacy.append(ET.Element("menus"))) + for name, width, height in ART: + for frame in range(1 if name in ("panel", "help_panel", "rule") or name.startswith("title") else 2): + # Four samples per menu unit keep the native renderer's outlines smooth. + scale = 4 + image = Image.new("RGBA", (width * scale, height * scale), (0, 0, 0, 0)) + draw = ImageDraw.Draw(image) + blue = (40, 150, 255, 255) + def box(bounds, **kwargs): + draw.rectangle(tuple(round(v * scale) for v in bounds), **kwargs) + def rounded(bounds, radius, **kwargs): + draw.rounded_rectangle(tuple(round(v * scale) for v in bounds), round(radius * scale), **kwargs) + if name == "panel": + for y in range(70, 410): + alpha = round(172 - 85 * (y - 70) / 340) + box((0, y, width, y + 1), fill=(0, 20, 46, alpha)) + box((0, 410, width, 444), fill=(0, 0, 0, 175)) + box((0, 70, width, 70.5), fill=blue) + box((0, 410, width, 410.5), fill=blue) + elif name.startswith("title"): + font = ImageFont.truetype(str(ROOT / "port/assets/fonts/OpenCE-Regular.ttf"), 128, layout_engine=ImageFont.Layout.BASIC) + caption = "SETTINGS" if name == "title" else frontend_multiplayer.TITLES[name] if name in frontend_multiplayer.TITLES else frontend_navigation.SCREENS[name[6:]][0] + bounds = font.getbbox(caption) + ink = Image.new("RGBA", (bounds[2] - bounds[0], bounds[3] - bounds[1]), (0, 0, 0, 0)) + ImageDraw.Draw(ink).text((-bounds[0], -bounds[1]), caption, font=font, fill=blue) + title_width = 184 if name == "title" else min(width, round(22 * ink.width / ink.height)) + ink = ink.resize((title_width * scale, 22 * scale), Image.Resampling.LANCZOS) + image.alpha_composite(ink, (0, 4 * scale)) + elif name == "rule": + box((0, 0, width, 1), fill=(35, 90, 140, 255)) + elif name == "help_panel": + rounded((1, 1, width - 1, height - 1), 10, fill=(0, 12, 30, 225), outline=blue, width=2 * scale) + elif name in ("button", "tab") or frame: + rounded((1, 1, width - 1, height - 1), 12, fill=(3, 35, 65, 220), outline=blue, width=2 * scale) + if name == "button" and frame: + rounded((2, 2, width - 2, height - 2), 11, outline=(166, 218, 255, 255), width=scale) + image.save(target / f"{name}_{frame}.png") + manifest = folder / "menus.json" + data = json.loads(manifest.read_text(encoding="utf-8")) + files = [name for name in data["files"] if not name.startswith("modern/")] + data["files"] = files + sorted(path.relative_to(folder).as_posix() for path in target.iterdir() + if path.suffix in (".xml", ".png")) + manifest.write_text(json.dumps(data, indent=1) + "\n", encoding="utf-8") + + +if __name__ == "__main__": + generate() + header = "/* Generated by tools/frontend_menu.py; page routes, never legacy widgets. */\n" + header += "static struct { char const *path; short tab, parent; char const *paused; } const frontend_pages[] = {\n" + for index, (_, tab, parent, _, _) in enumerate(PAGES): + path = "pc\\" + (page_base(index) + "/settings").replace("/", "\\") + paused = path.replace("pc\\modern\\", "pc\\modern\\paused\\", 1) + header += " {" + json.dumps(path) + f", {tab}, {parent}, " + json.dumps(paused) + "},\n" + header += "};\n" + (ROOT / "port/linux/game/frontend_pages.inl").write_text(header, encoding="utf-8") diff --git a/tools/frontend_multiplayer.py b/tools/frontend_multiplayer.py new file mode 100644 index 0000000000..b0bf55a427 --- /dev/null +++ b/tools/frontend_multiplayer.py @@ -0,0 +1,275 @@ +"""Independent modern views of the existing multiplayer widget contracts. + +Read the generated CE declarations as a service inventory (names, callbacks, +strings and lifecycle), never modify them. Only child/description dependencies +are copied: opening an editor remains a native service handoff. Presentation +and viewport metadata belong exclusively to this generator. +""" +from copy import deepcopy +from pathlib import Path +import json +import re +import xml.etree.ElementTree as ET + +ROOT = Path(__file__).resolve().parents[1] +MP = "main_menu/multiplayer_type_select/" +PAGES = { + "maps": (MP + "connected/connected_map_select_wrapper", "SELECT MAP", "MAPS"), + "gametypes": (MP + "connected/gametype_select_screen_wrapper", "GAMETYPE", "GAME RULES"), + "server": (MP + "server_settings/server_settings_screen", "SERVER SETUP", "HOST OPTIONS"), + "session": (MP + "server_settings/session_options/session_options_screen", "SESSION OPTIONS", "COMPATIBILITY"), + "lobby": (MP + "lobby/lobby_screen", "GAME LOBBY", "PLAYERS"), + "preview": (MP + "lobby/preview_screen", "JOIN GAME", "GAME IN PROGRESS"), + "bots": ("main_menu/settings_select/player_setup/player_profile_edit/network_setup/bots/bots_screen", "BOTS", "BOT OPTIONS"), + "sharing": ("main_menu/settings_select/player_setup/player_profile_edit/network_setup/map_sharing/map_sharing_settings_screen", "MAP SHARING", "MAP SHARING"), + "mcc_packages": ("main_menu/settings_select/player_setup/player_profile_edit/network_setup/mcc_packages/mcc_packages_screen", "MCC PACKAGES", "MCC PACKAGES"), + "coop": (MP + "server_settings/coop_options/coop_options_screen", "CO-OP OPTIONS", "CO-OP OPTIONS"), + "voice": (MP + "server_settings/voice_options/voice_options_screen", "VOICE AND VOTING", "VOICE AND VOTING"), + "campaign": ("main_menu/solo_level_select/solo_level_select_screen", "SELECT MISSION", "MISSIONS"), + "difficulty": ("main_menu/difficulty_select/difficulty_select_list_screen", "DIFFICULTY", "CHOOSE DIFFICULTY"), +} +TITLES = {"title_" + key: title for key, (_, title, _) in PAGES.items()} + + +def inventory(): + return {w.get("name"): w for p in sorted((ROOT / "port/assets/menus/ce").glob("*.xml")) + for w in ET.parse(p).getroot().findall("widget")} + + +def append(doc): + source = inventory() + roles = [] + routes = [] + def put(node, **attrs): + node.attrib.update({k: str(v) for k, v in attrs.items()}) + def leaf(path): + return path.rsplit("/", 1)[-1] + def add(kind, name, **attrs): + return ET.SubElement(doc, kind, name=name, **{k: str(v) for k,v in attrs.items()}) + def role(widget, value): + roles.append((widget.get("name"), value)) + for page, (original, caption, heading) in PAGES.items(): + base = "modern/network/" + page + copies = {} + def copy(path): + if path in copies: + return copies[path] + w = deepcopy(source[path]) + # Preserve semantic leaf names, including repeated names in modals. + w.set("name", base + "/" + str(len(copies)) + "/" + leaf(path)) + copies[path] = w + doc.append(w) + for c in w.findall("child"): + c.set("widget", copy(c.get("widget")).get("name")) + if w.get("description"): + w.set("description", copy(w.get("description")).get("name")) + w.set("flags", " ".join(f for f in w.get("flags", "").split() if f != "pause_game")) + return w + root = copy(original) + if page == "maps": + # Multiplayer chooses difficulty in-place, inside its map list. + # Give that step the same detail art/text as the campaign screen. + description = copy(MP + "mp_map_select/mp_map_extended_desc") + for leaf_name in ("difficulty_options", "difficulty_extended_description"): + detail = copy("main_menu/difficulty_select/" + leaf_name) + ET.SubElement(description, "child", widget=detail.get("name")) + routes.append((original, root.get("name"))) + by_name = {w.get("name"): w for w in copies.values()} + # The native wrappers retain their B/back and server-defer lifecycle. + screens = [w for w in copies.values() if w.get("bitmap") in ("bitmaps/gradient", "bitmaps/gradient_big")] + body = next(iter(screens), root) + for w in screens: + w.set("bitmap", "modern/panel") + role(w, "full") + for w in copies.values(): + name = leaf(w.get("name")) + if w.get("width")=="640" and w.get("height")=="480": role(w,"full") + children = w.findall("child") + for c in children: + target = by_name[c.get("widget")] + n = leaf(target.get("name")) + if n == "sel_list_desc_bkd" or n == "current_profile_name" or (n == "header" or n.startswith("header_")) and w is body: + w.remove(c) + # Lists keep child order: existing services address rows by index. + data = {c.get("input") for c in w.findall("data")} + scroll = bool(data & {"mp map list update", "solo map list update", "difficulty menu update desc", "gt select list update", "server settings update", "port lobby update", "game settings lists text update", "port settings help"}) + if scroll: + ET.SubElement(w, "data", input="port frontend multiplayer update") + index = 0 + for c in w.findall("child"): + target = by_name[c.get("widget")] + n = leaf(target.get("name")) + if re.match(r"list_item_\d", n) or n.startswith("op_") or n.endswith("_difficulty_item"): + put(c, x=28, y=110+30*index) + put(target, left=0, top=0, width=336, height=26, bitmap="modern/row") + target.set("flags", target.get("flags", "") + " nifty_fx") + role(target, "row") + if n.endswith("_difficulty_item"): + put(target, text_x=0, text_y=3, align="center", font="ui\\large_ui") + index += 1 + for inner in target.findall("child"): + item = by_name[inner.get("widget")] + item_name = leaf(item.get("name")) + if item_name in ("list_item_arrows", "scroll_up_button", "scroll_down_button"): + target.remove(inner) + continue + if item.get("type") == "spinner" or item_name.endswith("_value"): + chooser = n.startswith("list_item_0") + value_width = 296 if chooser else 140 + put(inner, x=20 if chooser else 180, y=3) + put(item, left=0, top=0, width=value_width, height=24, text_x=0, text_y=0, font="ui\\large_ui", align="center") + if item.get("type") == "spinner": + put(item, header_bounds="5 -12 17 -6", footer_bounds=f"5 {value_width} 17 {value_width + 6}") + if item_name == "session_compatibility_spinner": + # The native service reads indices; short captions fit + # the modern value column even at 4:3. + put(item, strings="CROSSPLAY|GULCHCE ONLY") + if item_name == "voice_mode_spinner": + item.attrib.pop("string_list", None) + put(item, strings="OFF|TEAM NEAR|ANYONE NEAR|TEAM|TEAM + NEARBY") + role(item, "chooser" if chooser else "value") + elif item.get("type") == "text": + put(inner, x=12, y=3) + put(item, left=0, top=0, width=312 if item_name=="list_item_text" else 152, height=24, text_x=0, text_y=0, font="ui\\large_ui", align="left") + if item_name == "session_compatibility_label": + put(item, text="COMPATIBILITY") + if item_name == "voice_proximity_label": + item.attrib.pop("string_list", None) + put(item, text="VOICE RANGE:", string_index=0) + role(item, "label_full" if item_name=="list_item_text" else "label") + if name.endswith("button_bar") or name == "button_bar": + put(w, left=0, top=0, width=588, height=26) + role(w, "bar") + count = len(w.findall("child")) + slot = min(130, 588 // max(1, count)) + for i,c in enumerate(w.findall("child")): + put(c, x=588-slot*(count-i), y=0) + button = by_name[c.get("widget")] + put(button, left=0, top=0, width=slot-6, height=26, bitmap="modern/button", text_y=3, font="ui\\small_ui") + button.set("flags", button.get("flags", "")+" nifty_fx") + role(button, "button") + for c in w.findall("child"): + if leaf(c.get("widget")).endswith("button_bar"): + put(c, x=26, y=414) + if name.endswith("_right_item"): + put(w, left=0, top=0, width=640, height=480) + w.attrib.pop("bitmap", None) + for c in w.findall("child"): + put(c,x=0,y=0) + if page == "campaign": + markers = [c for c in w.findall("child") if leaf(c.get("widget")) == "difficulty_indicator"] + for i,c in enumerate(markers): + put(c,x=444+36*i,y=359) + if page == "campaign" and name == "difficulty_indicator": + put(w,width=32,height=35) + role(w,"detail_icon") + if name.endswith("_extended_desc") or name in ("lobby_desc", "difficulty_ext_desc"): + if name == "difficulty_ext_desc": + put(w,left=0,top=0,width=640,height=480) + w.attrib.pop("bitmap",None) + role(w,"full") + for c in w.findall("child"): + put(c,x=0,y=0) + if name.endswith("_right_pic") or name == "lobby_map_pic": + put(w,left=426,top=94,width=140,height=114) + role(w,"detail_fixed") + if name.endswith("_right_name") or name in ("lobby_map_name", "mcc_folder_name"): + put(w,left=396,top=218,width=200,height=42,font="ui\\large_ui",align="center",text_x=0,text_y=0) + role(w,"detail") + if name.endswith("_right_data") or name in ("lobby_game_data", "mcc_folder_help"): + put(w,left=396,top=266,width=200,height=94 if page=="campaign" else 124,font="ui\\small_ui",align="center",text_x=0,text_y=0) + role(w,"detail_wrap") + if page in ("difficulty", "maps") and name == "difficulty_options": + put(w,left=415,top=92,width=162,height=171) + role(w,"detail_icon") + if page in ("difficulty", "maps") and name == "difficulty_extended_description": + put(w,left=396,top=270,width=200,height=122,text_x=0,text_y=0,align="center",font="ui\\small_ui") + role(w,"detail_wrap") + if page == "difficulty" and name == "warning_message": + put(w,left=0,top=0,width=312,height=140,text_x=0,text_y=0,align="center") + role(w,"heading") + for c in body.findall("child"): + if c.get("widget")==w.get("name"):put(c,x=40,y=245) + if name == "lobby_join_help": + put(w,left=28,top=387,width=584,height=20,align="left",text_y=0) + role(w,"status") + if name == "preview_status": + put(w,left=40,top=120,width=312,height=260,font="ui\\large_ui") + role(w,"heading") + if w.get("type") == "text" and name in ("help", "coop_options_help", "voice_options_help"): + put(w,left=396,top=174 if page in ("server", "session") else 108,width=200,height=212 if page in ("server", "session") else 278,font="ui\\large_ui",color="#FF2896FF") + role(w,"detail_wrap") + if page == "maps": + for original_label in list(copies.values()): + if leaf(original_label.get("name")) == "list_item_text": + centered = deepcopy(original_label) + centered.set("name", original_label.get("name") + "_centered") + centered.set("align", "center") + doc.append(centered) + role(centered, "label_full") + if page in ("server", "session"): + w=add("widget",base+"/help_value",type="text",controller=1,left=396,top=108,width=200,height=56,font="ui\\large_ui",color="#FFFFFFFF") + ET.SubElement(body,"child",widget=w.get("name")) + role(w,"detail_wrap") + # The fixed chrome is not inserted into service lists (row indices). + parent, title, chrome_base = body, page, base + if page == "difficulty": + # The difficulty service owns child zero (list) and one (warning), + # and the list draws its detached description before later siblings. + # Put decoration behind that intact service screen in an outer shell. + parent = add("widget", base+"/screen", width=640, height=480, + flags="pass_unhandled_to_focused_child", bitmap="modern/panel") + root.attrib.pop("bitmap", None) + role(parent, "full") + routes[-1] = (original, parent.get("name")) + ET.SubElement(parent, "on", event="created", focus=root.get("name")) + for n,x,y,width,height,bitmap in [("title",70,40,300,28,"modern/title_"+title), ("help_panel",380,82,232,318,"modern/help_panel"), ("rule",28,104,336,1,"modern/rule")]: + w=add("widget",chrome_base+"/"+n,left=x,top=y,width=width,height=height,controller=1,bitmap=bitmap,flags="nifty_fx" if n=="help_panel" else "") + # The difficulty shell owns decoration; other screens already + # permit leading chrome. Always draw it before detached details. + if page == "difficulty": + ET.SubElement(parent,"child",widget=w.get("name")) + else: + parent.insert(0,ET.Element("child",widget=w.get("name"))) + role(w,"detail" if n=="help_panel" else "heading") + if page == "difficulty": + ET.SubElement(parent, "child", widget=root.get("name")) + for n,x,y,width,text in [("section",32,82,332,heading),("prompts",28,450,584," "),("status",28,387,336,"")]: + w=add("widget",chrome_base+"/"+n,type="text",left=x,top=y,width=width,height=22,controller=1,text=text,font="ui\\small_ui" if n!="section" else "ui\\large_ui",color="#FF80A2C0") + ET.SubElement(parent,"child",widget=w.get("name")) + role(w,"status" if n=="prompts" else "heading") + # Remove declarations whose children were deliberately replaced, so legacy + # decorative bitmaps and unused captions do not accumulate in the new set. + generated={w.get("name"):w for w in doc.findall("widget") if w.get("name").startswith("modern/network/")} + reachable=set() + def visit(name): + if name in reachable:return + reachable.add(name) + w=generated[name] + for c in w.findall("child"):visit(c.get("widget")) + if w.get("description"):visit(w.get("description")) + for _,name in routes:visit(name) + for name in generated: + if name.endswith("_centered") and name[:-9] in reachable:visit(name) + for name,w in generated.items(): + if name not in reachable:doc.remove(w) + return [(n,r) for n,r in roles if n in reachable], routes + + +def write_metadata(roles, routes): + # Geometry roles are read-only; no pointers or scrolling state survive a map. + unique = dict(roles) + types = list(dict.fromkeys(unique.values())) + text = "/* Generated by tools/frontend_menu.py. Modern multiplayer views only. */\n" + text += "enum { " + ", ".join("FRONTEND_NET_"+v.upper() for v in types) + " };\n" + text += "static struct { char const *name; int role; } const frontend_network_widgets[] = {\n" + for name,value in unique.items(): + text += " {"+json.dumps("pc\\"+name.replace("/","\\"))+", FRONTEND_NET_"+value.upper()+"},\n" + text += "};\n" + (ROOT/"port/linux/game/frontend_network_layout.inl").write_text(text,encoding="utf-8") + text = "/* Generated by tools/frontend_menu.py; only explicitly migrated roots. */\n" + text += "static struct { char const *legacy, *modern; } const frontend_network_routes[] = {\n" + for old,new in routes: + text += " {"+json.dumps("pc\\"+old.replace("/","\\"))+", "+json.dumps("pc\\"+new.replace("/","\\"))+"},\n" + text += "};\n" + (ROOT/"port/linux/game/frontend_network_routes.inl").write_text(text,encoding="utf-8") diff --git a/tools/frontend_navigation.py b/tools/frontend_navigation.py new file mode 100644 index 0000000000..553d87d2b9 --- /dev/null +++ b/tools/frontend_navigation.py @@ -0,0 +1,112 @@ +"""Modern landing screens; existing services retain their editors and lifecycle.""" +import xml.etree.ElementTree as ET + +MP = "main_menu/multiplayer_type_select" +HOST = MP + "/connected/connected_map_select_wrapper" +BROWSER = MP + "/join_game/join_game_screen" +PROFILE = "main_menu/settings_select/player_setup/player_profile_edit/" + + +def append_legacy(doc): + """Additive Xbox links use stock editors and never replace native widgets.""" + links = [ + ("audio", "AUDIO SETUP", "audio_settings/audio_settings_screen", 51, 177, 232), + ("video", "VIDEO SETUP", "video_settings/video_settings_screen", 51, 210, 232), + ("network", "NETWORK SETUP", "network_setup/network_settings_screen", 51, 243, 232), + ("keyboard", "KEYBOARD BINDINGS", "controls_setup/controls_settings_screen", 54, 223, 512), + ("controller", "CONTROLLER REMAPPING", "controller_remapping/controller_remapping_screen", 54, 253, 512), + ("glyphs", "BUTTON GLYPHS", "controller_appearance/controller_appearance_screen", 54, 283, 512), + ] + for key, caption, target, x, y, width in links: + w = ET.SubElement(doc, "widget", name="frontend_legacy/"+key, type="text", + left=str(x), top=str(y), width=str(width), height="32" if width == 232 else "28", + text=caption, font="ui\\large_ui", color="#FF2896FF", + text_x="13", text_y="5", bitmap="bitmaps/list_item_bkd" if width == 232 else "ui\\shell\\bitmaps\\option_bkds") + for event in ("a", "start"): + ET.SubElement(w,"on",event=event,open=PROFILE+target) + ET.SubElement(w,"on",event="left_mouse",run="mouse emit accept event") + ET.SubElement(doc, "widget", name="frontend_legacy/description", type="text", + controller="1", left="294", top="290", width="296", height="110", + font="ui\\large_ui", color="#FF2896FF") + +# Section, caption, key, destination, callback(s), help. +# Multiplayer mode callbacks use the documented create_inter/create_lan/join_lan/ +# join_direct tokens in the instance name. Keep those tokens within 31 characters. +SCREENS = { + "multiplayer": ("MULTIPLAYER", "PLAY ONLINE", [ + (None, "SERVER BROWSER", "join_internet_item", BROWSER, ["mp type set mode"], "Browse public internet games, view their details, and join a server."), + (None, "LOCAL NETWORK", "join_lan_item", BROWSER, ["mp type set mode"], "Find and join games on your local network."), + (None, "JOIN BY LINK", "join_direct_item", BROWSER, ["mp type set mode"], "Join a game using its invite link. Paste the link into the Direct Link screen."), + ("HOST", "CREATE GAME >", "host", "modern/host/screen", [], "Host over the internet or your local network. Choose a multiplayer map or a single-player level for online campaign co-op."), + (None, "SPLIT-SCREEN CO-OP >", "coop", MP + "/coop/player_2_profile_screen", ["port coop begin"], "Play the campaign with another player on this machine. Player two chooses a profile with their own controller. For online co-op, use Create Game."), + ("GAME RULES", "EDIT GAMETYPES >", "gametypes", "main_menu/settings_select/multiplayer_setup/playlist_select/gametype_select_screen", [], "Create or edit saved multiplayer gametypes and their rules."), + ]), + "host": ("CREATE GAME", "HOST", [ + (None, "INTERNET", "create_internet_item", HOST, ["join controller to mp game", "mp type set mode"], "Host a game online. Choose a map and gametype, then set visibility, invite links and bots before entering the lobby."), + (None, "LOCAL NETWORK", "create_lan_item", HOST, ["join controller to mp game", "mp type set mode"], "Host on your local network only. Choose a multiplayer map or a single-player level for campaign co-op."), + ]), +} + + +def append(doc): + def node(kind, **attrs): + return ET.SubElement(doc, kind, **{k: str(v) for k, v in attrs.items() if v is not None}) + for page, (title, heading, rows) in SCREENS.items(): + base = "modern/" + page + def widget(name, **attrs): + return node("widget", name=base + "/" + name, **attrs) + def child(parent, name, x=0, y=0): + return ET.SubElement(parent, "child", widget=base + "/" + name, x=str(x), y=str(y)) + def text(name, **attrs): + return widget(name, type="text", font="ui\\large_ui", color="#FF2896FF", **attrs) + screen = widget("screen", width=640, height=480, bitmap="modern/panel", flags="pass_unhandled_to_focused_child main_menu_if_no_history") + # Returning from a cancelled host/browser abandons that session. Use + # the native shell cleanup before the guarded navigation initializer. + ET.SubElement(screen, "on", event="created", run="main menu intialize") + ET.SubElement(screen, "on", event="created", run="port frontend navigation init") + for key in ("b", "back"): + ET.SubElement(screen, "on", event=key, back="true") + child(screen, "title", 70, 40) + child(screen, "help_panel", 310, 82) + child(screen, "options") + child(screen, "help_title", 326, 96) + child(screen, "status", 28, 389) + child(screen, "prompts", 28, 450) + widget("title", width=300, height=28, bitmap="modern/title_" + page, controller=1) + widget("help_panel", width=302, height=318, bitmap="modern/help_panel", controller=1, flags="nifty_fx") + text("help_title", width=270, height=24, controller=1, string_list=base+"/labels").set("color", "#FF80A2C0") + text("help", left=326, top=135, width=270, height=250, controller=1, string_list=base+"/help_strings") + text("status", width=272, height=20, controller=1).set("font", "ui\\small_ui") + text("prompts", width=584, height=22, text=" ").set("font", "ui\\small_ui") + options = widget("options", type="column_list", width=640, height=480, flags="pass_unhandled_to_focused_child up_down_tabs_children", description=base+"/help") + ET.SubElement(options, "data", input="port frontend navigation update") + labels = node("strings", name=base+"/labels") + helps = node("strings", name=base+"/help_strings") + ET.SubElement(helps, "string", text="Choose an option. Up and Down navigate; Back returns to the previous screen.") + y = 82 + for index, (section, caption, key, target, callbacks, help_text) in enumerate(rows): + if index == 0 or section: + child(options, f"section_{index}", 32, y) + text(f"section_{index}", width=268, height=24, controller=1, text=heading if index==0 else section).set("color", "#FF80A2C0") + child(options, f"rule_{index}", 28, y+22) + widget(f"rule_{index}", width=272, height=1, bitmap="modern/rule", controller=1) + y += 28 + child(options, "row_"+key, 28, y) + row = widget("row_"+key, width=272, height=26, bitmap="modern/row", flags="nifty_fx") + child(row, "label_"+key, 12, 3) + text("label_"+key, width=248, height=24, controller=1, string_list=base+"/labels", string_index=index) + ET.SubElement(labels, "string", text=caption) + ET.SubElement(helps, "string", text=help_text) + for event in ("a", "start"): + for callback in callbacks[:-1]: + ET.SubElement(row, "on", event=event, run=callback) + ET.SubElement(row, "on", event=event, open=target, **({"run": callbacks[-1], "branch": "true"} if callbacks else {})) + ET.SubElement(row, "on", event="left_mouse", run="mouse emit accept event") + y += 30 + child(options, "button_bar", 26, 414) + bar = widget("button_bar", type="column_list", width=588, height=26, flags="pass_unhandled_to_focused_child left_right_tabs_items") + child(bar, "button_back", 462) + button = text("button_back", text="BACK", width=124, height=26, text_y=3, align="center", bitmap="modern/button", flags="nifty_fx") + for event in ("a", "start"): + ET.SubElement(button,"on",event=event,back="true") + ET.SubElement(button,"on",event="left_mouse",run="mouse emit accept event") diff --git a/tools/harness/tests/aim_assist.c b/tools/harness/tests/aim_assist.c index a4bfcfd223..607fc4e3fa 100644 --- a/tools/harness/tests/aim_assist.c +++ b/tools/harness/tests/aim_assist.c @@ -5,7 +5,8 @@ typedef unsigned short word; enum { _game_connection_local, _game_connection_network_client, _game_connection_network_server }; #include "message_ids.inc" enum { _distributed_to_clients_reliably }; -struct distributed_message_header { word header; byte type,count; long game_time; }; +typedef word message_header; +#include "message_header.inc" #define GET_MESSAGE_TYPE(h) (((h)>>2)&3) static int connection=2,playing=1,menu=0,block=0,preference=1; static unsigned long changes,mouse_aimed_ms,stick_aimed_ms,touch_aimed_ms; @@ -25,6 +26,7 @@ static void distributed_send(void *data,byte type,int count,word size,int destin static void distributed_send_to_machine_reliably(long machine,void *data,byte type,int count,word size){distributed_send(data,type,count,size,0);} #include "policy.inc" #include "input.inc" +#define POLICY_BYTES ((int)sizeof(struct aim_assist_policy_message)) static void receive(int from,int value,int count,int size){ struct aim_assist_policy_message m={{8,_distributed_message_aim_assist_policy,count,0},value}; network_aim_assist_handle_message(from,(word*)&m,size); @@ -33,8 +35,8 @@ int main(int argc,char **argv){CHECK(argc==2,"case");char const *case_name=argv[ CASE("allowed") {CHECK(!halo_linux_mouse_aiming(0),"enabled preference lost");preference=0;changes++;CHECK(!halo_linux_mouse_aiming(0),"allowed default changed");mouse_aimed_ms=1;CHECK(halo_linux_mouse_aiming(0),"local disabled ignored");CHECK(!halo_linux_mouse_aiming(1),"other controller affected");} else CASE("devices") {block=1;CHECK(halo_linux_mouse_aiming(0),"keyboard default bypass");mouse_aimed_ms=20;stick_aimed_ms=10;CHECK(halo_linux_mouse_aiming(0),"mouse preference bypass");stick_aimed_ms=30;CHECK(!halo_linux_mouse_aiming(0),"controller blocked");CHECK(!halo_linux_mouse_aiming(1),"second controller blocked");mouse_aimed_ms=40;CHECK(halo_linux_mouse_aiming(0),"switch back bypass");touch_aimed_ms=50;CHECK(!halo_linux_mouse_aiming(0),"touch blocked");mouse_aimed_ms=60;CHECK(halo_linux_mouse_aiming(0),"mouse after touch bypass");} else CASE("scope") {block=1;connection=0;CHECK(!halo_linux_mouse_aiming(0),"singleplayer affected");connection=2;menu=1;CHECK(!network_aim_assist_block_mouse(),"main menu affected");menu=0;playing=0;CHECK(!network_aim_assist_block_mouse(),"loading affected");} - else CASE("replication") {block=1;network_aim_assist_update();CHECK(sends==1&&wire_size==12,"wire layout");network_aim_assist_update();CHECK(sends==1,"unchanged spam");connection=1;block=0;network_aim_assist_handle_message(NONE,(word*)wire,wire_size);CHECK(network_aim_assist_block_mouse(),"client preference beat host");connection=2;network_aim_assist_send_policy(7);CHECK(sends==2,"late join policy missing");block=0;network_aim_assist_update();CHECK(sends==3,"changed policy missing");connection=1;network_aim_assist_handle_message(NONE,(word*)wire,wire_size);CHECK(!network_aim_assist_block_mouse(),"Allowed not restored");} - else CASE("admission") {connection=1;receive(NONE,0,1,12);CHECK(!network_aim_assist_block_mouse(),"valid policy");unreliable=1;receive(NONE,1,1,12);CHECK(!network_aim_assist_block_mouse(),"datagram spoof");unreliable=0;receive(3,1,1,12);CHECK(!network_aim_assist_block_mouse(),"client spoof");receive(NONE,1,0,12);CHECK(!network_aim_assist_block_mouse(),"count accepted");receive(NONE,2,1,12);CHECK(!network_aim_assist_block_mouse(),"invalid policy accepted");for(int n=0;n<12;n++)receive(NONE,1,1,n);CHECK(!network_aim_assist_block_mouse(),"truncation accepted");receive(NONE,1,1,13);CHECK(!network_aim_assist_block_mouse(),"trailing bytes accepted");connection=2;receive(NONE,1,1,12);connection=1;CHECK(!network_aim_assist_block_mouse(),"host accepted policy");} - else CASE("reset") {connection=1;receive(NONE,0,1,12);CHECK(!network_aim_assist_block_mouse(),"setup");network_aim_assist_reset();CHECK(network_aim_assist_block_mouse(),"previous host rule retained");receive(NONE,0,1,12);CHECK(!network_aim_assist_block_mouse(),"Allowed inaccessible");} + else CASE("replication") {block=1;network_aim_assist_update();CHECK(sends==1&&wire_size==POLICY_BYTES,"wire layout");network_aim_assist_update();CHECK(sends==1,"unchanged spam");connection=1;block=0;network_aim_assist_handle_message(NONE,(word*)wire,wire_size);CHECK(network_aim_assist_block_mouse(),"client preference beat host");connection=2;network_aim_assist_send_policy(7);CHECK(sends==2,"late join policy missing");block=0;network_aim_assist_update();CHECK(sends==3,"changed policy missing");connection=1;network_aim_assist_handle_message(NONE,(word*)wire,wire_size);CHECK(!network_aim_assist_block_mouse(),"Allowed not restored");} + else CASE("admission") {connection=1;receive(NONE,0,1,POLICY_BYTES);CHECK(!network_aim_assist_block_mouse(),"valid policy");unreliable=1;receive(NONE,1,1,POLICY_BYTES);CHECK(!network_aim_assist_block_mouse(),"datagram spoof");unreliable=0;receive(3,1,1,POLICY_BYTES);CHECK(!network_aim_assist_block_mouse(),"client spoof");receive(NONE,1,0,POLICY_BYTES);CHECK(!network_aim_assist_block_mouse(),"count accepted");receive(NONE,2,1,POLICY_BYTES);CHECK(!network_aim_assist_block_mouse(),"invalid policy accepted");for(int n=0;n +#define NUMBEROF(a) ((int)(sizeof(a)/sizeof((a)[0]))) +#define MIN(a,b) ((a)<(b)?(a):(b)) +#define MAX(a,b) ((a)>(b)?(a):(b)) +#define PIN(a,b,c) MIN(MAX(a,b),c) +typedef struct { real red,green,blue; } real_rgb_color; +typedef struct { real_point3d position; } real_matrix4x3; +struct object_marker { real_matrix4x3 matrix; }; +enum { _object_invisible_bit=0, _object_mask_projectile=16, _object_mask_biped=1, _object_mask_vehicle=2, _object_mask_weapon=4, _object_mask_equipment=8, _object_mask_scenery=64 }; +struct object_datum { long definition_index; struct { + long flags,owner_object_index,parent_object_index; + struct { int size; } node_matrices; + real maximum_body_vitality,body_vitality,outgoing_function_values[4]; + real_point3d position; + } object; }; +static struct object_datum objects[40]; +static struct { struct { struct { long index; } model; } object; } definition; +#define object_definition_get(i) (&definition) +static int vehicle,world,projectile,lookups,iteration_count,marker_count=8,generation; +struct object_iterator { long index; }; +static struct object_datum *object_try_and_get(long i) { return i>=0&&i<40?objects+i:NULL; } +static void object_iterator_new(struct object_iterator *it,int mask,int flags) { it->index=19; } +static struct object_datum *object_iterator_next(struct object_iterator *it) { return ++it->index<20+iteration_count?objects+it->index:NULL; } +static void object_get_origin(long i,real_point3d *p) { *p=objects[i].object.position; } +void render_interpolation_object_point(long i,real_point3d *p) { p->x+=.5f; } +static int object_get_marker_by_name(long i,const char *name,struct object_marker *out,int max) +{ int n;CHECK(!strcmp(name,"hover thrusters"),"only authored thrusters");for(n=0;n.53f&&sample.strength<.55f,"first thruster follows engine function"); + CHECK(ambient_emitter_lighting_sample(0,1,&sample)&&sample.position.x==4,"second thruster separated"); + marker_count=1;CHECK(!ambient_emitter_lighting_sample(0,1,&sample),"short marker list bounded");marker_count=8; + objects[0].object.maximum_body_vitality=1;CHECK(ambient_emitter_lighting_sample(0,0,&sample)&&sample.strength==0,"destroyed engine dark"); + projectile=1;iteration_count=12;definition.object.model.index=NONE; + for(i=20;i<32;i++){objects[i].definition_index=10;objects[i].object.flags=1;objects[i].object.owner_object_index=1;objects[i].object.position.x=(real)(i-20);} + ambient_emitter_lighting_begin();CHECK(flame_count==1&&flames[0].count==12,"many particles share one stream"); + CHECK(ambient_emitter_lighting_sample(1,0,&sample)&&sample.kind==EMITTER_FLAME&&sample.position.x==6&&sample.strength==1,"stream centroid and intensity bounded"); + for(i=20;i<32;i++)objects[i].object.owner_object_index=i-19; + ambient_emitter_lighting_begin();CHECK(flame_count==8,"many owners bounded"); + iteration_count=0;vehicle=0;CHECK(!ambient_emitter_lighting_begin(),"no live stream skips owner walk");CHECK(!ambient_emitter_lighting_sample(1,0,&sample),"expired stream disappears"); + ambient_emitter_lighting_forget();generation=100;world=1;ambient_emitter_lighting_begin();objects[0].definition_index=2; + CHECK(!ambient_emitter_lighting_sample(0,0,&sample),"stale map identity cannot match"); + objects[0].definition_index=102;CHECK(ambient_emitter_lighting_sample(0,0,&sample),"new map identity resolved"); + return 0; +} diff --git a/tools/harness/tests/android_cheats.c b/tools/harness/tests/android_cheats.c new file mode 100644 index 0000000000..86175fc7d4 --- /dev/null +++ b/tools/harness/tests/android_cheats.c @@ -0,0 +1,159 @@ +#include "harness.h" +#define HALO_ANDROID 1 +#define NUMBEROF(a) (sizeof(a) / sizeof((a)[0])) +#define SET_FLAG(value, bit, enabled) ((value) = ((value) & ~(1UL << (bit))) | ((enabled) ? 1UL << (bit) : 0)) +/* Keep the single-threaded stand-ins separate from system pthread types. */ +#define pthread_mutex_t harness_mutex_t +#define pthread_mutex_lock harness_mutex_lock +#define pthread_mutex_unlock harness_mutex_unlock +typedef int harness_mutex_t; +#define PTHREAD_MUTEX_INITIALIZER 0 +static void pthread_mutex_lock(pthread_mutex_t *mutex) { (void)mutex; } +static void pthread_mutex_unlock(pthread_mutex_t *mutex) { (void)mutex; } +typedef void JNIEnv; +typedef void *jclass; +typedef int jint; +typedef int jboolean; +#define JNIEXPORT +#define JNICALL +#define JNI_TRUE 1 +#define JNI_FALSE 0 +static struct { boolean deathless_player, infinite_ammo, bottomless_clip, super_jump, omnipotent, jetpack, medusa, bump_possession; } cheat; +boolean rider_ejection = TRUE; +static int vehicles; +static void cheat_all_vehicles(void) { vehicles++; } +static int enabled, playing, cinematic, network, local, hosting, client_lobby, weapons, powerups, camouflage; +static int config_boolean(char const *name) { (void)name; return enabled; } +static int touch_game_playing(void) { return playing; } +static int touch_game_cinematic_playing(void) { return cinematic; } +static boolean network_game_distributed_client(void) { return network && !local && !hosting; } +static void *global_network_game_client_get(void) { return network || client_lobby ? (void *)1 : NULL; } +static void *global_network_game_server_get(void) { return local || hosting ? (void *)1 : NULL; } +static void cheat_all_weapons(void) { weapons++; } +static void cheat_all_powerups(void) { powerups++; } +static void cheat_active_camouflage_local_player(short player) { CHECK(player == 0, "wrong player"); camouflage++; } +#include "under_test.inc" +#define request(value) Java_com_halo_decomp_AndroidCheatMenu_nativeRequest(NULL, NULL, value) +#define state_read() Java_com_halo_decomp_AndroidCheatMenu_nativeState(NULL, NULL) + +int main(int argc, char **argv) +{ + int i; + CHECK(argc == 2, "case"); + playing = 1; + if (!strncmp(argv[1], "host", 4)) network = hosting = 1; + if (!strcmp(argv[1], "disabled") || !strcmp(argv[1], "host-disabled")) + { + android_cheats_update(); + CHECK(state_read() == 0 && !request(0x100), "default enabled"); + return 0; + } + enabled = 1; + android_cheats_update(); + CHECK((state_read() & 3) == 3, "offline unavailable"); + if (!strcmp(argv[1], "offline") || !strcmp(argv[1], "host")) + { + CHECK(request(0x100) && request(9) && request(10) && request(11), "rejected typed request"); + android_cheats_update(); + CHECK(cheat.deathless_player && weapons == 1 && powerups == 1 && camouflage == 1, "actions not applied"); + CHECK(request(0), "disable request"); + android_cheats_update(); + CHECK(!cheat.deathless_player, "switch not disabled"); + } + else if (!strcmp(argv[1], "all-cheats")) + { + for (i = 0; i < 9; i++) { + CHECK(request(0x100 | i), "switch refused"); + android_cheats_update(); + CHECK(state_read() & (1 << (8 + i)), "switch state missing"); + } + CHECK(cheat.deathless_player && cheat.infinite_ammo && cheat.bottomless_clip && cheat.super_jump && + cheat.omnipotent && cheat.jetpack && cheat.medusa && cheat.bump_possession && !rider_ejection, + "cheat mapping incorrect"); + CHECK(request(12), "vehicle action refused"); + android_cheats_update(); + CHECK(vehicles == 1, "vehicles not spawned"); + android_cheats_reset(); + CHECK(!cheat.deathless_player && !cheat.infinite_ammo && !cheat.bottomless_clip && !cheat.super_jump && + !cheat.omnipotent && !cheat.jetpack && !cheat.medusa && !cheat.bump_possession && rider_ejection, + "switches leaked across maps"); + } + else if (!strcmp(argv[1], "network")) + { + CHECK(request(9), "queue before transition"); + network = 1; + android_cheats_update(); + CHECK(state_read() == 1 && !request(9) && weapons == 0, "network client accepted cheat"); + local = 1; + android_cheats_update(); + CHECK(request(9), "offline split screen rejected"); + android_cheats_update(); + CHECK(weapons == 1, "stale request survived transition"); + } + else if (!strcmp(argv[1], "host-client")) + { + CHECK(request(0x100), "host switch refused"); + android_cheats_update(); + CHECK(cheat.deathless_player && request(9), "host request refused"); + hosting = 0; + android_cheats_update(); + CHECK(!cheat.deathless_player && state_read() == 1 && !request(9) && weapons == 0, + "host privilege or queued request survived joining another host"); + hosting = 1; + android_cheats_update(); + CHECK((state_read() & 3) == 3 && weapons == 0, "new host inherited a queued request"); + } + else if (!strcmp(argv[1], "client-lobby")) + { + CHECK(request(9), "queue before joining"); + client_lobby = 1; + android_cheats_update(); + CHECK(state_read() == 1 && !request(9) && weapons == 0, "joining lobby accepted cheat"); + } + else if (!strcmp(argv[1], "reset") || !strcmp(argv[1], "host-reset")) + { + cheat.infinite_ammo = TRUE; + CHECK(request(0x100) && request(1), "switch requests"); + android_cheats_update(); + CHECK(cheat.deathless_player && !cheat.infinite_ammo, "switches"); + CHECK(request(9), "queue at unload"); + android_cheats_reset(); + CHECK(!cheat.deathless_player && cheat.infinite_ammo && host_android_cheats_read() == -1, "state leaked at unload"); + android_cheats_update(); + CHECK(request(0x103), "super jump"); + android_cheats_update(); + cheat.super_jump = FALSE; /* A subsequent console edit owns this value. */ + enabled = 0; + android_cheats_update(); + CHECK(!cheat.super_jump && state_read() == 0, "disable overwrote subsequent change"); + android_cheats_reset(); + CHECK(cheat.infinite_ammo, "repeated reset lost original setting"); + } + else if (!strcmp(argv[1], "cinematic") || !strcmp(argv[1], "host-cinematic")) + { + CHECK(request(0x100), "deathless request"); + android_cheats_update(); + CHECK(request(9), "queued before cinematic"); + cinematic = 1; + android_cheats_update(); + CHECK(cheat.deathless_player && weapons == 0 && !request(9), "cinematic changed cheats or accepted action"); + cinematic = 0; + android_cheats_update(); + CHECK(weapons == 0 && cheat.deathless_player, "stale cinematic action survived"); + playing = 0; + android_cheats_update(); + CHECK(!cheat.deathless_player, "cheat survived gameplay exit"); + } + else if (!strcmp(argv[1], "queue")) + { + CHECK(!request(-1) && !request(13) && !request(0x109) && !request(0x200), "malformed request accepted"); + for (i = 0; i < 8; i++) CHECK(request(9), "bounded queue refused early"); + CHECK(!request(9), "queue overflow"); + android_cheats_update(); + CHECK(weapons == 4, "poll exceeded budget"); + android_cheats_update(); + CHECK(weapons == 8 && host_android_cheats_read() == -1, "queue duplicated/lost request"); + } + else CHECK(0, "unknown case"); + return 0; +} diff --git a/tools/harness/tests/authored_emitter_lighting.c b/tools/harness/tests/authored_emitter_lighting.c new file mode 100644 index 0000000000..43851f2b56 --- /dev/null +++ b/tools/harness/tests/authored_emitter_lighting.c @@ -0,0 +1,81 @@ +#include "harness.h" +#include +#define NUMBEROF(a) ((int)(sizeof(a) / sizeof((a)[0]))) +#define MIN(a,b) ((a)<(b)?(a):(b)) +#define MAX(a,b) ((a)>(b)?(a):(b)) +#define PIN(a,b,c) MIN(MAX(a,b),c) + + + +struct object_datum { long definition_index; struct {real_point3d bounding_sphere_center;} object; } object; +struct observer_result {real_point3d position;} cameras[4]; +static int local_count=1; +int local_player_count(void) {return local_count;} +struct observer_result const *observer_get_camera(short i) {return &cameras[i];} +static int weapon_on, vehicle_on, projectile_on, prong_on, lookups, generation; +static const char *names[64]; +static long groups[64]; +static int name_count; +int lighting_config_boolean(const char *name) +{ + return !strcmp(name, "display.plasma_prong_lighting") ? prong_on : !strcmp(name, "display.weapon_glow") ? weapon_on : + !strcmp(name, "display.vehicle_lighting") ? vehicle_on : projectile_on; +} +struct object_datum *object_try_and_get(long index) { return index == 1 ? &object : NULL; } +long tag_loaded(long group, const char *name) +{ + int i; + lookups++; + for (i = 0; i < name_count; i++) + if (group == groups[i] && !strcmp(name, names[i])) return generation + i; + names[name_count] = name; + groups[name_count] = group; + return generation + name_count++; +} +#include "under_test.inc" +int main(int argc, char **argv) +{ + int i, calls; + float scale = 42; + (void)argc; (void)argv; + CHECK(!authored_emitter_lighting_profile(1, 10, &scale) && !lookups && scale == 42, + "off performs no tag discovery or writes"); + for (i = 0; i < NUMBEROF(profiles); i++) + { + long light; + weapon_on = profiles[i].category == 1; + prong_on = profiles[i].category == 4; + vehicle_on = profiles[i].category == 2; + projectile_on = profiles[i].category == 3; + object.definition_index = tag_loaded(profiles[i].group, profiles[i].object); + light = tag_loaded('ligh', profiles[i].light); + CHECK(authored_emitter_lighting_profile(1, light, &scale) == profiles[i].category && + scale == profiles[i].scale, "selected source uses its category and scale"); + calls = lookups; + CHECK(authored_emitter_lighting_profile(1, light, &scale) && lookups == calls, + "steady frames reuse cached identities"); + CHECK(!authored_emitter_lighting_profile(1, 60000, &scale), "unrelated light stays stock"); + CHECK(!authored_emitter_lighting_profile(2, light, &scale), "deleted owner stays stock"); + if (profiles[i].category == 4) + { + prong_on=0;weapon_on=1; + CHECK(!authored_emitter_lighting_profile(1,light,&scale),"Weapon Glow cannot enable standalone prongs"); + } + weapon_on = vehicle_on = projectile_on = prong_on = 0; + CHECK(!authored_emitter_lighting_profile(1, light, &scale), "disable immediately restores stock"); + } + weapon_on = 1; + object.object.bounding_sphere_center.x=4; + CHECK(prong_reach(&object)>0 && prong_reach(&object)<1,"mid-distance prongs fade smoothly"); + object.object.bounding_sphere_center.x=7; + CHECK(prong_reach(&object)==0,"distant prongs retain only their stock authored effects"); + cameras[1].position.x=7;local_count=2; + CHECK(prong_reach(&object)==1,"another split-screen player retains nearby prong spill"); + generation = 1000; + authored_emitter_lighting_forget(); + object.definition_index = tag_loaded('weap', "weapons\\energy sword\\energy sword"); + CHECK(authored_emitter_lighting_profile(1, tag_loaded('ligh', "weapons\\energy sword\\energy sword dynamic"), &scale), + "new map resolves new tag identities"); + CHECK(!authored_emitter_lighting_profile(1, 1, &scale), "old map identity cannot match"); + return 0; +} diff --git a/tools/harness/tests/bot_decisions.c b/tools/harness/tests/bot_decisions.c new file mode 100644 index 0000000000..f4b6b999ec --- /dev/null +++ b/tools/harness/tests/bot_decisions.c @@ -0,0 +1,102 @@ +#include "harness.h" +#include "bots_combat.h" +#include +#include +#define REAL_MAX FLT_MAX +#define BOTS_MAXIMUM 15 +#define TICKS_PER_SECOND 30 +static long game_time_get(void) { return 100; } +#define MIN(a,b) ((a) < (b) ? (a) : (b)) +#define PIN(a,l,h) ((a) < (l) ? (l) : (a) > (h) ? (h) : (a)) +enum { game_engine_slayer, game_engine_ctf }; +static struct { long game_engine_index; } variant; +#define game_engine_get_variant() (&variant) +enum { _equipment_powerup_health, _equipment_powerup_overshield, _equipment_powerup_active_camouflage }; +enum { _unit_active_camouflaged_bit }; +struct bots_bot { long player_index; real_point3d goal; }; +struct player_datum { long team_index; }; +struct unit_datum { + struct { real body_vitality, shield_vitality; } object; + struct { unsigned long flags; } unit; +}; +static struct { struct { int powerup_type; } equipment; } equipment; +#define equipment_definition_get(index) (&equipment) +static struct { struct { + boolean present[2], at_home[2], home_to_score; + long carrier_player_index[2]; + real_point3d home[2], position[2]; +} ctf; } bots_globals; +static boolean defender; +static void bots_ctf_update(void) {} +static boolean bots_ctf_defender(struct bots_bot *bot, struct player_datum *player) +{ (void)bot; (void)player; return defender; } +static boolean bots_ctf_set_goal(struct bots_bot *bot, real_point3d const *point, real moved) +{ (void)moved; bot->goal = *point; return TRUE; } +#include "under_test.inc" + +int main(int argc, char **argv) +{ + struct bots_bot bot = { 42, { 0, 0, 0 } }; + struct player_datum player = { 0 }; + real_point3d position = { 0, 0, 0 }; + struct unit_datum unit = { { 1.0f, 1.0f }, { 0 } }; + CHECK(argc == 2, "case"); + bots_globals.ctf.present[0] = bots_globals.ctf.present[1] = TRUE; + bots_globals.ctf.at_home[0] = bots_globals.ctf.at_home[1] = TRUE; + bots_globals.ctf.carrier_player_index[0] = bots_globals.ctf.carrier_player_index[1] = NONE; + bots_globals.ctf.home[0].x = 10; + bots_globals.ctf.position[0].x = 20; + if (!strcmp(argv[1], "carrier")) + { + bots_globals.ctf.carrier_player_index[1] = 42; + CHECK(bots_ctf_urgent_goal(&bot, &player, &position) && bot.goal.x == 10, "carrier did not go home"); + player.team_index = 2; + CHECK(!bots_ctf_urgent_goal(&bot, &player, &position), "invalid team accepted"); + } + else if (!strcmp(argv[1], "standoff")) + { + bots_globals.ctf.home_to_score = TRUE; + bots_globals.ctf.carrier_player_index[0] = 1; + bots_globals.ctf.carrier_player_index[1] = 2; + position.x = 100; + CHECK(bots_ctf_urgent_goal(&bot, &player, &position) && bot.goal.x == 20, "standoff did not recover own flag"); + } + else if (!strcmp(argv[1], "recovery")) + { + bots_globals.ctf.at_home[0] = FALSE; + CHECK(bots_ctf_urgent_goal(&bot, &player, &position) && bot.goal.x == 20, "near dropped flag ignored"); + position.x = 100; + CHECK(!bots_ctf_urgent_goal(&bot, &player, &position), "distant attacker diverted"); + defender = TRUE; + CHECK(bots_ctf_urgent_goal(&bot, &player, &position), "defender ignored own flag"); + } + else if (!strcmp(argv[1], "powerups")) + { + equipment.equipment.powerup_type = _equipment_powerup_health; + CHECK(enhanced_bots_powerup_score(&unit, 0, 10, _bots_skill_normal, FALSE, FALSE) == REAL_MAX, "healthy bot seeks health"); + unit.object.body_vitality = 0.1f; + CHECK(enhanced_bots_powerup_score(&unit, 0, 10, _bots_skill_normal, FALSE, FALSE) < 0, "critical health not prioritized"); + CHECK(enhanced_bots_powerup_score(&unit, 0, 10, _bots_skill_easy, TRUE, FALSE) == REAL_MAX, "easy bot heals during combat"); + CHECK(enhanced_bots_powerup_score(&unit, 0, 16, _bots_skill_legendary, TRUE, FALSE) == REAL_MAX, "combat healing exceeds reach"); + unit.object.body_vitality = 0.7f; + CHECK(enhanced_bots_powerup_score(&unit, 0, 1, _bots_skill_legendary, FALSE, FALSE) < REAL_MAX, "legendary health threshold"); + CHECK(enhanced_bots_powerup_score(&unit, 0, 1, _bots_skill_normal, FALSE, FALSE) == REAL_MAX, "normal health threshold"); + equipment.equipment.powerup_type = _equipment_powerup_overshield; + unit.object.shield_vitality = 2; + CHECK(enhanced_bots_powerup_score(&unit, 0, 1, _bots_skill_normal, FALSE, FALSE) == REAL_MAX, "overshield wasted"); + equipment.equipment.powerup_type = _equipment_powerup_active_camouflage; + CHECK(enhanced_bots_powerup_score(&unit, 0, 1, _bots_skill_normal, FALSE, FALSE) < 0, "camouflage ignored"); + CHECK(enhanced_bots_powerup_score(&unit, 0, 7, _bots_skill_legendary, FALSE, TRUE) == REAL_MAX, "vantage point abandoned for distant powerup"); + variant.game_engine_index = game_engine_ctf; + CHECK(enhanced_bots_powerup_score(&unit, 0, 13, _bots_skill_legendary, FALSE, FALSE) == REAL_MAX, "objective powerup detour too long"); + unit.unit.flags = FLAG(_unit_active_camouflaged_bit); + CHECK(enhanced_bots_powerup_score(&unit, 0, 1, _bots_skill_normal, FALSE, FALSE) == REAL_MAX, "camouflage wasted"); + unit.object.body_vitality = 0.2f; unit.object.shield_vitality = 0; + CHECK(enhanced_bots_retreat(&unit, _bots_skill_normal, 95), "wounded turret gunner stayed"); + CHECK(!enhanced_bots_retreat(&unit, _bots_skill_normal, 50), "old injury caused turret exit"); + unit.object.shield_vitality = 1; + CHECK(!enhanced_bots_retreat(&unit, _bots_skill_normal, 95), "shielded gunner abandoned turret"); + } + else CHECK(0, "unknown case"); + return 0; +} diff --git a/tools/harness/tests/bot_vehicles.c b/tools/harness/tests/bot_vehicles.c new file mode 100644 index 0000000000..c6779c9318 --- /dev/null +++ b/tools/harness/tests/bot_vehicles.c @@ -0,0 +1,298 @@ +#include "harness.h" +#include +#include +#define REAL_MAX FLT_MAX +#define BOTS_MAXIMUM 15 +#define TICKS_PER_SECOND 30 +#define MAXIMUM_WEAPONS_PER_UNIT 4 +#define MIN(a,b) ((a) < (b) ? (a) : (b)) +#define MAX(a,b) ((a) > (b) ? (a) : (b)) +#define PIN(a,l,h) ((a) < (l) ? (l) : (a) > (h) ? (h) : (a)) +#define csmemset memset +#define SET_FLAG(f,b,v) ((v) ? ((f) |= FLAG(b)) : ((f) &= ~FLAG(b))) +#define platform_log(...) ((void)0) +#define VEHICLE_DEFINITION_TAG 0 +#define _object_mask_vehicle 1 +#define _object_mask_unit 2 +enum { _object_dead_bit, _unit_not_enterable_by_player_bit, _unit_seat_driver_bit, _unit_seat_gunner_bit }; +enum { _unit_control_action_bit, _unit_control_jump_bit, _unit_control_throw_grenade_bit, + _unit_control_use_equipment_bit, _unit_control_weapon_primary_trigger_bit }; +enum { _unit_nearby_seat_available = 2 }; +struct object_state { + long parent_object_index; + long first_child_object_index, next_object_index; + short type; + real_vector3d up, forward, translational_velocity; + real_point3d position; + real_point3d bounding_sphere_center; + real bounding_sphere_radius; + unsigned long damage_flags; +}; +struct object_datum { long definition_index; struct object_state object; }; +struct unit_datum { + long definition_index; + struct object_state object; + struct { long driver_object_index, gunner_object_index, weapon_object_indices[4]; + short current_weapon_index, parent_seat_index; unsigned long flags; long player_index; real_vector3d aiming_vector; } unit; +}; +struct unit_seat { unsigned long flags; }; +struct unit_definition { struct { struct { long count; struct unit_seat *address; } seats; } unit; }; +#define TAG_BLOCK_GET_ELEMENT(block, i, type) (&(block)->address[i]) +struct player_action { struct { real i, j; } throttle; struct { real yaw, pitch; } desired_facing; + unsigned long control_flags; real primary_trigger; }; +static struct unit_datum units[3]; +static struct unit_seat seat; +static struct unit_definition tag; +static byte vehicle_tag[1024]; +static real entry_offset; +static long now = 100; +static int enabled = 1, available = 1, clock_ready; +struct player_datum { short team_index; struct { short machine_index; } network_player_data; }; +static boolean bots_player_owned(long index) { return index>=65; } +static struct player_datum player; +static int game_engine_has_teams(void) { return 1; } +static struct player_datum *player_try_and_get(long index) { return index == NONE ? NULL : &player; } +struct weapon_trigger_definition { real charging_time; }; +struct weapon_definition { struct { struct { long count; struct weapon_trigger_definition *address; } triggers; } weapon; }; +static struct weapon_definition weapon_tag; +static struct weapon_trigger_definition trigger; +static struct object_datum *weapon_get(long index) { (void)index; return (void *)&units[0]; } +static struct weapon_definition *weapon_definition_get(long index) { (void)index; return &weapon_tag; } +static void bots_vehicle_obstacle(long index, real_point3d const *goal) { (void)index; (void)goal; } +static void vector_from_points3d(real_point3d const *a, real_point3d const *b, real_vector3d *v) +{ v->i = b->x-a->x; v->j = b->y-a->y; v->k = b->z-a->z; } +static real dot_product3d(real_vector3d const *a, real_vector3d const *b) { return a->i*b->i+a->j*b->j+a->k*b->k; } +static real magnitude3d(real_vector3d const *v) { return (real)sqrt(dot_product3d(v,v)); } +static int config_boolean(char const *name) { (void)name; return enabled; } +static long game_time_get(void) { CHECK(clock_ready, "clock read outside a running map"); return now; } +static struct object_datum *object_get(long index) { CHECK(index >= 0 && index < 3, "index"); return (void *)&units[index]; } +static struct object_datum *object_try_and_get(long index) { return index >= 0 && index < 3 ? object_get(index) : NULL; } +static struct object_datum *object_try_and_get_and_verify_type(long index, int type) +{ (void)type; return index == 1 ? object_get(index) : NULL; } +static struct unit_datum *unit_get(long index) { return &units[index]; } +static void *tag_get(int group, long index) { (void)group; (void)index; return vehicle_tag; } +static struct unit_definition *unit_definition_get(long index) { (void)index; return &tag; } +static boolean unit_can_enter_seat(long a, long b, short c, void *d) +{ (void)a; (void)b; (void)c; (void)d; return available; } +static boolean unit_has_animation_to_enter_seat(long a, long b, short c) +{ (void)a; (void)b; (void)c; return TRUE; } +static int unit_find_nearby_seat(long a, long b, short *chosen) +{ (void)a; (void)b; *chosen = 0; return available ? _unit_nearby_seat_available : 0; } +static struct unit_datum *mcc_seat_parent(long index) { (void)index; return NULL; } +static long mcc_seat_controller(long index) { (void)index; return NONE; } +static boolean flight_failed, flight_grounded; +static void enhanced_flight_reset(long index) { (void)index; flight_failed=FALSE; } +static boolean enhanced_flight_landing(long index) { return FALSE; } +static boolean enhanced_flight_failed(long index) { (void)index;return flight_failed; } +static boolean enhanced_flight_can_exit(long index) { (void)index; return flight_grounded; } +static int flight_turn; +static void enhanced_flight_action(long a, long b, boolean hovering, real_point3d const *c, boolean d, boolean e, struct player_action *f) +{ (void)a; (void)b; (void)c; (void)d; (void)e; f->primary_trigger=0; f->control_flags &= ~FLAG(_unit_control_weapon_primary_trigger_bit); f->desired_facing.yaw += flight_turn; } +static int infection_enabled(void) { return 0; } +static int infection_unit_is_zombie(long index) { (void)index; return 0; } +struct object_iterator { long index; }; +static void object_iterator_new(struct object_iterator *it, int mask, int flags) { (void)mask; (void)flags; it->index=0; } +static struct object_datum *object_iterator_next(struct object_iterator *it) { return ++it->index==1 ? object_get(1):NULL; } +static boolean unit_get_seat_entrance_point(long a,long b,short c,real_point3d *entry,real_point3d *seat_point,void *unused) +{ (void)a;(void)c;(void)unused; *entry=units[b].object.position; entry->x+=entry_offset;entry->y+=1; *seat_point=*entry; return TRUE; } +static long bots_routes_ground(real_point3d const *p,real_point3d *ground) { *ground=*p; return 5; } +#include "under_test.inc" + +int main(int argc, char **argv) +{ + struct player_action action; + real_point3d goal = { 100, 0, 0 }; + real radius = 0.1f; + int i; + CHECK(argc == 2, "case"); + bots_vehicles_reset(); + clock_ready = 1; + memset(&action, 0, sizeof(action)); + units[0].object.parent_object_index = 1; + units[1].unit.driver_object_index = 0; + units[1].unit.gunner_object_index = NONE; + units[1].object.up.k = units[1].object.forward.i = 1; + units[1].object.first_child_object_index = NONE; + units[1].unit.aiming_vector.i = 1; + tag.unit.seats.count = 1; + tag.unit.seats.address = &seat; + seat.flags = FLAG(_unit_seat_driver_bit); + ((struct bots_vehicle_definition *)vehicle_tag)->type = 1; + ((struct bots_vehicle_definition *)vehicle_tag)->radius = 1.5f; + if (!strcmp(argv[1], "seat")) + { + CHECK(!seat_available(0, 0, 1, -1) && !seat_available(0, 0, 1, 1), "seat bounds"); + CHECK(seat_available(0, 0, 1, 0), "valid seat refused"); + vehicles[1].sought = 1; vehicles[1].seat = 0; + CHECK(!seat_available(0, 0, 1, 0), "reservation ignored"); + bots_vehicles_reset_player(1); + available = 0; + CHECK(!seat_available(0, 0, 1, 0), "engine rejection ignored"); + } + else if (!strcmp(argv[1], "driver")) + { + CHECK(bots_vehicle_navigation(0, &radius) == 1 && radius == 1.5f, "driver used biped navigation"); + bots_vehicle_action(0, 0, &goal, FALSE, TRUE, 0.7f, NONE, FALSE, &action); + CHECK(action.throttle.i == 0, "driver left before entry grace elapsed"); + now += TICKS_PER_SECOND; + action.primary_trigger = 1; action.control_flags = FLAG(_unit_control_weapon_primary_trigger_bit); + bots_vehicle_action(0, 0, &goal, FALSE, TRUE, 0.7f, NONE, FALSE, &action); + CHECK(action.throttle.i > 0 && action.desired_facing.yaw == 0.7f, "driver did not steer"); + CHECK(!action.primary_trigger && !TEST_FLAG(action.control_flags, _unit_control_weapon_primary_trigger_bit), "steering fired an aimed shot"); + } + else if (!strcmp(argv[1], "disable")) + { + enabled = 0; + bots_vehicle_action(0, 0, &goal, FALSE, FALSE, 0, NONE, FALSE, &action); + CHECK(TEST_FLAG(action.control_flags, _unit_control_action_bit), "disable left seated bot stranded"); + units[0].object.parent_object_index = NONE; + bots_vehicle_action(0, 0, &goal, FALSE, FALSE, 0, NONE, FALSE, &action); + CHECK(vehicles[0].ridden == NONE && vehicles[0].sought == NONE, "exit retained reservation"); + } + else if (!strcmp(argv[1], "gunner")) + { + units[1].unit.driver_object_index = NONE; units[1].unit.gunner_object_index = 0; + units[1].unit.current_weapon_index = -1; + CHECK(bots_vehicle_weapon(0, 90) == 90, "invalid weapon slot"); + units[1].unit.current_weapon_index = 2; units[1].unit.weapon_object_indices[2] = 91; + CHECK(bots_vehicle_weapon(0, 90) == 91, "gunner did not use turret weapon"); + action.primary_trigger = 1; + bots_vehicle_action(0, 0, &goal, FALSE, FALSE, 0, NONE, FALSE, &action); + CHECK(action.primary_trigger == 1, "gunner trigger cleared"); + } + else if (!strcmp(argv[1], "stuck")) + { + for (i = 0; i <= 6; i++) { + now += TICKS_PER_SECOND; + action.control_flags = 0; + bots_vehicle_action(0, 0, &goal, FALSE, TRUE, 0, NONE, FALSE, &action); + } + CHECK(TEST_FLAG(action.control_flags, _unit_control_action_bit), "stuck driver never exited"); + } + else if (!strcmp(argv[1], "ghost")) + { + ((struct bots_vehicle_definition *)vehicle_tag)->type = 3; + CHECK(drivable(1) && bots_vehicle_flying(0), "human plane has no flight controller"); + ((struct bots_vehicle_definition *)vehicle_tag)->type = 4; + CHECK(drivable(1), "alien scout refused"); + units[2].object.position.x = 50; + bots_vehicle_action(0, 0, &goal, TRUE, TRUE, 1.0f, 2, FALSE, &action); + now += 30; action.primary_trigger = 1; + bots_vehicle_action(0, 0, &goal, TRUE, TRUE, 1.0f, 2, FALSE, &action); + CHECK(action.throttle.j > 0.8f && action.desired_facing.yaw == 0 && action.primary_trigger == 1, "scout lost independent aim"); + } + else if (!strcmp(argv[1], "claim")) + { + vehicles[1].sought = 1; vehicles[1].seat = 0; vehicles[1].unit_index = 2; + units[2].object.position.x = 20; + CHECK(seat_available(0, 0, 1, 0), "closer teammate could not take distant claim"); + units[2].object.position.x = 10; + CHECK(!seat_available(0, 0, 1, 0), "nearby teammate claim stolen"); + } + else if (!strcmp(argv[1], "boarding")) + { + vehicles[1].sought = 1; vehicles[1].unit_index = 2; vehicles[1].sought_tick = now; + units[2].object.position.x = 2; + bots_vehicle_action(0, 0, &goal, FALSE, TRUE, 0, NONE, FALSE, &action); + now += 30; + bots_vehicle_action(0, 0, &goal, FALSE, TRUE, 0, NONE, FALSE, &action); + CHECK(action.throttle.i == 0, "driver abandoned boarding teammate"); + now += 360; + bots_vehicle_action(0, 0, &goal, FALSE, TRUE, 0, NONE, FALSE, &action); + CHECK(action.throttle.i > 0, "boarding wait never expired"); + } + else if (!strcmp(argv[1], "turret")) + { + ((struct bots_vehicle_definition *)vehicle_tag)->type = 6; + units[1].unit.gunner_object_index = 0; units[1].unit.current_weapon_index = 0; + units[2].object.bounding_sphere_center.x = 10; + weapon_tag.weapon.triggers.count = 1; weapon_tag.weapon.triggers.address = &trigger; trigger.charging_time = 1; + action.primary_trigger = 1; + bots_vehicle_action(0, 0, &goal, FALSE, FALSE, 0, 2, FALSE, &action); + now += 15; action.primary_trigger = 0; + bots_vehicle_action(0, 0, &goal, FALSE, FALSE, 0, 2, FALSE, &action); + CHECK(action.primary_trigger == 1, "charged turret released early"); + now += 25; + bots_vehicle_action(0, 0, &goal, FALSE, FALSE, 0, 2, FALSE, &action); + CHECK(action.primary_trigger == 0, "charged turret never released"); + units[2].object.bounding_sphere_center.x = -10; + bots_vehicle_action(0, 0, &goal, FALSE, FALSE, 0, 2, FALSE, &action); + now += 61; + bots_vehicle_action(0, 0, &goal, FALSE, FALSE, 0, 2, FALSE, &action); + CHECK(TEST_FLAG(action.control_flags, _unit_control_action_bit), "turret retained unreachable firing arc"); + } + else if (!strcmp(argv[1], "flip")) + { + units[0].object.parent_object_index = NONE; + units[1].object.up.k = -1; units[1].object.bounding_sphere_radius = 2; + vehicles[0].sought = 1; vehicles[0].flipping = TRUE; + bots_vehicle_action(0, 0, &goal, FALSE, TRUE, 0, NONE, FALSE, &action); + CHECK(TEST_FLAG(action.control_flags, _unit_control_action_bit), "flip did not use ordinary action"); + } + + else if (!strcmp(argv[1],"human") || !strcmp(argv[1],"fast") || !strcmp(argv[1],"aircraft") || !strcmp(argv[1],"progress") || !strcmp(argv[1],"large")) + { + real_point3d entry; long surface; + units[0].object.parent_object_index=NONE; + units[1].object.position.x=10; + units[1].unit.driver_object_index=2; + units[0].unit.player_index=0; units[2].unit.player_index=1; + seat.flags=0; goal.x=15; + units[1].object.translational_velocity.i=.04f; + if (!strcmp(argv[1],"large")) { units[1].object.position.x=60;units[1].object.bounding_sphere_radius=60;entry_offset=-50; } + if (!strcmp(argv[1],"fast")) units[1].object.translational_velocity.i=.2f; + if (!strcmp(argv[1],"aircraft")) ((struct bots_vehicle_definition *)vehicle_tag)->type=3; + if (!strcmp(argv[1],"fast")) CHECK(!bots_vehicle_goal(0,0,&goal,&entry,&surface),"chased speeding driver"); + else { + CHECK(bots_vehicle_player_goal(0,0,&goal,&entry,&surface),"did not board nearby human on short journey"); + CHECK(vehicles[0].sought==1 && vehicles[0].seat==0,"wrong seat"); + if (!strcmp(argv[1],"progress")) { + now+=9*TICKS_PER_SECOND; + CHECK(!bots_vehicle_goal(0,0,&goal,&entry,&surface) && vehicles[0].sought==NONE,"unreachable seat retained forever"); + } + } + } + else if (!strcmp(argv[1], "airfailure") || !strcmp(argv[1], "airdriverless")) { + ((struct bots_vehicle_definition *)vehicle_tag)->type=3;goal.x=100; + flight_failed=!strcmp(argv[1],"airfailure");flight_grounded=TRUE; + if (!flight_failed) units[1].unit.driver_object_index=NONE; + bots_vehicle_action(0,0,&goal,TRUE,FALSE,0,NONE,FALSE,&action); + CHECK(TEST_FLAG(action.control_flags,_unit_control_action_bit),"grounded aircraft stranded bot far from its objective"); + if (flight_failed) { + units[0].object.parent_object_index=NONE; + bots_vehicle_action(0,0,&goal,TRUE,FALSE,0,NONE,FALSE,&action); + CHECK(!flight_failed && vehicles[0].avoided==1 && vehicles[0].avoided_until==now+120*TICKS_PER_SECOND,"failed flight immediately reused or retained stale flight state"); + } + } + else if (!strcmp(argv[1], "aircombat")) { + ((struct bots_vehicle_definition *)vehicle_tag)->type=3; + action.primary_trigger=1;action.control_flags=FLAG(_unit_control_weapon_primary_trigger_bit); + bots_vehicle_action(0,0,&goal,FALSE,TRUE,0,2,FALSE,&action); + CHECK(action.primary_trigger==1,"aligned aircraft shot suppressed"); + flight_turn=1; + bots_vehicle_action(0,0,&goal,FALSE,TRUE,0,2,FALSE,&action); + CHECK(!action.primary_trigger && !TEST_FLAG(action.control_flags,_unit_control_weapon_primary_trigger_bit),"flight steering fired away from enemy"); + } + else if (!strcmp(argv[1], "humangunner")) { + units[1].unit.driver_object_index=2; units[1].unit.gunner_object_index=0; + seat.flags=FLAG(_unit_seat_gunner_bit);goal.x=1; + bots_vehicle_action(0,0,&goal,TRUE,FALSE,0,NONE,FALSE,&action); + now+=10*TICKS_PER_SECOND; + bots_vehicle_action(0,0,&goal,TRUE,FALSE,0,NONE,FALSE,&action); + CHECK(!TEST_FLAG(action.control_flags,_unit_control_action_bit),"gunner abandoned human during quiet journey"); + } + else if (!strcmp(argv[1], "humanride")) { + units[1].unit.driver_object_index=2;seat.flags=0;goal.x=1; + bots_vehicle_action(0,0,&goal,TRUE,FALSE,0,NONE,FALSE,&action); + now+=60; + bots_vehicle_action(0,0,&goal,TRUE,FALSE,0,NONE,FALSE,&action); + CHECK(!TEST_FLAG(action.control_flags,_unit_control_action_bit),"passenger abandoned human near its old objective"); + units[1].unit.driver_object_index=NONE; + bots_vehicle_action(0,0,&goal,FALSE,FALSE,0,NONE,FALSE,&action); + now+=100; + bots_vehicle_action(0,0,&goal,FALSE,FALSE,0,NONE,FALSE,&action); + CHECK(TEST_FLAG(action.control_flags,_unit_control_action_bit),"passenger stayed after human left"); + } + else CHECK(0, "unknown case"); + return 0; +} diff --git a/tools/harness/tests/bots_combat.c b/tools/harness/tests/bots_combat.c new file mode 100644 index 0000000000..146cbcee84 --- /dev/null +++ b/tools/harness/tests/bots_combat.c @@ -0,0 +1,175 @@ +#include "harness.h" +#include "bots_combat.h" +#include +#include +#define TICKS_PER_SECOND 30 +#define REAL_MAX FLT_MAX +#define MIN(a,b) ((a)<(b)?(a):(b)) +#define PIN(a,l,h) ((a)<(l)?(l):(a)>(h)?(h):(a)) +#define NUMBEROF(a) (sizeof(a)/sizeof((a)[0])) +enum { _game_mode_swat = 1, _object_dead_bit = 0, _bots_goal_objective = 1 }; +struct bots_bot_combat {boolean head_aim;long throw_until_tick;real throw_lead;}; +struct bots_bot { struct bots_bot_combat combat; long player_index, aim_target, aim_until, guard_until_tick; unsigned long random; + boolean aim_head, aim_feet; short goal_kind; real_point3d goal; }; +struct player_datum { long unit_index; }; +struct object_datum { long definition_index; struct { real_point3d position; real shield_vitality; + unsigned long damage_flags; real_vector3d translational_velocity; } object; }; +struct data_iterator { long datum_index; }; +static struct player_datum players[3] = {{0},{1},{2}}; +static struct object_datum units[3]; +static int zombies[3], mode, scans, player_data, ground_valid = 1; +static long now = 100; +static char const *weapon_name = "weapons\\pistol\\pistol"; +static real_point3d points[2] = {{10,0,0},{100,0,0}}; +static struct { short skill;long combat_counts[1];struct bots_bot bots[1]; long roam_point_count; real_point3d *roam_points; } bots_globals; +static long game_time_get(void) { return now; } +static int game_modes_mode(void) { return mode; } +static struct player_datum *player_get(long i) { return &players[i]; } +static struct object_datum *object_get(long i) { return &units[i]; } +static struct object_datum *object_try_and_get(long i) { return i >= 0 && i < 3 ? &units[i] : NULL; } +static struct object_datum *weapon_get(long i) { (void)i; return &units[0]; } +static char const *tag_get_name(long i) { (void)i; return weapon_name; } +static void unit_get_head_position(long i, real_point3d *point) { *point = units[i].object.position; point->z += 1.5f; } +static long bots_surface_below(real_point3d const *point, real_point3d *ground) +{ *ground = *point; ground->z = 0; return ground_valid ? 0 : NONE; } +static boolean infection_unit_is_zombie(long i) { return zombies[i]; } +static void data_iterator_new(struct data_iterator *it, int data) { (void)data; it->datum_index = -1; scans++; } +static void *data_iterator_next(struct data_iterator *it) { return ++it->datum_index < 3 ? &players[it->datum_index] : NULL; } +static boolean bots_ctf_set_goal(struct bots_bot *bot, real_point3d const *point, real moved) +{ (void)moved; bot->goal = *point; bot->goal_kind = _bots_goal_objective; return TRUE; } +struct unit_datum {struct {real shield_vitality,body_vitality;} object;struct {unsigned long flags;} unit;}; +enum {_equipment_powerup_health,_equipment_powerup_overshield,_equipment_powerup_active_camouflage, + _unit_active_camouflaged_bit=0,game_engine_slayer=0}; +static struct {struct {int powerup_type;} equipment;} equipment_definition; +#define equipment_definition_get(index) (&equipment_definition) +static struct {int game_engine_index;} variant; +#define game_engine_get_variant() (&variant) +enum {_bots_combat_count_head_aims}; +struct bots_tick {long weapon_index,now;struct object_datum *object;real_point3d eye;}; +static struct {boolean precision;} weapon_kind={TRUE}; +#define bots_weapon_kind(index) (&weapon_kind) +static struct unit_definition {struct {real grenade_velocity;} unit;} unit_definition={{18}}; +#define unit_definition_get(index) (&unit_definition) +static real_point3d *bots_tick_eye(struct bots_tick *tick){return &tick->eye;} +#include "under_test.inc" + +int main(int argc, char **argv) +{ + struct bots_bot *bot = &bots_globals.bots[0]; + real_point3d eye = {0,0,2}, aim = {5,0,1}, position = {0,0,0}; + unsigned long random; + CHECK(argc == 2, "case"); + bot->aim_target = NONE; + units[1].object.position.x = 5; + units[2].object.position.x = 100; + bots_globals.roam_point_count = 2; bots_globals.roam_points = points; + if (!strcmp(argv[1], "skill-mapping")) + { + /* The pre-merge four named difficulties are a compatibility contract. */ + short levels[4] = {_bots_skill_easy,_bots_skill_normal,_bots_skill_heroic,_bots_skill_legendary}; + real expected[4][5] = {{.15f,0,.35f,0,15},{.40f,.4f,.50f,.25f,25}, + {.70f,.8f,.65f,.35f,30},{1,1,.80f,.45f,40}}; + int i; + for(i=0;i<4;i++) { + CHECK(enhanced_skills[levels[i]].head==expected[i][0], "named head chance shifted"); + CHECK(enhanced_skills[levels[i]].feet==expected[i][1], "named feet chance shifted"); + CHECK(enhanced_skills[levels[i]].heal==expected[i][2], "named heal threshold shifted"); + CHECK(enhanced_skills[levels[i]].heal_fighting==expected[i][3], "named combat heal threshold shifted"); + CHECK(enhanced_skills[levels[i]].powerup_reach==expected[i][4], "named powerup reach shifted"); + } + for(i=0;iaim_until=0;bot->random=12345; + enhanced_bots_aim(0,(short)i,1,0,&eye,&aim); + CHECK(bot->aim_head==(i>=_bots_skill_normal), "aim consumer uses wrong row"); + CHECK(bot->aim_feet==(i>=_bots_skill_veteran), "feet consumer uses wrong row"); + unit.object.body_vitality=fighting[i]+.09f; + CHECK(enhanced_bots_retreat(&unit,(short)i,now), "retreat threshold too low"); + unit.object.body_vitality=fighting[i]+.11f; + CHECK(!enhanced_bots_retreat(&unit,(short)i,now), "retreat threshold too high"); + equipment_definition.equipment.powerup_type=_equipment_powerup_health; + unit.object.body_vitality=heal[i]-.01f; + CHECK(enhanced_bots_powerup_score(&unit,0,5,(short)i,FALSE,FALSE)0)CHECK(enhanced_bots_powerup_score(&unit,0,5,(short)i,TRUE,FALSE)random=1234567;bot->aim_until=0; + enhanced_bots_aim(0,_bots_skill_normal,1,0,&eye,&aim); + CHECK(!bot->aim_head&&aim.z==1,"base head aim bypassed enhanced chance"); + bot->random=12345;bot->aim_until=0; + enhanced_bots_aim(0,_bots_skill_normal,1,0,&eye,&aim); + CHECK(bot->aim_head&&aim.z==1.5f,"enhanced head choice lost"); + bot->combat.throw_until_tick=101;bot->combat.throw_lead=1; + units[1].object.translational_velocity.i=.1f;aim.x=5; + enhanced_level_aim_point(bot,&tick,1,&aim); + CHECK(aim.x>5&&aim.x<=8.5f,"enhanced mode disabled bounded grenade lead"); + } + else if (!strcmp(argv[1], "precision") || !strcmp(argv[1], "swat")) + { + if (!strcmp(argv[1], "swat")) { mode = _game_mode_swat; weapon_name = "assault rifle"; } + else units[1].object.shield_vitality = 1; + enhanced_bots_aim(0, _bots_skill_legendary, 1, 0, &eye, &aim); + CHECK(aim.z == (mode ? 1.5f : 1.0f), "shield/SWAT aim rule"); + random = bot->random; + units[1].object.shield_vitality = 0; + enhanced_bots_aim(0, _bots_skill_legendary, 1, 0, &eye, &aim); + CHECK(aim.z == 1.5f && random == bot->random, "head choice rerolled during burst"); + } + else if (!strcmp(argv[1], "explosive")) + { + weapon_name = "rocket launcher"; + enhanced_bots_aim(0, _bots_skill_legendary, 1, 0, &eye, &aim); + CHECK(aim.z == 0.1f, "grounded rocket target not aimed at feet"); + units[1].object.position.z = 3; aim.z = 1; + enhanced_bots_aim(0, _bots_skill_legendary, 1, 0, &eye, &aim); + CHECK(aim.z == 1, "airborne target aimed at ground"); + units[1].object.position.z = 0; ground_valid = 0; + enhanced_bots_aim(0, _bots_skill_legendary, 1, 0, &eye, &aim); + CHECK(aim.z == 1, "missing ground accepted"); + } + else if (!strcmp(argv[1], "infection")) + { + zombies[0] = 1; + CHECK(bots_infection_goal(bot, &players[0], &position) && bot->goal.x == 5, "zombie ignored nearest human"); + bots_infection_goal(bot, &players[0], &position); + CHECK(scans == 1, "role snapshot rescanned within tick"); + zombies[1] = 1; now += 30; + CHECK(bots_infection_goal(bot, &players[0], &position) && bot->goal.x == 100, "converted target retained"); + zombies[0] = 0; bot->goal_kind = 0; now += 30; + CHECK(bots_infection_goal(bot, &players[0], &position) && bot->goal.x == 100, "human failed to regroup"); + } + else if (!strcmp(argv[1], "alone")) + { + zombies[1] = zombies[2] = 1; units[2].object.position.x = 6; + CHECK(bots_infection_goal(bot, &players[0], &position) && bot->goal.x == 100, "last human approached zombies"); + } + else CHECK(0, "case"); + return 0; +} diff --git a/tools/harness/tests/bots_controller_lifecycle.c b/tools/harness/tests/bots_controller_lifecycle.c new file mode 100644 index 0000000000..3e39ccb68d --- /dev/null +++ b/tools/harness/tests/bots_controller_lifecycle.c @@ -0,0 +1,38 @@ +#include "harness.h" +#define BOTS_MAXIMUM 63 +#define csmemset memset +static boolean bots_enhanced_running, enabled; +static long stock_releases, enhanced_starts, enhanced_stops, management_resets; +static struct { + struct { long player_index; } bots[BOTS_MAXIMUM]; + boolean map_ready; + long roam_point_count, ticks, searches, search_failures, search_partials; + long search_overflows, search_unavoided, search_unsmoothed, stuck_events, stuck_giveups; + long combat_counts[20], last_report_tick; +} bots_globals; +static struct { long count; } bots_weapon_kinds; +static boolean config_boolean(char const *name) { CHECK(!strcmp(name,"bots.enhanced"),"setting"); return enabled; } +static void bots_management_reset(void) { management_resets++; } +static void enhanced_controller_initialize(void) { enhanced_starts++; } +static void enhanced_controller_dispose(void) { enhanced_stops++; } +static void bots_paths_release(void) { stock_releases++; } +#include "under_test.inc" +int main(void) +{ + bots_initialize_for_new_map(); + CHECK(!bots_enhanced_running && !enhanced_starts,"stock initialized enhanced state"); + enabled=TRUE; + bots_dispose_from_old_map(); + CHECK(stock_releases==1 && !enhanced_stops,"changed setting disposed the wrong map owner"); + bots_initialize_for_new_map(); + CHECK(bots_enhanced_running && enhanced_starts==1,"enhanced controller was not selected"); + enabled=FALSE; + CHECK(bots_enhanced_running,"setting changed the running controller mid-map"); + bots_dispose_from_old_map(); + CHECK(!bots_enhanced_running && enhanced_stops==1 && stock_releases==1,"enhanced cleanup leaked into stock"); + bots_initialize_for_new_map(); + CHECK(!bots_enhanced_running && enhanced_starts==1,"enhanced mode leaked into the next stock map"); + bots_dispose_from_old_map(); + CHECK(stock_releases==2 && management_resets==6,"common admission lifecycle was skipped"); + return 0; +} diff --git a/tools/harness/tests/bots_lifecycle.c b/tools/harness/tests/bots_lifecycle.c new file mode 100644 index 0000000000..ce3c690927 --- /dev/null +++ b/tools/harness/tests/bots_lifecycle.c @@ -0,0 +1,36 @@ +#include "harness.h" + +static struct { void *node_of_surface, *cost, *previous, *heap, *heap_position; long link_capacity; } bots_routes; +static struct { void *nodes, *link_first, *links; long node_count, link_count; } bots_graph; +static struct { void *grid_area, *grid_height_sum; } bots_vantage; +static int frees; +static void game_free(void *memory) +{ + CHECK(memory != NULL, "the engine allocator rejects free(NULL)"); + free(memory); + frees++; +} +#define free game_free +#include "under_test.inc" + +int main(int argc, char **argv) +{ + (void)argc; + (void)argv; + bots_routes_free(); + bots_vantage_free(); + CHECK(frees == 0, "initial disposal freed memory"); + /* A failed allocation can leave only part of each structure allocated. */ + bots_routes.cost = malloc(16); + bots_graph.nodes = malloc(16); + bots_graph.node_count = 4; + bots_vantage.grid_area = malloc(16); + bots_routes_free(); + bots_vantage_free(); + CHECK(frees == 3 && !bots_routes.cost && !bots_graph.nodes && !bots_vantage.grid_area, "partial allocations leaked"); + CHECK(!bots_graph.node_count && !bots_graph.link_count && !bots_routes.link_capacity, "stale graph bounds"); + bots_routes_free(); + bots_vantage_free(); + CHECK(frees == 3, "repeated disposal"); + return 0; +} diff --git a/tools/harness/tests/bots_lobby.c b/tools/harness/tests/bots_lobby.c index 9f20c6a95d..3aff85a439 100644 --- a/tools/harness/tests/bots_lobby.c +++ b/tools/harness/tests/bots_lobby.c @@ -14,6 +14,8 @@ constants and structures (config.inc) and the code (under_test.inc). typedef unsigned short word; #define VALID_INDEX(index, count) ((index) >= 0 && (index) < (count)) +#define MIN(a, b) ((a) < (b) ? (a) : (b)) +#define MAX(a, b) ((a) > (b) ? (a) : (b)) #define PIN(value, low, high) ((value) < (low) ? (low) : (value) > (high) ? (high) : (value)) #define NUMBEROF(array) (sizeof(array) / sizeof((array)[0])) #define csmemset memset @@ -45,19 +47,73 @@ struct network_game_server word state; struct network_game game; boolean sent_start_game_message; + struct client_machine { short machine_index; } client_machines[HALO_PORT_MAXIMUM_NETWORK_MACHINES]; + boolean queued_player_valid; + long waiting_player_count; }; /* the world the lobby asks */ static boolean local_game; +static boolean enhanced; +static boolean network_option; static long wanted; static short teams_setting; static long sends; static short next_color; +static struct network_game_server server; +static boolean is_host = TRUE, has_teams = TRUE, encode_ok = TRUE; +static long tick = 100, messages, joined, removed; +static int last_message_type; +enum { _message_server_add_player_ingame, _message_server_remove_player_ingame }; +struct message_server_remove_player_ingame { struct network_player player; long reason; }; +static long game_time_get(void) { return tick; } +static boolean game_engine_has_teams(void) { return has_teams; } +static int bots_enhanced_running; +static boolean slots_held, additions_allowed = TRUE; +static unsigned long milliseconds; +#define TICKS_PER_SECOND 30 +static unsigned long system_milliseconds(void) { return milliseconds; } +static int network_game_server_get_state(struct network_game_server *s, void *unused) +{ (void)unused; return s->state; } +static struct network_game *network_game_server_get_game(struct network_game_server *s) +{ return &s->game; } +static boolean network_game_server_client_machine_is_joined_to_game(struct network_game_server *s, struct client_machine *m) +{ (void)s; return m->machine_index != NONE; } +static boolean network_game_server_machine_may_add_player_ingame(struct network_game_server *s, long m) +{ (void)s; (void)m; return additions_allowed; } +void bots_management_reset(void); +static void *create_network_game_message(int type, const void *record, short size) +{ + (void)size; + last_message_type = type; + if (type == _message_server_add_player_ingame) { + const struct network_player *joining = record; + long player_slot = joining->player_list_index; + CHECK(VALID_INDEX(player_slot, NETWORK_GAME_PLAYER_SLOTS), "missing authoritative join slot"); + CHECK(server.game.players[(unsigned char)joining->player_list_index].machine_index == joining->machine_index, + "join slot differs from host"); + } + if (type == _message_server_remove_player_ingame) { + const struct message_server_remove_player_ingame *leaving = record; + CHECK(leaving->reason == tick + NETWORK_GAME_PLAYER_QUIT_DELAY, "quit tick"); + } + return encode_ok ? (void *)1 : NULL; +} +static boolean network_game_server_send_message_to_all_machines(struct network_game_server *game, void *message) +{ + (void)game; (void)message; + messages++; + if (last_message_type == _message_server_add_player_ingame) joined++; + else removed++; + return TRUE; +} static boolean network_game_is_splitscreen_local(void) { return local_game; } +static int config_boolean(const char *name) { return !strcmp(name, "bots.network") ? network_option : enhanced; } +static struct network_game_server *global_network_game_server_get(void) { return is_host ? &server : NULL; } static long bots_wanted_count(void) { return wanted; } static short bots_teams(void) { return teams_setting; } -static boolean network_game_player_slot_held(long player_index) { (void)player_index; return FALSE; } +static boolean network_game_player_slot_held(long player_index) { (void)player_index; return slots_held; } static void get_unique_random_color(struct network_game_server *server, struct network_player *player) { (void)server; @@ -76,7 +132,6 @@ machine index against the session's 128) */ #pragma clang diagnostic ignored "-Wtautological-constant-out-of-range-compare" #include "under_test.inc" -static struct network_game_server server; /* a pregame lobby of the game engine, room for `maximum`, and its players */ static void lobby(short game_engine_index, long maximum) @@ -89,6 +144,8 @@ static void lobby(short game_engine_index, long maximum) server.game.maximum_players = (byte)maximum; for (index = 0; index < HALO_PORT_MAXIMUM_NETWORK_PLAYERS; index++) network_game_invalidate_player(&server.game.players[index]); + for (index = 0; index < HALO_PORT_MAXIMUM_NETWORK_MACHINES; index++) + server.client_machines[index].machine_index = NONE; local_game = TRUE; teams_setting = _bots_teams_even; sends = 0; @@ -155,9 +212,316 @@ int main(int argc, char **argv) { char const *case_name = argc > 1 ? argv[1] : ""; long team0, team1, count; + char status[180]; + if (!strncmp(case_name, "population-", 11) || !strcmp(case_name, "human-count")) + { + struct network_player joining, leaving; + lobby(game_engine_slayer, 4); + player(0, 0); + server.client_machines[0].machine_index = 0; + local_game = FALSE; + network_option = TRUE; + wanted = 3; + bots_network_session_begin(); + network_game_server_port_bots(&server); + memset(&joining, 0, sizeof(joining)); + joining.machine_index = 1; + joining.controller_index = 0; + joining.player_list_index = NONE; + server.client_machines[1].machine_index = 1; + CHECK(bots_human_count(&server.game) == 1 && bots_population_count(&server.game) == 3, "initial population"); + CASE("human-count") { + CHECK(bots_human_count(NULL) == 0, "null game"); + memcpy(server.game.players[0].name, L"BOT Johnson", sizeof(L"BOT Johnson")); + CHECK(bots_human_count(&server.game) == 1, "bot-like human name hidden"); + server.game.players[0].machine_index = BOTS_FIRST_MACHINE + 20; + CHECK(bots_human_count(&server.game) == 1, "high-ID human hidden"); + CHECK(server.game.player_count == 4, "reporting modified roster"); + return 0; + } + CASE("population-lobby") { + CHECK(!lobby_join_full(&server), "bot-filled lobby rejected connection before admission"); + CHECK(bots_population_can_join(&server), "bot-filled lobby closed"); + bots_population_pregame_join(&server, &joining); + CHECK(network_game_add_player(&server.game, &joining), "human cannot replace bot"); + network_game_server_port_bots(&server); + CHECK(server.game.player_count == 4 && bots_human_count(&server.game) == 2, "lobby did not retain human capacity"); + CHECK(network_game_remove_player(&server.game, &joining), "human departure"); + network_game_server_port_bots(&server); + CHECK(server.game.player_count == 4 && bots_population_count(&server.game) == 3, "lobby restoration"); + return 0; + } + server.state = _network_game_server_state_ingame; + CASE("population-empty") { + leaving = server.game.players[0]; + CHECK(network_game_remove_player(&server.game, &leaving), "last human left"); + bots_population_update(&server); + CHECK(bots_human_count(&server.game) == 0 && bots_population_count(&server.game) == 3, "empty human count or bot ceiling"); + CHECK(!bots_population_wait_for_slot(&server, &joining), "empty space unnecessarily reserved"); + CHECK(network_game_add_player(&server.game, &joining), "human return"); + CHECK(bots_population_count(&server.game) == 3, "vacant space displaced an extra bot"); + return 0; + } + CASE("population-invalid") { + joining.controller_index = MAXIMUM_LOCAL_PLAYERS; + CHECK(!bots_population_wait_for_slot(&server, &joining), "invalid controller reserved"); + joining.controller_index = 0; + server.client_machines[1].machine_index = NONE; + CHECK(!bots_population_wait_for_slot(&server, &joining), "unvalidated machine reserved"); + server.client_machines[1].machine_index = 1; + additions_allowed = FALSE; + CHECK(!bots_population_wait_for_slot(&server, &joining), "rate-limited machine reserved"); + CHECK(bots_population_count(&server.game) == 3, "invalid join removed bots"); + return 0; + } + CASE("population-manual") { + CHECK(bots_manage(FALSE, NONE, status, sizeof(status)), "manual drop"); + tick += 90; + bots_population_update(&server); + CHECK(bots_population_count(&server.game) == 2, "manual drop restored"); + CHECK(bots_manage(TRUE, NONE, status, sizeof(status)), "manual add"); + tick += 90; + bots_population_update(&server); + CHECK(bots_population_count(&server.game) == 3, "manual add removed"); + return 0; + } + CASE("population-manual-crowded") { + long i; + server.game.maximum_players = 8; + for (i = 1; i <= 4; i++) { + joining.machine_index = (char)i; + joining.player_list_index = NONE; + server.client_machines[i].machine_index = (short)i; + CHECK(!bots_population_wait_for_slot(&server, &joining), "vacant slot delayed"); + CHECK(network_game_add_player(&server.game, &joining), "humans could not exceed initial target"); + } + CHECK(bots_human_count(&server.game) == 5 && !bots_population_count(&server.game), "crowded setup"); + tick += 90; + CHECK(bots_manage(TRUE, NONE, status, sizeof(status)), "manual add above target"); + bots_population_update(&server); + CHECK(bots_population_count(&server.game) == 1, "manual addition immediately removed"); + return 0; + } + CASE("population-human-full") { + long i; + for (i = 0; i < 128; i++) if (bots_player_owned(server.game.players[i].machine_index)) + bots_player_ownership(server.game.players[i].machine_index, FALSE); + CHECK(!bots_population_can_join(&server), "full-human game advertised open"); + server.state = _network_game_server_state_pregame; + CHECK(lobby_join_full(&server), "full-human lobby admitted connection"); + server.state = _network_game_server_state_ingame; + CHECK(!bots_population_wait_for_slot(&server, &joining), "full-human join deferred"); + CHECK(server.game.player_count == 4, "human removed"); + return 0; + } + if (!strcmp(case_name, "population-wait") || !strcmp(case_name, "population-cancel")) { + slots_held = TRUE; + CHECK(bots_population_wait_for_slot(&server, &joining), "held departure not awaited"); + CHECK(bots_population_count(&server.game) == 2, "wrong number evicted"); + milliseconds += 100; + CHECK(bots_population_wait_for_slot(&server, &joining), "reservation lost"); + CHECK(bots_population_count(&server.game) == 2, "repeat evicted another bot"); + if (!strcmp(case_name, "population-wait")) { + milliseconds += 10000; + CHECK(!bots_population_wait_for_slot(&server, &joining), "unbounded reservation"); + } else { + server.client_machines[1].machine_index = NONE; + CHECK(!bots_population_wait_for_slot(&server, &joining), "cancelled connection retained"); + } + slots_held = FALSE; + tick += 90; + bots_population_update(&server); + CHECK(bots_population_count(&server.game) == 3, "failed join permanently removed bot"); + return 0; + } + if (!strcmp(case_name, "population-split")) { + joining.machine_index = 0; + joining.controller_index = 1; + } + /* A target below the server limit must not grow when a human joins. */ + if (!strcmp(case_name, "population-live")) server.game.maximum_players = 8; + CHECK(!bots_population_wait_for_slot(&server, &joining), "free slot delayed"); + CHECK(network_game_add_player(&server.game, &joining), "join after departure"); + CHECK(bots_human_count(&server.game) == 2 && bots_population_count(&server.game) == 2, "one-in one-out"); + CHECK(!bots_population_wait_for_slot(&server, &joining), "duplicate join reserved"); + CHECK(bots_population_count(&server.game) == 2, "duplicate join displaced bot"); + tick += 90; + bots_population_update(&server); + CHECK(bots_population_count(&server.game) == 2, "restoration ignored the newly joined human"); + CASE("population-concurrent") { + struct network_player second = joining; + second.controller_index = 1; + second.player_list_index = NONE; + CHECK(!bots_population_wait_for_slot(&server, &second), "second queued human delayed"); + CHECK(network_game_add_player(&server.game, &second), "second human join"); + CHECK(bots_human_count(&server.game) == 3 && bots_population_count(&server.game) == 1, "two joins did not replace two bots"); + CHECK(network_game_remove_player(&server.game, &second), "second human departure"); + CHECK(network_game_remove_player(&server.game, &joining), "first human departure"); + tick += 90; + bots_population_update(&server); + tick += 90; + bots_population_update(&server); + CHECK(bots_population_count(&server.game) == 3, "two humans did not restore two bots"); + return 0; + } + CASE("population-lifecycle") { + bots_management_reset(); + server.state = _network_game_server_state_pregame; + network_game_server_port_bots(&server); + CHECK(bots_population_count(&server.game) == 2, "map change reset target"); + bots_network_session_end(); + bots_network_session_begin(); + server.game.maximum_players = 8; + CHECK(bots_population_wanted(&server.game) == 3, "old session target leaked"); + return 0; + } + leaving = joining; + CHECK(network_game_remove_player(&server.game, &leaving), "human remove"); + tick += 90; + CASE("population-queue") { + server.waiting_player_count = 1; + bots_population_update(&server); + CHECK(bots_population_count(&server.game) == 2, "restoration stole queued human slot"); + server.waiting_player_count = 0; + } + bots_population_update(&server); + CHECK(bots_population_count(&server.game) == 3 && server.game.player_count == 4, "live restoration"); + return 0; + } + + CASE("lobby-enable") + { + lobby(game_engine_slayer, 128); + player(0, 0); + local_game = FALSE; + bots_network_session_begin(); + network_option = TRUE; + wanted = 63; + CHECK(bots_lobby_settings_apply(status, sizeof(status)), "lobby apply refused: %s", status); + CHECK(server.game.player_count == 64, "settings saved in lobby did not add 63 bots"); + CHECK(bots_network_reserved() && bots_session_allowed(), "IDs were not reserved before admission"); + CHECK(sends == 1, "new lobby not published once"); + CHECK(bots_lobby_settings_apply(status, sizeof(status)) && sends == 1, "reapply changed unchanged lobby"); + CHECK(bots_player_owned(BOTS_FIRST_MACHINE + 62), "last bot ownership lost"); + wanted = 1; + CHECK(bots_lobby_settings_apply(status, sizeof(status)) && server.game.player_count == 2, "count reduction ignored"); + CHECK(bots_player_owned(BOTS_FIRST_MACHINE), "remaining ownership reset"); + bots_network_session_end(); + CHECK(!bots_network_reserved() && !bots_session_allowed(), "session state leaked"); + return 0; + } + CASE("lobby-disable") + { + lobby(game_engine_slayer, 128); player(0, 0); local_game = FALSE; + network_option = TRUE; bots_network_session_begin(); wanted = 63; + CHECK(bots_lobby_settings_apply(status, sizeof(status)) && server.game.player_count == 64, "initial bots absent"); + network_option = FALSE; + CHECK(bots_lobby_settings_apply(status, sizeof(status)), "disable refused"); + CHECK(server.game.player_count == 1 && !bots_session_allowed(), "disabled bots stayed"); + CHECK(bots_network_reserved(), "identity reservation released before session end"); + network_option = TRUE; + CHECK(bots_lobby_settings_apply(status, sizeof(status)) && server.game.player_count == 64, "reenable failed"); + wanted = 0; + CHECK(bots_lobby_settings_apply(status, sizeof(status)) && server.game.player_count == 1, "zero count ignored"); + return 0; + } + CASE("lobby-enable-conflict") + { + struct network_player *human; + lobby(game_engine_slayer, 128); human = player(0, 0); local_game = FALSE; + bots_network_session_begin(); network_option = TRUE; wanted = 63; + server.client_machines[BOTS_FIRST_MACHINE].machine_index = BOTS_FIRST_MACHINE; + CHECK(!bots_lobby_settings_apply(status, sizeof(status)) && strstr(status, "Re-host"), "pending client conflict hidden"); + CHECK(!bots_network_reserved() && !bots_session_allowed() && server.game.player_count == 1, "pending client stolen"); + server.client_machines[BOTS_FIRST_MACHINE].machine_index = NONE; + human->machine_index = BOTS_FIRST_MACHINE + 62; + CHECK(!bots_lobby_settings_apply(status, sizeof(status)), "high-ID human stolen"); + CHECK(!bots_player_owned(human->machine_index) && sends == 0, "human ownership changed"); + human->machine_index = 0; + CHECK(bots_lobby_settings_apply(status, sizeof(status)) && server.game.player_count == 64, "released IDs unusable"); + return 0; + } + CASE("lobby-apply-guards") + { + lobby(game_engine_slayer, 128); player(0, 0); local_game = FALSE; + bots_network_session_begin(); network_option = TRUE; wanted = 63; + is_host = FALSE; + CHECK(bots_lobby_settings_apply(status, sizeof(status)) && !bots_network_reserved(), "client changed host policy"); + is_host = TRUE; server.sent_start_game_message = TRUE; + CHECK(bots_lobby_settings_apply(status, sizeof(status)) && !bots_network_reserved(), "loading changed policy"); + server.sent_start_game_message = FALSE; server.state = _network_game_server_state_ingame; + CHECK(bots_lobby_settings_apply(status, sizeof(status)) && !bots_network_reserved(), "ingame enabled policy"); + server.state = _network_game_server_state_pregame; + CHECK(bots_lobby_settings_apply(status, sizeof(status)) && server.game.player_count == 64, "pregame not applied"); + server.state = _network_game_server_state_ingame; network_option = FALSE; + CHECK(bots_lobby_settings_apply(status, sizeof(status)) && bots_session_allowed(), "live bot AI stopped"); + CHECK(server.game.player_count == 64 && bots_player_owned(BOTS_FIRST_MACHINE), "live roster reset"); + bots_network_session_end(); bots_network_session_begin(); + CHECK(!bots_network_reserved() && !bots_session_allowed(), "disabled policy not read on next host"); + lobby(game_engine_slayer, 16); player(0, 0); + CHECK(bots_lobby_settings_apply(status, sizeof(status)) && server.game.player_count == 16, "local capacity changed"); + CHECK(!bots_network_reserved(), "local settings reserved network IDs"); + return 0; + } + + CASE("live") + { + long i; + lobby(game_engine_slayer, 128); + player(0, 0); + server.state = _network_game_server_state_ingame; + for (i = 0; i < 63; i++) CHECK(bots_manage(TRUE, NONE, status, sizeof(status)), "join %ld: %s", i, status); + CHECK(!bots_manage(TRUE, NONE, status, sizeof(status)) && joined == 63, "over capacity"); + CHECK(bots_in(&team0, &team1) == 63 && team0 == 31 && team1 == 32, "unbalanced live bots"); + CHECK(bots_manage(FALSE, 1, status, sizeof(status)), "team removal"); + CHECK(removed == 1 && !bots_manage(TRUE, NONE, status, sizeof(status)), "premature identity reuse"); + tick += NETWORK_GAME_PLAYER_QUIT_DELAY + 1; + CHECK(bots_manage(TRUE, 0, status, sizeof(status)) && joined == 64, "identity never reusable"); + CHECK(bots_in(&team0, &team1) == 63 && team0 == 32 && team1 == 31, "explicit team ignored"); + return 0; + } + CASE("live-permissions") + { + lobby(game_engine_slayer, 128); + player(0, 0); + CHECK(!bots_manage(TRUE, NONE, status, sizeof(status)), "lobby used live joins"); + server.state = _network_game_server_state_ingame; + is_host = FALSE; + CHECK(!bots_manage(TRUE, NONE, status, sizeof(status)), "client changed host"); + is_host = TRUE; local_game = FALSE; + CHECK(!bots_manage(TRUE, NONE, status, sizeof(status)), "network default ignored"); + network_option = TRUE; bots_network_session_begin(); + has_teams = FALSE; + CHECK(!bots_manage(TRUE, 0, status, sizeof(status)) && !bots_manage(TRUE, 2, status, sizeof(status)), "invalid team"); + CHECK(bots_manage(TRUE, NONE, status, sizeof(status)), "FFA bot refused"); + CHECK(bots_manage(FALSE, NONE, status, sizeof(status)), "FFA removal refused"); + CHECK(!bots_manage(FALSE, NONE, status, sizeof(status)), "removed a human"); + CHECK(server.game.player_count == 1, "lost human"); + server.game.variant.game_engine_index = game_engine_ctf; + enhanced = TRUE; + CHECK(!bots_manage(TRUE, NONE, status, sizeof(status)), "unloaded tactics enabled by live setting"); + bots_enhanced_running = TRUE; + CHECK(bots_manage(TRUE, NONE, status, sizeof(status)), "loaded CTF tactics refused"); + bots_network_session_end(); + CHECK(!bots_manage(TRUE, NONE, status, sizeof(status)), "host policy survived session end"); + return 0; + } + CASE("live-encode-failure") + { + lobby(game_engine_slayer, 128); player(0, 0); + server.state = _network_game_server_state_ingame; + encode_ok = FALSE; + CHECK(!bots_manage(TRUE, NONE, status, sizeof(status)) && server.game.player_count == 1, "failed join changed host"); + encode_ok = TRUE; + CHECK(bots_manage(TRUE, NONE, status, sizeof(status)), "join refused"); + encode_ok = FALSE; + CHECK(!bots_manage(FALSE, NONE, status, sizeof(status)) && server.game.player_count == 2, "failed quit changed host"); + CHECK(messages == 1, "failed encode sent a message"); + return 0; + } /* as many as asked for, once: the lobby unchanged after (nothing sent - again); more than 15 asked for is 15 */ + again); a 16-player lobby still has room for only 15 bots */ CASE("fills") { lobby(game_engine_slayer, 16); @@ -280,6 +644,51 @@ int main(int argc, char **argv) return 0; } /* nothing changes once the game is started, nor in the game */ + CASE("enhanced-objectives") + { + lobby(game_engine_ctf, 16); + player(0, 0); + wanted = 4; + enhanced = TRUE; + network_game_server_port_bots(&server); + CHECK(bots_in(&team0, &team1) == 4, "enhanced CTF bots absent"); + server.game.variant.game_engine_index = game_engine_king; + network_game_server_port_bots(&server); + CHECK(bots_in(&team0, &team1) == 4, "enhanced King bots absent"); + enhanced = FALSE; + network_game_server_port_bots(&server); + CHECK(bots_in(&team0, &team1) == 0, "disabled objectives retained bots"); + return 0; + } + CASE("network-opt-in") + { + lobby(game_engine_slayer, 128); + player(0, 0); + local_game = FALSE; + wanted = 6; + network_option = TRUE; + bots_network_session_begin(); + network_game_server_port_bots(&server); + CHECK(bots_in(&team0, &team1) == 6, "opted-in host has no bots"); + network_option = FALSE; + CHECK(bots_network_reserved(), "IDs changed in a live session"); + bots_network_session_end(); + bots_network_session_begin(); + CHECK(!bots_network_reserved() && !bots_session_allowed(), "policy leaked into next session"); + return 0; + } + CASE("human-high-id") + { + lobby(game_engine_slayer, 128); + player(0, 0)->machine_index = BOTS_FIRST_MACHINE; + local_game = FALSE; + wanted = 6; + bots_network_session_begin(); + CHECK(!bots_player_owned(BOTS_FIRST_MACHINE), "human high ID acquired bot ownership"); + network_game_server_port_bots(&server); + CHECK(server.game.player_count == 1, "ordinary host removed a high-ID human"); + return 0; + } CASE("not-once-started") { lobby(game_engine_slayer, 16); @@ -307,11 +716,11 @@ int main(int argc, char **argv) colour of its own */ CASE("names-and-machines") { - long index, named = 0; + long index, other, named = 0; - lobby(game_engine_slayer, 16); + lobby(game_engine_slayer, 128); player(0, 0); - wanted = 15; + wanted = 99; network_game_server_port_bots(&server); for (index = 0; index < HALO_PORT_MAXIMUM_NETWORK_PLAYERS; index++) { @@ -326,8 +735,20 @@ int main(int argc, char **argv) CHECK(slot->primary_color_index != NONE, "bot of machine %d has no colour", slot->machine_index); if (slot->name[0]) named++; + CHECK(slot->name[NUMBEROF(slot->name) - 1] == 0, "unterminated bot name"); + CHECK(!wcsncmp(slot->name, L"BOT ", 4), "missing bot prefix"); + if (slot->machine_index == BOTS_FIRST_MACHINE) + CHECK(!wcscmp(slot->name, L"BOT Johnson"), "first bot name changed"); + if (slot->machine_index == BOTS_FIRST_MACHINE + 3) + CHECK(!wcscmp(slot->name, L"BOT Bisenti"), "Bisenti name changed"); + if (slot->machine_index == BOTS_FIRST_MACHINE + 15) + CHECK(!wcscmp(slot->name, L"BOT Johns16"), "numbered bot name lost identity"); + for (other = 0; other < index; other++) + if (bots_player_owned(server.game.players[other].machine_index)) + CHECK(wcscmp(slot->name, server.game.players[other].name), "duplicate bot name"); } - CHECK(named == 15, "%ld of 15 bots named", named); + CHECK(named == 63, "%ld of 63 bots named", named); + CHECK(server.game.player_count == 64, "capacity was not capped at 63 bots"); CHECK(!bots_machine_is_bot(0) && !bots_machine_is_bot(BOTS_FIRST_MACHINE - 1), "a real machine is a bot"); return 0; } diff --git a/tools/harness/tests/bots_menu.c b/tools/harness/tests/bots_menu.c new file mode 100644 index 0000000000..79fdbf6a18 --- /dev/null +++ b/tools/harness/tests/bots_menu.c @@ -0,0 +1,71 @@ +#include "harness.h" +#include +#define NUMBEROF(a) (sizeof(a) / sizeof((a)[0])) + +struct widget_instance { + char const *name; int visible; + struct { struct { struct widget_instance *extended_description; } list; } parameters; +}; +static int host, calls, last_add, last_team; +static int saves, applies, apply_ok = TRUE, errors; +static wchar_t displayed[180]; +static struct widget_instance description, options; +static void *global_network_game_server_get(void) { return host ? (void *)1 : NULL; } +static struct widget_instance *screen_of(struct widget_instance *widget) { return widget; } +static struct widget_instance *named(struct widget_instance *widget, char const *name, int index) +{ (void)widget; (void)index; CHECK(!strcmp(name, "options_menu"), "wrong list"); return &options; } +static void text_set(struct widget_instance *widget, wchar_t const *text) +{ CHECK(widget == &description, "status did not target list description"); wcsncpy(displayed, text, 179); displayed[179] = 0; } +static int bots_manage(int add, int team, char *status, long size) +{ + calls++; last_add = add; last_team = team; + snprintf(status, size, "Host result"); + return host; +} +static void console_printf(int color, char const *format, ...) { (void)color; (void)format; } +struct pc_menu_setting; +static boolean setting_changed_save(struct widget_instance *widget, struct pc_menu_setting *setting) +{ (void)widget; (void)setting; return TRUE; } +static void settings_each(struct widget_instance *widget, + boolean (*visit)(struct widget_instance *, struct pc_menu_setting *)) +{ (void)widget; CHECK(visit == setting_changed_save, "wrong save callback"); saves++; } +static int bots_lobby_settings_apply(char *status, long size) +{ CHECK(saves == applies + 1, "policy applied before saving choices"); applies++; snprintf(status, size, "Slot conflict"); return apply_ok; } +static void display_error_text_deferred(wchar_t const *message, short controller) +{ (void)controller; CHECK(!wcscmp(message, L"Slot conflict"), "missing rejection text"); errors++; } +#include "under_test.inc" + +int main(void) +{ + static char const *const rows[] = { "op_add_any", "op_add_red", "op_add_blue", + "op_drop_any", "op_drop_red", "op_drop_blue" }; + static char const *const commands[] = { "add_bot", "add_bot_red", "add_bot_blue", + "drop_bot", "drop_bot_red", "drop_bot_blue" }; + struct widget_instance widget = { "button_bots", TRUE, { { NULL } } }; + int index; + options.parameters.list.extended_description = &description; + CHECK(bots_menu_event(&description, "port bots init") && displayed[0], "initial help missing"); + CHECK(bots_menu_event(&widget, "port bots host entry") && !widget.visible, "client host button visible"); + host = TRUE; + CHECK(bots_menu_event(&widget, "port bots host entry") && widget.visible, "host button hidden"); + for (index = 0; index < 6; index++) { + widget.name = rows[index]; + CHECK(bots_menu_event(&widget, "port bots command"), "unhandled menu action"); + CHECK(last_add == (index < 3) && last_team == index % 3 - 1, "wrong menu team or operation"); + CHECK(!wcscmp(displayed, L"Host result"), "host result not shown"); + CHECK(bots_console_command(commands[index]) == TRUE, "console command unhandled"); + CHECK(last_add == (index < 3) && last_team == index % 3 - 1, "wrong console team or operation"); + } + CHECK(calls == 12, "duplicated action"); + CHECK(bots_console_command("add_bot unexpected") == -1 && bots_console_command("unknown") == -1, + "unrelated console command intercepted"); + host = FALSE; + CHECK(bots_console_command("add_bot") == FALSE, "host rejection hidden"); + widget.name = "button_ok"; + CHECK(!bots_menu_event(&widget, "unrelated") && saves == 0, "unrelated event applied settings"); + CHECK(bots_menu_event(&widget, "port bots settings save") && saves == 1 && applies == 1 && !errors, + "OK did not save then apply"); + apply_ok = FALSE; + CHECK(bots_menu_event(&widget, "port bots settings save") && errors == 1, "slot conflict was silent"); + return 0; +} diff --git a/tools/harness/tests/bots_navigation.c b/tools/harness/tests/bots_navigation.c new file mode 100644 index 0000000000..68a95aac27 --- /dev/null +++ b/tools/harness/tests/bots_navigation.c @@ -0,0 +1,169 @@ +#include "harness.h" +#include +#include +#define REAL_MAX FLT_MAX +#define BOTS_MAXIMUM 63 +#define TICKS_PER_SECOND 30 +#define BOTS_PATH_RADIUS 0.25f +#define PATH_NODE_LIST_SIZE 16 +#define BOTS_PI 3.14159265f +#define MAX(a,b) ((a) > (b) ? (a) : (b)) +#define MIN(a,b) ((a) < (b) ? (a) : (b)) +#define csmemset memset +#define platform_log(...) ((void)0) +enum { _bots_goal_none, _bots_goal_item, _bots_goal_vehicle, _bots_goal_enhanced }; +enum { _bots_role_attacker, _bots_role_defender }; +enum { _unit_control_weapon_primary_trigger_bit, _unit_control_jump_bit }; +struct structure_bsp { int unused; }; +struct bots_bot { short goal_kind; long goal_surface_index, path_tick, climb_until_tick; + long target_player_index, target_seen_tick; + long stuck_tick, stuck_count, unstick_until_tick; real unstick_direction; + real_point3d stuck_position; + real_point3d goal_point, last_position; struct { boolean valid; } path; }; +static struct { struct bots_bot bots[BOTS_MAXIMUM]; long stuck_events, stuck_giveups; } bots_globals; +static boolean bots_enhanced_running = TRUE; +struct object_datum { struct { long parent_object_index; } object; }; +struct bots_tick { long now; boolean moving; real_point3d position; real move_direction; + struct object_datum *object; unsigned long flags; }; +static real bots_random_real(struct bots_bot *bot) { (void)bot; return 0.0f; } +static void bots_goal_failed(struct bots_bot *bot) { bot->goal_kind = _bots_goal_none; } +static void bots_pick_roam_goal(struct bots_bot *bot, real_point3d const *position) +{ (void)bot; (void)position; } +struct bots_tactics_bot { short role, lane; boolean lane_given_up; }; +static struct bots_tactics_bot bots_tactics_bots[BOTS_MAXIMUM]; +struct path_node { real path_distance_from_origin; real_point3d entry_point; }; +struct path_state { short node_count, closest_node_index, heap_count; real closest_distance; + struct path_node node_list[16]; }; +struct player_action { struct { real yaw, pitch; } desired_facing; struct { real i, j; } throttle; + real primary_trigger; unsigned long control_flags; }; +static long now = 100; +static long game_time_get(void) { return now; } +static short path_node_from_hash_table(struct path_state *state, long surface) +{ return surface >= 0 && surface < state->node_count ? (short)surface : NONE; } +static real bots_distance3d(real_point3d const *a, real_point3d const *b) +{ real x=a->x-b->x, y=a->y-b->y, z=a->z-b->z; return (real)sqrt(x*x+y*y+z*z); } +static real bots_distance2d(real_point3d const *a, real_point3d const *b) +{ real x=a->x-b->x, y=a->y-b->y; return (real)sqrt(x*x+y*y); } +/* Game allocations use debug_free, which rejects NULL unlike libc free. */ +static void checked_free(void *pointer) { CHECK(pointer != NULL, "engine free received NULL"); free(pointer); } +#define free checked_free +#include "under_test.inc" + +int main(int argc, char **argv) +{ + struct bots_bot *bot = &bots_globals.bots[0]; + struct bots_nav_route *route = &bots_navigation.routes[0]; + struct bots_nav_link *link = &bots_navigation.links[0]; + struct path_state search; + real_point3d start = {0,0,0}, goal; + long start_surface = 0, goal_surface = 1; + real direction = 0; + struct player_action action; + CHECK(argc == 2, "case"); + memset(&search, 0, sizeof(search)); + memset(&action, 0, sizeof(action)); + bot->target_player_index = NONE; + bots_navigation.count = 1; + link->entrance.x = 10; link->entrance_surface = 0; + link->exit.x = 80; link->exit_surface = 1; + bot->goal_point.x = 100; bot->goal_surface_index = 1; bot->goal_kind = _bots_goal_enhanced; + search.node_count = 2; + search.node_list[0].entry_point = link->entrance; + search.node_list[0].path_distance_from_origin = 10; + search.node_list[1].entry_point = bot->goal_point; + search.node_list[1].path_distance_from_origin = 100; + if (!strcmp(argv[1], "measure") || !strcmp(argv[1], "reject")) + { + CHECK(!bots_navigation_answer(bot, &search, &start, TRUE, FALSE, 0.25f), "normal path lost"); + CHECK(route->phase == _bots_nav_exit, "shortcut did not request exit measurement"); + goal = bot->goal_point; + CHECK(bots_navigation_query(bot, &start, &start_surface, &goal, &goal_surface), "no measuring query"); + CHECK(start.x == 80 && start_surface == 1 && goal.x == 100, "exit query used bot's origin"); + search.node_list[1].path_distance_from_origin = !strcmp(argv[1], "reject") ? 95 : 20; + CHECK(bots_navigation_answer(bot, &search, &start, TRUE, FALSE, 0.25f), "measurement replaced path"); + if (!strcmp(argv[1], "reject")) CHECK(route->phase == _bots_nav_none, "expensive exit was accepted"); + else + { + CHECK(route->phase == _bots_nav_entry, "short exit refused"); + bots_navigation_query(bot, &start, &start_surface, &goal, &goal_surface); + CHECK(goal.x == 10 && goal_surface == 0, "entrance was not measured"); + CHECK(!bots_navigation_answer(bot, &search, &start, TRUE, FALSE, 0.25f), "entrance path discarded"); + CHECK(route->phase == _bots_nav_going, "validated shortcut not followed"); + bot->last_position.x = 10; start.x = 80; + bots_navigation_update(bot, &start, FALSE); + CHECK(route->phase == _bots_nav_none && link->successes == 1, "landing retained route"); + } + } + else if (!strcmp(argv[1], "reservation")) + { + bots_navigation.routes[1].phase = bots_navigation.routes[2].phase = _bots_nav_going; + bots_navigation_answer(bot, &search, &start, TRUE, FALSE, 0.25f); + CHECK(route->phase == _bots_nav_none, "crowded teleporter selected"); + bots_navigation_reset_bot(1); now += 151; + bots_navigation_answer(bot, &search, &start, TRUE, FALSE, 0.25f); + CHECK(route->phase == _bots_nav_exit, "released reservation still blocked entrance"); + } + else if (!strcmp(argv[1], "ladder")) + { + route->phase = _bots_nav_going; route->goal = bot->goal_point; route->deadline = 1000; + link->ladder = TRUE; link->top = 5; link->climb_direction = 1.0f; link->exit = link->entrance; link->exit.z = 5; + start = link->entrance; + CHECK(bots_navigation_follow(bot, &start, &direction) && direction == 1.0f, "ladder facing"); + bots_navigation_action(bot, &action); + CHECK(action.throttle.i == 1 && action.desired_facing.yaw == 1 && TEST_FLAG(action.control_flags, _unit_control_jump_bit), "ladder controls"); + start.z = 5; now += 30; + bots_navigation_follow(bot, &start, &direction); + CHECK(route->phase == _bots_nav_none && link->successes == 1, "ladder landing cleanup"); + } + else if (!strcmp(argv[1], "timeout")) + { + route->phase = _bots_nav_going; route->goal = bot->goal_point; route->deadline = now-1; + bots_navigation_update(bot, &start, FALSE); + CHECK(route->phase == _bots_nav_none && link->failures == 1 && link->rest_until == now+900, "failure cooldown"); + now += 151; + bots_navigation_answer(bot, &search, &start, TRUE, FALSE, 0.25f); + CHECK(route->phase == _bots_nav_none, "failed link retried during cooldown"); + } + else if (!strcmp(argv[1], "tall_ladder")) + { + route->phase = _bots_nav_going; route->goal = bot->goal_point; route->deadline = now + 240; + link->ladder = TRUE; link->top = 5; start = link->entrance; + CHECK(bots_navigation_follow(bot, &start, &direction), "climb not started"); + now += 10 * TICKS_PER_SECOND; start.z = 4; + bots_navigation_update(bot, &start, FALSE); + CHECK(bots_navigation_follow(bot, &start, &direction) && !link->failures, + "tall ladder timed out during stock-speed progress"); + now += 6 * TICKS_PER_SECOND; + CHECK(!bots_navigation_follow(bot, &start, &direction) && link->failures == 1 && + link->successes == 0, "stalled ladder has no bounded timeout"); + } + else if (!strcmp(argv[1], "climb_recovery")) + { + struct object_datum unit; + struct bots_tick tick; + memset(&tick, 0, sizeof(tick)); + unit.object.parent_object_index = NONE; + tick.object = &unit; tick.moving = TRUE; tick.now = now; + tick.position.z = 3; + route->phase = _bots_nav_going; route->climb_tick = now - 60; + bot->stuck_count = 2; bot->unstick_until_tick = now + 10; + bots_bot_unstick(bot, &tick); + CHECK(!bots_globals.stuck_events && !bot->stuck_count && !bot->unstick_until_tick && + bot->stuck_position.z == 3, "climb mistaken for stuck movement"); + route->phase = _bots_nav_none; tick.now += 30; + bots_bot_unstick(bot, &tick); + CHECK(bots_globals.stuck_events == 1, "ordinary stuck recovery suppressed"); + + } + else if (!strcmp(argv[1], "lifecycle")) + { + route->phase = _bots_nav_going; route->goal = bot->goal_point; route->deadline = 1000; + bots_navigation_update(bot, &start, TRUE); + CHECK(!route->phase && !link->failures, "boarding counted as a broken link"); + bots_navigation.vehicle_walkable = (byte *)malloc(17) + 1; + bots_navigation_reset(); bots_navigation_reset(); + CHECK(!bots_navigation.count && !bots_navigation.vehicle_walkable, "map state retained"); + } + else CHECK(0, "unknown case"); + return 0; +} diff --git a/tools/harness/tests/bots_powerups.c b/tools/harness/tests/bots_powerups.c new file mode 100644 index 0000000000..a2d5b23158 --- /dev/null +++ b/tools/harness/tests/bots_powerups.c @@ -0,0 +1,32 @@ +#include "harness.h" +#define BOTS_MAXIMUM 63 +enum { _bots_goal_none, _bots_goal_item }; +struct bots_bot { long unit_index, powerup_index; short goal_kind; real powerup_distance; }; +static struct { struct bots_bot bots[BOTS_MAXIMUM]; } bots_globals; +#include "under_test.inc" +int main(int argc, char **argv) +{ + struct bots_bot *bot = &bots_globals.bots[1], *claim = &bots_globals.bots[0]; + CHECK(argc == 2, "case"); + claim->unit_index = 10; claim->powerup_index = 42; claim->goal_kind = _bots_goal_item; + claim->powerup_distance = 5; + if (!strcmp(argv[1], "closer")) + { + CHECK(bots_powerup_claimed(bot, 42, 10), "farther bot stole claim"); + CHECK(!bots_powerup_claimed(bot, 42, 3), "nearer bot refused claim"); + } + else if (!strcmp(argv[1], "tie")) + { + CHECK(bots_powerup_claimed(bot, 42, 5), "unstable tie"); + CHECK(!bots_powerup_claimed(claim, 42, 5), "claimant blocks itself"); + } + else if (!strcmp(argv[1], "released")) + { + claim->unit_index = NONE; + CHECK(!bots_powerup_claimed(bot, 42, 10), "dead bot retained claim"); + claim->unit_index = 10; claim->goal_kind = _bots_goal_none; + CHECK(!bots_powerup_claimed(bot, 42, 10), "changed goal retained claim"); + } + else CHECK(0, "case"); + return 0; +} diff --git a/tools/harness/tests/bots_worker.c b/tools/harness/tests/bots_worker.c new file mode 100644 index 0000000000..b5870b732e --- /dev/null +++ b/tools/harness/tests/bots_worker.c @@ -0,0 +1,128 @@ +#include "harness.h" +#include +#define __stdcall +#define TICKS_PER_SECOND 30 +#define BOTS_SEARCHES_A_TICK 3 +#define BOTS_PATHFINDING_WALKABLE_BIT 0 +#define MAXIMUM_PATH_EDGES_PER_COLLISION_SURFACE 64 +#define INFINITE 0xffffffffUL +#define WAIT_OBJECT_0 0 +#define csmemset memset +#define csmemcpy memcpy +#define SET_FLAG(f,b,v) ((v)?((f)|=FLAG(b)):((f)&=~FLAG(b))) +#define BIT_VECTOR_TEST_FLAG(p,b) TEST_FLAG((p)[(b)/32],(b)%32) +#define platform_log(...) ((void)0) +struct collision_surface { byte flags, breakable_surface_index; long first_edge_index; }; +struct collision_edge { long vertex_indices[2], surface_indices[2], edge_indices[2]; }; +struct collision_bsp { struct { long count; struct collision_surface *address; } surfaces; + struct { long count; struct collision_edge *address; } edges; struct { long count; } vertices; }; +struct structure_bsp { + struct { long count; byte *address; } pathfinding_surfaces; + struct { long count; struct collision_bsp *address; } collision_bsp; + struct { long count; } breakable_surfaces; +}; +#define TAG_BLOCK_GET_ELEMENT(block,i,type) (&(block)->address[i]) +struct path_state { struct structure_bsp *structure; struct { boolean ignore_broken_surfaces; } input; }; +struct bots_bot { long goal_serial, navigation_parent, navigation_seat; long unit_index; short goal_kind; real_point3d goal_point, last_position; }; +struct bots_nav_route { short phase, link; }; +static struct { struct bots_bot bots[63]; } bots_globals; +static struct { struct bots_nav_route routes[63]; } bots_navigation; +static int bots_worker_enabled = 1, handles; +static long now = 100, broken; +static long game_time_get(void) { return now; } +static void *breakable_surface_flags_get(void) { return &broken; } +static real bots_distance3d(real_point3d const *a, real_point3d const *b) +{ real x=a->x-b->x,y=a->y-b->y,z=a->z-b->z; return (real)sqrt(x*x+y*y+z*z); } +struct event { int signaled, manual; }; +static void *CreateEventA(void *a, int manual, int signaled, void *b) +{ struct event *e=calloc(1,sizeof(*e)); (void)a;(void)b; e->manual=manual;e->signaled=signaled;handles++;return e; } +static int SetEvent(void *p) { ((struct event*)p)->signaled=1;return 1; } +static int ResetEvent(void *p) { ((struct event*)p)->signaled=0;return 1; } +static unsigned long WaitForSingleObject(void *p, unsigned long delay) +{ struct event *e=p;(void)delay;if (!e->signaled)return 258;if(!e->manual)e->signaled=0;return 0; } +static int CloseHandle(void *p) { CHECK(p!=NULL,"null handle");free(p);handles--;return 1; } +static void *CreateThread(void *a,long stack,unsigned long (*entry)(void*),void *arg,long flags,void *id) +{ (void)a;(void)stack;(void)entry;(void)arg;(void)flags;(void)id;return CreateEventA(NULL,1,1,NULL); } +static void bots_path_find_snapshot(struct path_state *state) { (void)state; } +static void *allocations[16]; +static int fail_after = -1; +static void *checked_malloc(size_t size) +{ + int index; + if (fail_after == 0) return NULL; + if (fail_after > 0) fail_after--; + for (index=0; index<16; index++) if (!allocations[index]) + return allocations[index]=malloc(size); + CHECK(0,"fixture allocation limit"); return NULL; +} +static void checked_free(void *pointer) +{ + int index; + CHECK(pointer!=NULL,"engine free received NULL"); + for (index=0; index<16; index++) if (allocations[index]==pointer) + { free(pointer); allocations[index]=NULL; return; } + CHECK(0,"worker allocation does not belong to engine allocator"); +} +#define malloc checked_malloc +#define free checked_free +#include "under_test.inc" +int main(int argc, char **argv) +{ + struct bots_bot *bot=&bots_globals.bots[0]; + struct structure_bsp structure; + struct collision_bsp bsp; + struct collision_surface surfaces[2]={{0,0,0},{8,0,0}}; + struct collision_edge edges[1]={{{0,1},{0,1},{0,0}}}; + byte walkable[2]={1,129}; + struct path_state state; + real_point3d start={0,0,0},goal={20,0,0}; + struct bots_path_job *job; + CHECK(argc==2,"case"); + memset(&structure,0,sizeof(structure));memset(&state,0,sizeof(state)); + structure.pathfinding_surfaces.address=walkable;structure.pathfinding_surfaces.count=2; + structure.collision_bsp.address=&bsp;structure.collision_bsp.count=1; + structure.breakable_surfaces.count=1;bsp.surfaces.address=surfaces;bsp.surfaces.count=2; + bsp.edges.address=edges;bsp.edges.count=1;bsp.vertices.count=2; + state.structure=&structure;bot->unit_index=10;bot->goal_point=goal; + if (!strcmp(argv[1],"allocation") || !strcmp(argv[1],"graph_allocation")) + { + fail_after = !strcmp(argv[1],"allocation") ? 0 : 1; + CHECK(!bots_worker_submit(bot,&state,&start,&goal,1,FALSE,FALSE,.25f),"allocation failure submitted"); + bots_worker_stop();bots_worker_stop(); + CHECK(!handles && !allocations[0],"failed allocation retained ownership"); + return 0; + } + if (!strcmp(argv[1],"disabled") || !strcmp(argv[1],"malformed")) + { + if (!strcmp(argv[1],"disabled")) bots_worker_enabled=0; + else edges[0].edge_indices[0]=9; + CHECK(!bots_worker_submit(bot,&state,&start,&goal,1,FALSE,FALSE,.25f),"worker changed default"); + CHECK(!handles && !bots_worker.jobs,"disabled worker allocated"); + return 0; + } + CHECK(bots_worker_submit(bot,&state,&start,&goal,1,FALSE,FALSE,.25f),"submission failed"); + job=bots_worker_job(bot);CHECK(job && job->pending,"pending ownership lost"); + if (!strcmp(argv[1],"snapshot")) + { + CHECK(job->state.input.ignore_broken_surfaces,"worker still reads live breakage"); + CHECK(job->walkable[-1]==0,"open-edge sentinel missing"); + CHECK(!(job->walkable[1]&1) && walkable[1]==129,"breakage snapshot changed live graph"); + walkable[0]=0;broken=1; + CHECK(job->walkable[0]==1 && !(job->walkable[1]&1),"snapshot reads mutable state"); + } + else if (!strcmp(argv[1],"stale") || !strcmp(argv[1],"goal") || !strcmp(argv[1],"boarding") || !strcmp(argv[1],"seat")) + { + if (!strcmp(argv[1],"stale")) bot->unit_index=11; + if (!strcmp(argv[1],"goal")) bot->goal_serial++; + if (!strcmp(argv[1],"boarding")) bot->navigation_parent=1; + if (!strcmp(argv[1],"seat")) bot->navigation_seat=1; + CHECK(bots_worker_job(bot)==job && job->pending,"in-flight answer overwritten on respawn"); + SetEvent(job->done); + CHECK(!bots_worker_job(bot) && !job->pending,"respawn consumed stale answer"); + } + else CHECK(!strcmp(argv[1],"cleanup"),"case"); + bots_worker_stop();bots_worker_stop(); + CHECK(!handles && !bots_worker.jobs && !bots_worker.thread,"worker cleanup leaked ownership"); + CHECK(!allocations[0] && !allocations[1],"worker allocations leaked"); + return 0; +} diff --git a/tools/harness/tests/browser_ping_text.c b/tools/harness/tests/browser_ping_text.c index f1520fc355..07224b210e 100644 --- a/tools/harness/tests/browser_ping_text.c +++ b/tools/harness/tests/browser_ping_text.c @@ -7,6 +7,7 @@ server's ('m'), after Refresh or not, from test_browser_ping_text.py's listing.i under_test.inc. */ +#define _CRT_SECURE_NO_WARNINGS #include "harness.h" #include "listing.inc" #include "words.inc" diff --git a/tools/harness/tests/cheat_spawns.c b/tools/harness/tests/cheat_spawns.c new file mode 100644 index 0000000000..12e828972b --- /dev/null +++ b/tools/harness/tests/cheat_spawns.c @@ -0,0 +1,100 @@ +#include "harness.h" +#include + +#define MIN(a, b) ((a) < (b) ? (a) : (b)) +#define CEILING(a, b) ((a) < (b) ? (b) : (a)) +#define SHORT_MAX SHRT_MAX +#define _pi 3.14159265f +#define MAXIMUM_CHEATS 16 +#define WEAPON_DEFINITION_TAG 1 +#define NUMBEROF(array) (sizeof(array) / sizeof((array)[0])) +#include "config.inc" + +struct tag_reference { long index; }; +struct tag_block { long count; void *address; }; +struct game_globals { struct tag_block weapon_list; }; +struct player_datum { long unit_index; }; +struct unit_datum { int unused; }; +struct tag_iterator { long next; }; +struct weapon_definition { struct { short type; } object; struct { unsigned long flags; } weapon; }; +struct object_placement_data +{ + long definition_index, owner_team_index; + real_point3d position; + real_vector3d forward, up; +}; + +static struct weapon_definition definitions[6]; +static struct game_globals globals; +static struct player_datum player = { 7 }; +static struct unit_datum unit; +static short connection; +static long player_index, made[6], made_count; + +#define TAG_BLOCK_GET_ELEMENT(block, index, type) (&((type *)(block)->address)[index]) +#define TAG_BLOCK_TRY_AND_GET_ELEMENT(block, index, type) ((block)->count ? TAG_BLOCK_GET_ELEMENT(block, index, type) : NULL) +#define object_definition_get(index) (&definitions[index]) +#define weapon_definition_get(index) (&definitions[index]) +static short game_connection(void) { return connection; } +static long cheat_player_index(void) { return player_index; } +static struct player_datum *player_get(long index) { (void)index; return &player; } +static struct unit_datum *unit_get(long index) { (void)index; return &unit; } +static struct game_globals *scenario_get_game_globals(void) { return &globals; } +static void object_get_origin(long index, real_point3d *origin) { (void)index; memset(origin, 0, sizeof(*origin)); } +static void object_get_orientation(long index, real_vector3d *forward, real_vector3d *up) +{ (void)index; memset(forward, 0, sizeof(*forward)); memset(up, 0, sizeof(*up)); } +/* Placement maths is not under test; the real spawn loop and tag selection are. */ +static real arctangent(real a, real b) { (void)a; (void)b; return 0; } +static real cosine(real a) { (void)a; return 1; } +static real sine(real a) { (void)a; return 0; } +static void object_placement_data_new(struct object_placement_data *data, long definition, long owner) +{ memset(data, 0, sizeof(*data)); data->definition_index = definition; data->owner_team_index = owner; } +static long object_new(struct object_placement_data *data) +{ + CHECK(made_count < 6, "too many spawns"); + CHECK(data->owner_team_index == NONE, "cheat assigned an objective owner"); + made[made_count++] = data->definition_index; + return made_count; +} +static void tag_iterator_new(struct tag_iterator *iterator, long group) { (void)group; iterator->next = 0; } +static long tag_iterator_next(struct tag_iterator *iterator) { return iterator->next < 4 ? iterator->next++ : NONE; } + +#include "under_test.inc" + +int main(int argc, char **argv) +{ + char const *case_name = argv[1]; + struct tag_reference references[] = { { 0 }, { 1 }, { NONE }, { 2 }, { 3 } }; + struct tag_reference other[] = { { 4 }, { 5 } }; + struct tag_block other_block = { 2, other }; + short index; + (void)argc; + connection = _game_connection_network_server; + globals.weapon_list.count = 5; + globals.weapon_list.address = references; + for (index = 0; index < 6; index++) definitions[index].object.type = _object_type_weapon; + definitions[1].weapon.flags = FLAG(_weapon_must_be_readied_bit); + definitions[2].weapon.flags = FLAG(_weapon_must_be_readied_bit) | FLAG(_weapon_doesnt_count_toward_maximum_bit); + definitions[3].weapon.flags = FLAG(_weapon_must_be_picked_up_bit); + definitions[4].object.type = _object_type_vehicle; + definitions[5].object.type = _object_type_equipment; + definitions[4].weapon.flags = definitions[5].weapon.flags = FLAG(_weapon_must_be_readied_bit); + if (strstr(case_name, "offline")) connection = _game_connection_local; + if (strstr(case_name, "fallback")) globals.weapon_list.count = 0; + if (!strcmp(case_name, "no-player")) player_index = NONE; + if (!strcmp(case_name, "other-objects")) + { + cheat_objects_from_block(&other_block); + CHECK(made_count == 2 && made[0] == 4 && made[1] == 5, "non-weapons changed"); + } + else + { + cheat_all_weapons(); + if (player_index == NONE) CHECK(made_count == 0, "spawned without a player"); + else if (connection == _game_connection_local) + CHECK(made_count == 4 && made[0] == 0 && made[1] == 1 && made[2] == 2 && made[3] == 3, "offline behavior changed"); + else CHECK(made_count == 2 && made[0] == 0 && made[1] == 3, "host spawned unowned objectives or lost a normal weapon"); + } + return 0; +} + diff --git a/tools/harness/tests/cinematic_titles.c b/tools/harness/tests/cinematic_titles.c index 3c21b5275c..f3f8073b68 100644 --- a/tools/harness/tests/cinematic_titles.c +++ b/tools/harness/tests/cinematic_titles.c @@ -4,9 +4,8 @@ CINEMATIC_TITLES.C (test) The real cinematic_render (cinematics.c) over a fake scenario with one title, as some Custom Edition maps show their name for the whole game: drawn in the game, not over a menu (the screen's overlays are drawn after the players' menus), and -its time going on under one. On a screen wider than 640 columns, the edge the -title is justified to (its middle, if centered) keeps its place relative to the -screen's sides, as on the Xbox's 4:3 screen. test_cinematic_titles.py takes the +its time going on under one. Widescreen placement follows the title alignment; +MCC clipping expansion preserves that anchor. test_cinematic_titles.py takes the structures, the slots' count (config.inc) and the code (under_test.inc). */ @@ -70,7 +69,6 @@ static struct string_list help_text = { { 1 } }; static long draws; static real drawn_alpha; static pixel32 shadow, drawn_shadow; -static rectangle2d drawn_bounds; static void pixel32_to_real_argb_color(pixel32 pixel, real_argb_color *color) { color->alpha = (real)((pixel >> 24) & 0xFF) / 255.0f; @@ -84,18 +82,14 @@ static void draw_string_set_draw_mode(long font_index, short style, short justif drawn_alpha = color->alpha; } static void rasterizer_text_set_shadow_color(pixel32 color) { shadow = color; } -/* the screen's columns: the Xbox's 640, or a wide screen's */ -static long screen_width = 640; -static long halo_screen_width(void) { return screen_width; } -#define rasterizer_draw_unicode_string(bounds, style, color, flags, string) \ - (draws++, drawn_shadow = shadow, drawn_bounds = *(bounds)) - -/* draw_string.c's justifications, as a title's tag has them */ -enum { justified_left, justified_right, justified_center }; - -/* MCC title adaptation is inactive for these Xbox/CE cases. */ -static boolean mcc_cache_tags_loaded(void) { return FALSE; } -static void mcc_hud_title_bounds(rectangle2d *bounds, short justification, unsigned long flags) { } +static short screen_width = 640; +static boolean mcc_loaded; +#define SHORT_MAX 32767 +static short halo_screen_width(void) { return screen_width; } +static boolean mcc_cache_tags_loaded(void) { return mcc_loaded; } +static rectangle2d drawn_bounds; +#define rasterizer_draw_unicode_string(bounds, style, color, flags, string) (draws++, drawn_shadow = shadow, drawn_bounds = *(bounds)) + #include "under_test.inc" /* the title in its slot, at its start: up for up_time ticks, then fading out for fade_out_time */ @@ -136,6 +130,120 @@ int main(int argc, char **argv) struct cinematic_title const *slot = &globals_data.queued_titles[0]; long index; + CASE("title-screen-anchors") + { + static short const widths[] = { 640, 852, 1120, 480 }; + static short const shifts[3][4] = { + { 0, 13, 30, -10 }, /* left edge at 40 */ + { 0, 197, 447, -149 }, /* right edge at 597 */ + { 0, 105, 238, -79 } /* center at 318 */ + }; + short alignment, width; + rectangle2d original; + queue_title(1000000.0f, 1.0f); + titles[0].bounds.x0 = 40; + titles[0].bounds.x1 = 597; + original = titles[0].bounds; + for (alignment = 0; alignment < 3; alignment++) + { + titles[0].justification = alignment; + for (width = 0; width < 4; width++) + { + screen_width = widths[width]; + frame(); + CHECK(drawn_bounds.x0 == 40 + shifts[alignment][width] && + drawn_bounds.x1 == 597 + shifts[alignment][width], + "alignment %d at width %d: bounds %d..%d", alignment, screen_width, drawn_bounds.x0, drawn_bounds.x1); + CHECK(drawn_bounds.y0 == original.y0 && drawn_bounds.y1 == original.y1, "vertical bounds moved"); + CHECK(!memcmp(&original, &titles[0].bounds, sizeof(original)), "authored bounds mutated"); + } + } + return 0; + } + CASE("default-title-anchor") + { + queue_title(1000000.0f, 1.0f); + hud_globals->defaults.default_title_bounds = titles[0].bounds; + hud_globals->defaults.default_title_bounds.x0 = 0; + hud_globals->defaults.default_title_bounds.x1 = 597; + titles[0].bounds.x1 = titles[0].bounds.x0; + titles[0].justification = 1; + screen_width = 852; + frame(); + CHECK(drawn_bounds.x0 == 197 && drawn_bounds.x1 == 794, "default bounds did not use right anchor"); + CHECK(hud_globals->defaults.default_title_bounds.x1 == 597, "HUD default bounds mutated"); + return 0; + } + CASE("mcc-title-screen-anchor") + { + queue_title(1000000.0f, 1.0f); + titles[0].bounds.x0 = 40; + titles[0].bounds.x1 = 597; + titles[0].justification = 1; + screen_width = 852; + mcc_loaded = TRUE; + frame(); + CHECK(drawn_bounds.x0 == 0 && drawn_bounds.x1 == 794, "MCC expansion changed right anchor"); + titles[0].text_flags = 1; + frame(); + CHECK(drawn_bounds.x0 == 237 && drawn_bounds.x1 == 794, "wrapping title moved its anchor"); + mcc_loaded = FALSE; + titles[0].text_flags = 0; + frame(); + CHECK(drawn_bounds.x0 == 237 && drawn_bounds.x1 == 794, "MCC expansion leaked into legacy title"); + screen_width = 640; + frame(); + CHECK(drawn_bounds.x0 == 40 && drawn_bounds.x1 == 597, "resolution change retained wide bounds"); + return 0; + } + CASE("mcc-title-bounds") + { + rectangle2d original; + queue_title(1000000.0f, 1.0f); + titles[0].bounds.x0 = 240; + titles[0].bounds.x1 = 400; + titles[0].justification = 2; + original = titles[0].bounds; + /* Xbox and CE keep the exact authored clipping rectangle. */ + frame(); + CHECK(drawn_bounds.x0 == 240 && drawn_bounds.x1 == 400, "legacy bounds changed"); + mcc_loaded = TRUE; + frame(); + CHECK(drawn_bounds.x0 == 0 && drawn_bounds.x1 == 640, "MCC title still clipped"); + CHECK(drawn_bounds.y0 == original.y0 && drawn_bounds.y1 == original.y1, "vertical bounds changed"); + CHECK(!memcmp(&original, &titles[0].bounds, sizeof(original)), "authored tag changed"); + screen_width = 854; + frame(); + CHECK(drawn_bounds.x0 == 0 && drawn_bounds.x1 == 854, "widescreen center moved"); + titles[0].text_flags = 1; + frame(); + CHECK(drawn_bounds.x0 == 347 && drawn_bounds.x1 == 507, "wrapping bounds changed"); + titles[0].text_flags = 0; + mcc_loaded = FALSE; + frame(); + CHECK(drawn_bounds.x0 == 347 && drawn_bounds.x1 == 507, "MCC bounds leaked after unload"); + return 0; + } + CASE("mcc-title-anchors") + { + rectangle2d bounds = { 160, 100, 500, 261 }; + mcc_loaded = TRUE; + mcc_hud_title_bounds(&bounds, 2, 0); + CHECK(bounds.x0 == 0 && bounds.x1 == 361, "odd-width center moved"); + bounds.x0 = 240; bounds.x1 = 400; + mcc_hud_title_bounds(&bounds, 0, 0); + CHECK(bounds.x0 == 240 && bounds.x1 == 640, "left anchor moved"); + bounds.x0 = 240; bounds.x1 = 400; + mcc_hud_title_bounds(&bounds, 1, 0); + CHECK(bounds.x0 == 0 && bounds.x1 == 400, "right anchor moved"); + bounds.x0 = -10; bounds.x1 = 400; + mcc_hud_title_bounds(&bounds, 2, 0); + CHECK(bounds.x0 == -10 && bounds.x1 == 400, "offscreen bounds changed"); + bounds.x0 = 400; bounds.x1 = 240; + mcc_hud_title_bounds(&bounds, 2, 0); + CHECK(bounds.x0 == 400 && bounds.x1 == 240, "inverted bounds changed"); + return 0; + } /* a title for the whole game, no menu: drawn each frame, opaque */ CASE("drawn-in-the-game") { @@ -173,67 +281,6 @@ int main(int argc, char **argv) CHECK(frame() == 0, "an ended title was drawn after the menu was gone"); return 0; } - /* a 960-column screen (half again the Xbox's 640): a right-justified - title's box from near the left edge, as most chapter titles have, ends - where the Xbox's did, as a part of the screen's width (600 of 640 is - 900 of 960), not 300 columns short of it as when its middle was moved */ - CASE("right-justified-on-a-wide-screen") - { - queue_title(1000000.0f, 1.0f); - titles[0].bounds.x0 = 10; - titles[0].bounds.x1 = 600; - titles[0].justification = justified_right; - screen_width = 960; - CHECK(frame() == 1, "the title was not drawn"); - CHECK(drawn_bounds.x1 == 900, "the right-justified title's box ends at column %d of 960, not 900", - drawn_bounds.x1); - CHECK(drawn_bounds.x1 - drawn_bounds.x0 == 590, "the title's box is %d columns wide, not its 590", - drawn_bounds.x1 - drawn_bounds.x0); - CHECK(drawn_bounds.y0 == 440 && drawn_bounds.y1 == 480, "the title's box moved up or down: %d to %d", - drawn_bounds.y0, drawn_bounds.y1); - return 0; - } - /* a left-justified title starts where the Xbox's did, as a part of the - screen's width: 40 of 640 is 60 of 960 */ - CASE("left-justified-on-a-wide-screen") - { - queue_title(1000000.0f, 1.0f); - titles[0].bounds.x0 = 40; - titles[0].bounds.x1 = 600; - titles[0].justification = justified_left; - screen_width = 960; - CHECK(frame() == 1, "the title was not drawn"); - CHECK(drawn_bounds.x0 == 60, "the left-justified title's box starts at column %d of 960, not 60", - drawn_bounds.x0); - return 0; - } - /* a centered title's middle is where the Xbox's was, as a part of the - screen's width: 320 of 640 is 480 of 960 */ - CASE("centered-on-a-wide-screen") - { - queue_title(1000000.0f, 1.0f); - titles[0].bounds.x0 = 40; - titles[0].bounds.x1 = 600; - titles[0].justification = justified_center; - screen_width = 960; - CHECK(frame() == 1, "the title was not drawn"); - CHECK((drawn_bounds.x0 + drawn_bounds.x1) / 2 == 480, - "the centered title's box is centered on column %d of 960, not 480", - (drawn_bounds.x0 + drawn_bounds.x1) / 2); - return 0; - } - /* on the Xbox's 640 columns the title's box is the tag's */ - CASE("unmoved-on-640-columns") - { - queue_title(1000000.0f, 1.0f); - titles[0].bounds.x0 = 10; - titles[0].bounds.x1 = 600; - titles[0].justification = justified_right; - CHECK(frame() == 1, "the title was not drawn"); - CHECK(drawn_bounds.x0 == 10 && drawn_bounds.x1 == 600, "the title's box is %d to %d on 640 columns, not 10 to 600", - drawn_bounds.x0, drawn_bounds.x1); - return 0; - } fprintf(stderr, "unknown case: %s\n", case_name); return 2; } diff --git a/tools/harness/tests/collision_vector_cache.c b/tools/harness/tests/collision_vector_cache.c new file mode 100644 index 0000000000..91ca774460 --- /dev/null +++ b/tools/harness/tests/collision_vector_cache.c @@ -0,0 +1,117 @@ +#include "harness.h" +#include +#include +#define MAXIMUM_BSP3D_TRAVERSAL_DEPTH 128 +#define TAG_BLOCK_GET_ELEMENT(b,i,t) (&((t *)(b)->address)[i]) +enum { _contents_unknown, _contents_solid, _contents_empty, _contents_semi_empty }; +enum { _collision_test_front_facing_surfaces_bit, _collision_test_back_facing_surfaces_bit, + _collision_test_ignore_two_sided_surfaces_bit, _collision_test_ignore_invisible_surfaces_bit, + _collision_test_ignore_breakable_surfaces_bit }; +enum { _collision_leaf_contains_two_sided_bit, _collision_surface_invisible_bit, _collision_surface_breakable_bit }; +enum { COLLISION_VECTOR_CACHE_NODES=512 }; +typedef struct { real_vector3d n; real d; } real_plane3d; +struct bsp3d_node { long plane_designator, children[2]; }; +struct block { long count; void *address; }; +struct collision_bsp { struct { struct block nodes,planes; } bsp3d; struct block leaves,surfaces; }; +struct collision_leaf { unsigned long flags; }; +struct collision_surface { byte flags,breakable_surface_index; short material_index; long plane_designator; }; +struct collision_bsp_test_vector_result { real t; const real_plane3d *plane; long surface_index,plane_designator; + byte flags,breakable_surface_index; short material_index; long leaf_count,leaf_indices[256]; }; +#include "cache.inc" +#include "context.inc" +static int distances, entries; +static real plane3d_distance_to_point(const real_plane3d *p,const real_point3d *v) +{ distances++;return p->n.i*v->x+p->n.j*v->y+p->n.k*v->z-p->d; } +static real dot_product3d(const real_vector3d *a,const real_vector3d *b) +{ return a->i*b->i+a->j*b->j+a->k*b->k; } +static boolean collision_bsp3d_enter_node(const struct collision_bsp *b,long n,short depth,long *left) +{ entries++;return nbsp3d.nodes.count && depth<128 && --*left>=0; } +static boolean collision_bsp_valid_leaf(const struct collision_bsp *b,long n) +{ return n>=0 && nleaves.count; } +static long collision_leaf_test_vector(const struct collision_bsp *b,short count,const byte *bits, + const real_point3d *p,const real_vector3d *v,long leaf,long plane,real t,boolean surface) +{ return plane==NONE?NONE:0; } +#include "under_test.inc" +static struct { + const struct collision_bsp *bsp; + const real_point3d *point; + real extent; + struct collision_bsp_vector_cache cache[8]; +} batch; +#include "prepare.inc" +int main(int argc,char **argv) +{ + struct bsp3d_node nodes[513];real_plane3d planes[3];struct collision_leaf leaves[2]; + struct collision_surface surface;struct collision_bsp bsp;struct collision_bsp_vector_cache cache; + struct collision_bsp_test_vector_context c;struct collision_bsp_test_vector_result a,b; + real_point3d p={.25f,.5f,.75f};real_vector3d v;int i,hit_a,hit_b,uncached=0,cached=0; + memset(nodes,0,sizeof(nodes));memset(planes,0,sizeof(planes));memset(leaves,0,sizeof(leaves)); + memset(&surface,0,sizeof(surface));memset(&cache,0,sizeof(cache));memset(&c,0,sizeof(c)); + nodes[0].children[0]=512;nodes[0].children[1]=1; + nodes[512].plane_designator=1;nodes[512].children[0]=LONG_MIN;nodes[512].children[1]=NONE; + nodes[1].plane_designator=2;nodes[1].children[0]=LONG_MIN|1;nodes[1].children[1]=NONE; + planes[0].n.i=planes[1].n.j=planes[2].n.k=1; + bsp.bsp3d.nodes.count=513;bsp.bsp3d.nodes.address=nodes;bsp.bsp3d.planes.count=3;bsp.bsp3d.planes.address=planes; + bsp.leaves.count=2;bsp.leaves.address=leaves;bsp.surfaces.count=1;bsp.surfaces.address=&surface; + c.bsp=&bsp;c.point=&p;c.vector=&v;c.flags=3; + for(i=0;i<1000;i++) + { + v.i=(i%17-8)*.4f;v.j=(i%13-6)*.35f;v.k=(i%11-5)*.3f; + memset(&a,0,sizeof(a));a.t=1;c.result=&a;c.nodes_left=513;c.last_leaf_index=c.last_plane_index=NONE;c.last_contents=_contents_unknown;c.cache=NULL; + distances=0;hit_a=collision_bsp_test_vector_recursive(&c,0,0,1,0);uncached+=distances; + memset(&b,0,sizeof(b));b.t=1;c.result=&b;c.nodes_left=513;c.last_leaf_index=c.last_plane_index=NONE;c.last_contents=_contents_unknown;c.cache=&cache; + distances=0;hit_b=collision_bsp_test_vector_recursive(&c,0,0,1,0);cached+=distances; + CHECK(hit_a==hit_b && !memcmp(&a,&b,sizeof(a)),"cache preserves hit, leaf order and all result fields despite slot collisions"); + } + CHECK(cached=0)|((v.j>=0)<<1)|((v.k>=0)<<2),&work,&target,&skipped); + memset(&a,0,sizeof(a));a.t=1;c.result=&a;c.nodes_left=budget;c.last_leaf_index=c.last_plane_index=NONE;c.last_contents=_contents_unknown;c.cache=NULL; + entries=0;hit_a=collision_bsp_test_vector_recursive(&c,0,0,1,0); + left_a=c.nodes_left;entries_a=entries;plane_a=c.last_plane_index;leaf_a=c.last_leaf_index;contents_a=c.last_contents; + memset(&b,0,sizeof(b));b.t=1;c.result=&b;c.nodes_left=budget;c.last_leaf_index=c.last_plane_index=NONE;c.last_contents=_contents_unknown;c.cache=&batch.cache[(v.i>=0)|((v.j>=0)<<1)|((v.k>=0)<<2)]; + entries=0;hit_b=collision_bsp_test_vector_recursive(&c,0,0,1,0); + CHECK(hit_a==hit_b && !memcmp(&a,&b,sizeof(a)),"prepared chains preserve all surface and ordered leaf results"); + CHECK(left_a==c.nodes_left && plane_a==c.last_plane_index && leaf_a==c.last_leaf_index && contents_a==c.last_contents,"prepared chains preserve budget and crossing state"); + uncached+=entries_a;cached+=entries; + } + CHECK(cached(b)?(b):(v))) +#define _contents_unknown 0 +typedef struct { long long QuadPart; } LARGE_INTEGER; +struct collision_bsp { struct { struct { long count; } nodes; } bsp3d; }; +struct collision_bsp_vector_cache { int unused; }; +struct collision_bsp_test_vector_result { real t; long leaf_count; }; +static struct collision_bsp *global_collision_bsp; +static struct { LARGE_INTEGER vector; } collision_bsp_usage_times; +static long seen_node, seen_budget; +static short seen_depth; +static real seen_t; +static int calls, logs; +static void collision_log_usage(short function) { logs++; } +static void collision_log_start_time(LARGE_INTEGER *time) { time->QuadPart=0; } +static void collision_log_end_time(short function,long long time) {} +#include "context.inc" +static boolean collision_bsp_test_vector_recursive(struct collision_bsp_test_vector_context *c, + long node,real t0,real t1,short depth) +{ + CHECK(c->last_leaf_index==NONE && c->last_plane_index==NONE && c->last_contents==_contents_unknown, + "entry preserves initial traversal history"); + CHECK(c->result->leaf_count==0,"entry resets leaf collection"); + calls++;seen_node=node;seen_depth=depth;seen_budget=c->nodes_left;seen_t=t1; + return TRUE; +} +#include "under_test.inc" +int main(int argc,char **argv) +{ + struct collision_bsp bsp; + struct collision_bsp_test_vector_result result; + real_point3d point={0,0,0};real_vector3d vector={1,0,0}; + bsp.bsp3d.nodes.count=100; + CHECK(collision_bsp_test_vector(3,&bsp,0,NULL,&point,&vector,10,&result),"stock return value"); + CHECK(seen_node==0 && seen_depth==0 && seen_budget==100 && seen_t==1 && result.t==10, + "stock calls retain root, full budget and original maximum-t handling"); + collision_bsp_test_vector(3,&bsp,0,NULL,&point,&vector,-2,&result); + CHECK(seen_t==0 && result.t==0,"negative range preserves stock clamping"); + collision_bsp_test_vector_from_node(3,&bsp,0,NULL,&point,&vector,.7f,&result,18,6,NULL); + CHECK(seen_node==18 && seen_depth==6 && seen_budget==94 && seen_t==.7f, + "skipped prefix consumes its node and depth budgets"); + CHECK(logs==3 && calls==3,"one traversal and diagnostic accounting per query"); + return 0; +} diff --git a/tools/harness/tests/contrail_tick_points.c b/tools/harness/tests/contrail_tick_points.c index 64f1d96194..a4cb24728b 100644 --- a/tools/harness/tests/contrail_tick_points.c +++ b/tools/harness/tests/contrail_tick_points.c @@ -127,6 +127,7 @@ static void set_up(void) short index; struct contrail_datum *contrail; + contrails_reset_render_state(); for (index = 0; index < 3; index++) { memset(&states[index], 0, sizeof(states[index])); diff --git a/tools/harness/tests/contrails.c b/tools/harness/tests/contrails.c new file mode 100644 index 0000000000..db07586de1 --- /dev/null +++ b/tools/harness/tests/contrails.c @@ -0,0 +1,263 @@ +/* The real timing and point states, with allocation and attachment placement + supplied by a small fake world. No renderer, map assets or physics engine. */ +#include "harness.h" +typedef unsigned short word; +typedef struct { real alpha, red, green, blue; } real_argb_color; +struct location { short cluster_index; }; +struct tag_reference { long index; }; +#include "config.inc" +#define SET_FLAG(v,b,on) ((on) ? ((v) |= FLAG(b)) : ((v) &= ~FLAG(b))) +#define TICKS_PER_SECOND 30 +#define MAXIMUM_CONTRAIL_INSTANCES 4 +#define MAXIMUM_CONTRAIL_POINTS 512 +#define TAG_BLOCK_GET_ELEMENT(block,index,type) (&((type *)(block)->address)[(int)(index)]) +struct tag_block { long count; void *address; }; +struct contrail_definition { + unsigned long scale_flags; + real point_generation_rate, frames_per_second, texture_animation_u, texture_animation_v; + struct tag_block states; +}; +static struct data_array *contrail_data, *contrail_point_data; +static struct contrail_definition test_definition; +static struct contrail_point_state states[3]; +static long tick, trail_index; +static int active = TRUE; +static real physics_dt; +static boolean double_speed; +static boolean game_players_are_double_speed(void) { return double_speed; } +#define contrail_get(i) ((struct contrail_datum *)datum_get(contrail_data,i)) +#define contrail_point_get(i) ((struct contrail_point_datum *)datum_get(contrail_point_data,i)) +#define contrail_definition_get(i) (&test_definition) +#define game_time_get() tick +#define contrail_verify(i) ((void)0) +#define data_make_valid(d) ((void)0) +#define data_make_invalid(d) ((void)0) +#define point_physics_update(a,b,c,d,e,f,g,h,i,j,dt) (physics_dt += (dt)) +static real real_local_random_range(real a, real b) { return a; } +static boolean object_get_function_value(long i, short f, real *density) { *density=1; return active; } +static void contrail_next_frame(struct contrail_datum *trail) { trail->frame_time=0; ++trail->frame_index; } +static long data_next_index(struct data_array *data, long previous) +{ + long i=previous==NONE ? 0 : DATUM_INDEX_TO_ABSOLUTE_INDEX(previous)+1; + for(;imaximum_count;++i) + { + struct datum_header *h=(struct datum_header *)(data->data+i*data->size); + if(h->identifier) return ((long)(unsigned short)h->identifier<<16)|i; + } + return NONE; +} +static void contrail_delete(long i) { datum_delete(contrail_data,i); } +static void contrail_add_points(long i, short count, boolean force) +{ + struct contrail_datum *trail = contrail_get(i); + short n; + for (n=0; nflags=FLAG(_contrail_point_new_bit)|FLAG(_contrail_point_transitioning_bit); + point->state_index=NONE; + point->density=trail->density; + point->next_contrail_point_index=trail->first_contrail_point_indices[0]; + trail->first_contrail_point_indices[0]=id; + ++trail->contrail_point_counts[0]; + } +} +#include "under_test.inc" +#include "after_load.inc" + +static void setup(void) +{ + struct contrail_datum *trail; + int i; + if (contrail_data) { free(contrail_data->data); free(contrail_data); } + if (contrail_point_data) { free(contrail_point_data->data); free(contrail_point_data); } + contrail_data=game_state_data_new("contrails",4,sizeof(struct contrail_datum)); + contrail_point_data=game_state_data_new("points",512,sizeof(struct contrail_point_datum)); + contrails_initialize_for_new_map(); + memset(&test_definition,0,sizeof(test_definition)); + memset(states,0,sizeof(states)); + test_definition.point_generation_rate=30; + test_definition.frames_per_second=10; + test_definition.texture_animation_u=2; + test_definition.states.count=3; + test_definition.states.address=states; + /* Short bright state and fade reproduce the Shade's timing contract. */ + states[0].duration_lower_bound=states[0].duration_upper_bound=0.01f; + states[0].transition_duration_lower_bound=states[0].transition_duration_upper_bound=0.05f; + states[0].width=0.15f; + states[1].transition_duration_lower_bound=states[1].transition_duration_upper_bound=0.005f; + for(i=0;i<3;++i) states[i].physics.index=NONE; + tick=0; active=TRUE; physics_dt=0; double_speed=FALSE; + trail_index=datum_new(contrail_data); + trail=contrail_get(trail_index); + trail->object_index=1; trail->density=1; trail->flags=FLAG(_contrail_active_bit); + for(i=0;i<4;++i) trail->first_contrail_point_indices[i]=NONE; + contrail_add_points(trail_index,1,TRUE); +} + +static real width_sum(void) +{ + long id=contrail_get(trail_index)->first_contrail_point_indices[0]; + real sum=0; + while(id!=NONE) + { + struct contrail_point_datum *p=contrail_point_get(id); + real width; + CHECK(p->state_index>=0 && p->state_index<3, "renderable point state"); + width=states[(int)p->state_index].width; + if(TEST_FLAG(p->flags,_contrail_point_transitioning_bit)) + width=width*(1-p->time)+states[p->state_index+1].width*p->time; + sum+=width; + id=p->next_contrail_point_index; + } + return sum; +} +static boolean close_to(real a, real b) { real d=a-b; return d<0.0001f && d> -0.0001f; } +static void rates(void) +{ + int subdivisions[] = {1,2,4,8}; + real reference[30]; + int counts[30], rate, t, frame; + for(rate=0;rate<4;++rate) + { + setup(); + /* Frame zero initializes at the same phase for every refresh rate. */ + contrails_update(0); + for(t=0;t<30;++t) + { + for(frame=0;framecontrail_point_counts[0]; } + CHECK(close_to(width_sum(),reference[t]), "rate %d tick %d width %f expected %f",30*subdivisions[rate],t,width_sum(),reference[t]); + CHECK(contrail_get(trail_index)->contrail_point_counts[0]==counts[t], "point count rate %d tick %d",rate,t); + } + CHECK(close_to(contrail_get(trail_index)->texture_offset_u,-2), "texture animation remains per frame"); + } + CHECK(reference[15]>0.19f, "preserve the bright 30 Hz profile"); +} +static void irregular_rate(void) +{ + int frame; + real total=0; + setup(); contrails_update(0); + for(frame=1;frame<=1440;++frame) + { + tick=frame*30/144; + contrails_update(1.0f/144); + if(frame>144) total+=width_sum(); + } + /* The tick/render phase varies, but must retain the 30 Hz bright body. + The frame-aged negative control averages below 0.20. */ + CHECK(total/(1440-144)>0.22f, "144 Hz average trail width %f",total/(1440-144)); +} +static void lifecycle(void) +{ + short before; + setup(); contrails_update(0); contrails_update(0.02f); + before=contrail_get(trail_index)->contrail_point_counts[0]; + contrails_dispose_from_old_map(); + CHECK(last_point_game_time==NONE, "unload resets clock"); + last_point_game_time=0; + contrails_initialize_for_new_map(); + CHECK(last_point_game_time==NONE, "new map resets clock even at same tick"); + contrails_update(1.0f/30); + CHECK(contrail_get(trail_index)->contrail_point_counts[0]==before+1, "first draw after reset emits a tick of points"); +} +static void new_point(void) +{ + struct contrail_point_datum *p; + setup(); contrails_update(0); + contrail_add_points(trail_index,1,TRUE); + p=contrail_point_get(contrail_get(trail_index)->first_contrail_point_indices[0]); + contrails_update(1.0f/120); + CHECK(p->state_index==0 && p->delta>0, "new collision/attachment point initialized before rendering"); + CHECK(p->time==0, "render-only frame does not age point"); + states[0].physics.index=1; + contrails_update(1.0f/120); + CHECK(close_to(physics_dt,contrail_get(trail_index)->contrail_point_counts[0]/120.0f), "all initialized points move between ticks"); + CHECK(close_to(contrail_get(trail_index)->texture_offset_u,-4.0f/120), "texture moves between ticks"); +} +static void pause_and_activation(void) +{ + real width; + int i; + setup(); contrails_update(0); ++tick; contrails_update(1.0f/30); + width=width_sum(); + for(i=0;i<20;++i) contrails_update(0); + CHECK(close_to(width_sum(),width), "paused clock preserves trail"); + active=FALSE; contrails_update(1.0f/120); + CHECK(!TEST_FLAG(contrail_get(trail_index)->flags,_contrail_active_bit), "attachment stops emitting"); + active=TRUE; contrails_update(1.0f/120); + CHECK(TEST_FLAG(contrail_get(trail_index)->flags,_contrail_active_bit), "attachment reactivates between ticks"); + width_sum(); /* All point states must be initialized for the renderer. */ +} +static void detached(void) +{ + int i; + setup(); contrails_update(0); + contrail_get(trail_index)->object_index=NONE; + for(i=0;i<120;++i) { if(i%4==3) ++tick; contrails_update(1.0f/120); } + CHECK(contrail_data->count==0 && contrail_point_data->count==0, "detached trail expires and is reclaimed"); +} +static void checkpoint(void) +{ + setup(); contrails_update(0); + /* A saved trail can have a fresh point even at the current tick. */ + contrail_get(trail_index)->time_until_point=0; + game_state_call_after_load_procs(); + contrails_update(1.0f/120); + CHECK(last_point_game_time==tick, "restored clock catches up"); + CHECK(contrail_get(trail_index)->time_until_point>0, "same-tick restore emits on its first draw"); +} +static void catch_up(void) +{ + struct contrail_point_datum *p; + short state; + real time, motion; + setup(); contrails_update(0); + contrail_get(trail_index)->object_index=NONE; + p=contrail_point_get(contrail_get(trail_index)->first_contrail_point_indices[0]); + states[0].physics.index=states[1].physics.index=1; + contrail_update_points(trail_index,1.0f/30,1.0f/30); + contrail_update_points(trail_index,1.0f/30,1.0f/30); + state=p->state_index; time=p->time; motion=physics_dt; + setup(); contrails_update(0); + contrail_get(trail_index)->object_index=NONE; + p=contrail_point_get(contrail_get(trail_index)->first_contrail_point_indices[0]); + states[0].physics.index=states[1].physics.index=1; + contrail_update_points(trail_index,2.0f/30,2.0f/30); + CHECK(p->state_index==state && close_to(p->time,time), "two-tick frame follows individual state transitions"); + CHECK(close_to(physics_dt,motion), "catch-up moves points once for elapsed frame time"); +} +static void double_speed_case(void) +{ + struct contrail_point_datum *p; + setup(); double_speed=TRUE; + states[0].duration_lower_bound=states[0].duration_upper_bound=1; + contrail_get(trail_index)->time_until_point=2; + contrails_update(0); + p=contrail_point_get(contrail_get(trail_index)->first_contrail_point_indices[0]); + ++tick; contrails_update(1.0f/60); + CHECK(p->state_index==0 && close_to(p->time,1.0f/60), "double-speed tick ages half a normal tick"); +} +int main(int argc,char **argv) +{ + CHECK(argc==2,"case required"); + if(!strcmp(argv[1],"rates")) rates(); + else if(!strcmp(argv[1],"irregular")) irregular_rate(); + else if(!strcmp(argv[1],"pause-activation")) pause_and_activation(); + else if(!strcmp(argv[1],"lifecycle")) lifecycle(); + else if(!strcmp(argv[1],"new-point")) new_point(); + else if(!strcmp(argv[1],"detached")) detached(); + else if(!strcmp(argv[1],"checkpoint")) checkpoint(); + else if(!strcmp(argv[1],"catch-up")) catch_up(); + else if(!strcmp(argv[1],"double-speed")) double_speed_case(); + else CHECK(FALSE,"unknown case"); + return 0; +} diff --git a/tools/harness/tests/controller_remap_camera.c b/tools/harness/tests/controller_remap_camera.c index ea945f31c3..166407ed4c 100644 --- a/tools/harness/tests/controller_remap_camera.c +++ b/tools/harness/tests/controller_remap_camera.c @@ -36,6 +36,7 @@ static void flying_camera_update(void) {} static void editor_camera_update(void) {} static void orbiting_camera_update(void) {} static void first_person_camera_update(void) {} +static void third_person_camera_update(void) {} static void following_camera_update(void) {} static struct director camera; static struct gamepad_state pad; diff --git a/tools/harness/tests/coop_wipe.c b/tools/harness/tests/coop_wipe.c index e1389aadb7..964a6903a8 100644 --- a/tools/harness/tests/coop_wipe.c +++ b/tools/harness/tests/coop_wipe.c @@ -48,12 +48,18 @@ static boolean paused,all_dead,save_succeeds; static int reverts,respawns; static struct {boolean lost_map,saving_map;short loss_timer;} main_globals; static struct {boolean saved_game_valid;void *base_address;unsigned long cpu_allocation_size;} game_state_globals; -/* These legacy checkpoints contain no temporary console or MCC state. */ #define GAME_STATE_SIZE 1024 #define GAME_STATE_CPU_SIZE 512 -static boolean hs_console_state_capture(void){return TRUE;} -static int mcc_cache_tags_loaded(void){return FALSE;} -static int mcc_checkpoint_capture(void *image,unsigned long bytes,unsigned long used,unsigned long capacity){return TRUE;} +static int mcc_loaded,mcc_capture_succeeds=1,mcc_captures; +static int console_capture_succeeds=1,console_captures,save_writes; +static int live_image_generation,saved_image_generation; +static boolean hs_console_state_capture(void){console_captures++;return console_capture_succeeds;} +static int mcc_cache_tags_loaded(void){return mcc_loaded;} +static int mcc_checkpoint_capture(void *image,unsigned long bytes,unsigned long used,unsigned long capacity) +{ + CHECK(image==game_state_globals.base_address&&bytes==GAME_STATE_SIZE&&used==game_state_globals.cpu_allocation_size&&capacity==GAME_STATE_CPU_SIZE,"checkpoint bounds"); + mcc_captures++;return mcc_capture_succeeds; +} static long game_time_get(void){return tick;} static boolean game_time_get_paused(void){return paused;} static boolean players_are_all_dead(void){return all_dead;} @@ -63,7 +69,7 @@ static void game_state_revert(void){reverts++;} static void game_state_call_before_save_procs(void){} static void main_stop_time(void){} static void main_start_time(void){} -static boolean game_state_write_to_file(void){return save_succeeds;} +static boolean game_state_write_to_file(void){save_writes++;if(save_succeeds)saved_image_generation=live_image_generation;return save_succeeds;} static void game_state_note_event(char const *note){(void)note;} /* The unrelated state reset by the actual new-game lifecycle entry point. */ static int coop_presentation,coop_events,host_devices,client_devices,client_names_differing[1]; @@ -89,6 +95,8 @@ static void setup(void) connection=_game_connection_network_server;active=TRUE;memset(&lobby,0,sizeof(lobby));browser_enabled=TRUE;policy="auto"; tick=main_loss_last_tick=0;paused=FALSE;all_dead=TRUE;save_succeeds=TRUE;reverts=respawns=diagnostics=0; memset(&main_globals,0,sizeof(main_globals));game_state_globals.saved_game_valid=FALSE; + mcc_loaded=FALSE;mcc_capture_succeeds=TRUE;mcc_captures=0; + console_capture_succeeds=TRUE;console_captures=save_writes=0;live_image_generation=1;saved_image_generation=0; network_coop_new_game();game_state_save(); } static void wipe(void){main_lost_map();tick+=92;main_lost_map_private();} @@ -125,6 +133,29 @@ int main(int argc,char **argv) add_player();save_succeeds=FALSE;game_state_save(); CHECK(!network_coop_wipe_reverts(),"failed save replaced membership snapshot"); setup();game_state_globals.saved_game_valid=FALSE;wipe();CHECK(!reverts&&respawns==1,"missing saved state rewound"); + } else CASE("mcc-save") { + CHECK(!mcc_captures,"legacy save entered MCC"); + mcc_loaded=TRUE;game_state_save(); + CHECK(mcc_captures==1&&game_state_globals.saved_game_valid,"MCC checkpoint capture skipped"); + mcc_capture_succeeds=FALSE;game_state_save(); + CHECK(mcc_captures==2&&game_state_globals.saved_game_valid,"failed MCC capture discarded previous checkpoint"); + } else CASE("console-save") { + for(int mcc=0;mcc<2;mcc++){ + struct coop_checkpoint_players previous; + setup();mcc_loaded=mcc;previous=checkpoint_players; + add_player();live_image_generation=2;console_capture_succeeds=FALSE; + game_state_save(); + CHECK(console_captures==2&&save_writes==1&&saved_image_generation==1,"failed console capture wrote a saved image"); + CHECK(!mcc_captures&&game_state_globals.saved_game_valid,"failed console capture reached MCC or discarded previous state"); + CHECK(!memcmp(&previous,&checkpoint_players,sizeof(previous)),"failed console capture published new roster"); + wipe();CHECK(!reverts&&respawns==1,"failed console capture rewound a team wipe"); + console_capture_succeeds=TRUE;game_state_save(); + CHECK(console_captures==3&&save_writes==2&&saved_image_generation==2&&game_state_globals.saved_game_valid, + "successful console capture did not publish the replacement image"); + CHECK(mcc_captures==mcc&&checkpoint_players.count==3&&network_coop_wipe_reverts(), + "successful console capture did not publish the replacement roster"); + wipe();CHECK(reverts==1&&respawns==1,"replacement checkpoint could not restore the team"); + } } else CASE("new-map") { CHECK(network_coop_wipe_reverts(),"valid checkpoint rejected"); host_attachment_count=3;host_looping_sound_count=2;client_looping_sounds.count=2;sound_syncs=2; diff --git a/tools/harness/tests/covenant_emitter_lighting.c b/tools/harness/tests/covenant_emitter_lighting.c new file mode 100644 index 0000000000..d3c72fe64e --- /dev/null +++ b/tools/harness/tests/covenant_emitter_lighting.c @@ -0,0 +1,294 @@ +#include "harness.h" +#include +#include +#define MAX(a,b) ((a)>(b)?(a):(b)) +#define MIN(a,b) ((a)<(b)?(a):(b)) +#define PIN(a,b,c) MIN(MAX(a,b),c) +enum { _object_type_biped=0, _object_type_vehicle=1, _object_type_weapon=2, _object_type_scenery=6, + _object_mask_vehicle=2, _object_mask_equipment=8, _object_mask_biped=1, _object_mask_weapon=4, _object_mask_scenery=64, + _object_invisible_bit=0, _object_shield_depleted_bit=2, + MAXIMUM_REGIONS_PER_OBJECT=8, MAXIMUM_WEAPONS_PER_UNIT=4 }; +typedef struct { real red,green,blue; } real_rgb_color; +typedef struct { real scale; real_vector3d forward,left,up; real_point3d position; } real_matrix4x3; +struct object_marker { real_matrix4x3 matrix; }; +struct object_datum { long definition_index; struct { + long flags,damage_flags,regions_destroyed_flags,parent_object_index; + short type; struct { int size; } node_matrices; + real body_vitality,maximum_body_vitality,shield_vitality,recent_shield_damage; + real outgoing_function_values[4]; unsigned char region_permutations[8]; real_rgb_color outgoing_change_colors[4]; + } object; }; +struct unit_datum { struct { long flags; } object; struct { short current_weapon_index; } unit; }; +struct block { int count; }; +struct model_region { char name[32]; }; +struct model { struct block regions; }; +struct object_definition { struct { struct { long index; } model; } object; }; +static struct object_datum objects[10]; +static struct unit_datum parent; +static struct model model={{1}}; +static struct model_region fake_region={"shield"}; +static struct object_definition definition; +#define TAG_BLOCK_GET_ELEMENT(b,i,t) (&fake_region) +static const char *names[10]; +static real now,marker_x=1; +static int count=1,shield_on=1,fuel_on,stationary_on,allocs,deletes,disconnects,missing,fail,marker_missing; +static long inventory=0; +static int ammo_on,needler_on,first_person,ambient_mode,ambient_count=1,stream_live=1; +static real stream_x=10; +static const char *last_marker; +static void *global_d3d_device; +enum { D3DRS_PSRGBOUTPUTS7=7 }; +static int screen_draw_calls; +static unsigned long screen_output; +static void IDirect3DDevice8_SetRenderState(void *device,int state,unsigned long output) +{ CHECK(state==D3DRS_PSRGBOUTPUTS7,"only display RGB output is touched");screen_output=output;screen_draw_calls++; } +#define weapon_datum object_datum +static struct { int active,connected; real radius; real_rgb_color color; real_point3d position; } storage[64]; +static real_vector3d forward={1,0,0}; +static const real_vector3d *global_forward3d=&forward; +struct observer_result { real_point3d position; }; +static struct observer_result camera; +struct object_iterator { long index; }; +static void object_iterator_new(struct object_iterator *it,int mask,int flags) { it->index=-1; } +static void *object_iterator_next(struct object_iterator *it) { return ++it->indexindex]:NULL; } +static struct object_datum *object_try_and_get(long i) { return i>=0&&imatrix.forward.i=1;m->matrix.up.k=1;m->matrix.position.x=marker_x;return !marker_missing; } +static int first_person_weapon_adjust_light(long i,const char *n,real_point3d *p,real_vector3d *f,real_vector3d *u) +{ memset(p,0,sizeof(*p));memset(f,0,sizeof(*f));memset(u,0,sizeof(*u));p->x=5;f->j=1;u->k=1;return first_person&&!marker_missing; } +static short local_player_get_next(short i) { return i==NONE?0:NONE; } +static const struct observer_result *observer_get_camera(short i) { return &camera; } +static real distance3d(const real_point3d *a,const real_point3d *b) { return (real)fabs(a->x-b->x); } +static long game_time_get(void) { return (long)(now*30); } +real render_interpolation_game_time_sec(long ticks) { return now; } +int lighting_config_boolean(const char *name) +{ + if (!strcmp(name,"display.jackal_shield_lighting")) return shield_on; + if (!strcmp(name,"display.fuel_rod_lighting")) return fuel_on; + if (!strcmp(name,"display.covenant_shield_lighting")) return stationary_on; + if (!strcmp(name,"display.ammo_counter_lighting")) return ammo_on; + if (!strcmp(name,"display.needler_lighting")) return needler_on; + if (!strcmp(name,"display.vehicle_lighting")) return ambient_mode==1; + if (!strcmp(name,"display.plasma_lighting")) return ambient_mode==2; + return 0; +} +long light_port_glow_definition_get(void) { return missing?NONE:99; } +static long light_new_unattached(long d,long o,short n,const real_point3d *p,const real_vector3d *v,real scale) +{ if(fail)return NONE;storage[allocs].active=storage[allocs].connected=1;return 100+allocs++; } +boolean light_port_glow_set(long l,long o,const real_rgb_color *c,real r) +{ int i=l-100;if(i<0||i>=allocs||!storage[i].active)return FALSE;storage[i].color=*c;storage[i].radius=r;return TRUE; } +boolean light_port_glow_move(long l,const real_point3d *p) +{ storage[l-100].position=*p;storage[l-100].connected=1;return TRUE; } +static void light_delete(long l) { storage[l-100].active=0;deletes++; } +static void light_disconnect_from_map(long l) +{ CHECK(storage[l-100].connected,"double disconnect");storage[l-100].connected=0;disconnects++; } +void plasma_occlusion_submit(long l,long r) {} +struct shader { int unused; }; +struct pixel_shader_definition { unsigned long rgb_outputs[8]; }; +static struct shader screen_shader, needle_shader, core_shader, crystal_shader, other_shader; +static int screen_present=1; +static long tag_loaded(long group,const char *name) { if (screen_present && group=='sotr') return 97; if (screen_present && group=='schi') return 96; if (screen_present && group=='soso' && !strcmp(name,"weapons\\needler\\shaders\\needler dull")) return 98; return screen_present&&group=='soso'&&!strcmp(name,"weapons\\assault rifle\\fp\\shaders\\display")?99:NONE; } +static struct shader *shader_definition_get(long i) { return i==97?&core_shader:i==96?&crystal_shader:i==98?&needle_shader:&screen_shader; } +void authored_emitter_lighting_forget(void) {} +struct emitter_sample; +int ambient_emitter_lighting_enabled(void) { return ambient_mode!=0; } +unsigned long ambient_emitter_lighting_begin(void) { return ambient_mode==1?_object_mask_vehicle:ambient_mode==2&&stream_live?_object_mask_biped:0; } +void ambient_emitter_lighting_forget(void) {} +int ambient_emitter_lighting_sample(long i,int c,struct emitter_sample *s); +#include "under_test.inc" +int ambient_emitter_lighting_sample(long i,int c,struct emitter_sample *s) +{ + if(!ambient_mode||i>=ambient_count||(ambient_mode==2&&(!stream_live||c)))return 0; + s->kind=ambient_mode==1?EMITTER_VEHICLE:EMITTER_FLAME; + s->radius=2;s->strength=.8f;s->color.red=1;s->color.green=.4f;s->color.blue=.1f; + memset(&s->position,0,sizeof(s->position));s->position.x=ambient_mode==1?(real)(1+c*3):stream_x; + return 1; +} +static void frame(real dt) { now+=dt;covenant_emitter_lighting_update(); } +int main(int argc,char **argv) +{ + int i,old;real slow,fast;struct emitter_sample sample; + real_rgb_color screen={0,.2f,.35f}; + ammo_counter_lighting_screen(&screen_shader,&screen); + CHECK(screen.blue==.35f,"disabled screen untouched"); + ammo_on=1;ammo_counter_lighting_screen(&other_shader,&screen); + CHECK(screen.blue==.35f,"unrelated shaders untouched"); + ammo_counter_lighting_screen(&screen_shader,&screen); + CHECK(screen.blue==1&&screen.green==1&&screen.red==.45f,"both models share the stronger masked screen emission"); + ammo_counter_lighting_draw_begin(&other_shader,0xC00);ammo_counter_lighting_draw_end(); + CHECK(screen_draw_calls==0,"unrelated materials never change draw state"); + ammo_counter_lighting_draw_begin(&screen_shader,0xC00); + CHECK(screen_draw_calls==1&&screen_output==0x10C00,"display RGB doubled before fog"); + ammo_counter_lighting_draw_end();ammo_counter_lighting_draw_end(); + CHECK(screen_draw_calls==2&&screen_output==0xC00,"exact output restored once before next material"); + ammo_counter_lighting_draw_begin(&screen_shader,0x18C00);ammo_counter_lighting_draw_end(); + CHECK(screen_draw_calls==2,"custom biased output is preserved"); + ammo_on=0;ammo_counter_lighting_draw_begin(&screen_shader,0xC00);ammo_counter_lighting_draw_end(); + CHECK(screen_draw_calls==2,"disabled screen does not touch render state");ammo_on=1; + ammo_counter_lighting_forget();screen_present=0;screen.blue=.35f; + ammo_counter_lighting_screen(&screen_shader,&screen); + CHECK(screen.blue==.35f,"missing screen after map switch stays stock"); + ammo_counter_lighting_forget();screen_present=1;ammo_on=0; + for(i=0;i<10;i++) { + objects[i].definition_index=i;names[i]="characters\\jackal\\jackal"; + objects[i].object.node_matrices.size=sizeof(real_matrix4x3); + objects[i].object.parent_object_index=NONE;objects[i].object.maximum_body_vitality=1; + objects[i].object.body_vitality=objects[i].object.shield_vitality=1; + objects[i].object.outgoing_change_colors[2].blue=1; + } + CHECK(emitter_sample(0,0,&sample)&&sample.kind==0&&sample.radius==3.6f&&sample.color.green>=.42f,"minor shield profile"); + names[0]="characters\\jackal\\jackal major";objects[0].object.outgoing_change_colors[2].red=1; + CHECK(emitter_sample(0,0,&sample)&&sample.color.red==1,"major uses authored colour"); + objects[0].object.outgoing_change_colors[2].blue=.10f; + objects[0].object.outgoing_change_colors[2].green=.68f; + CHECK(emitter_sample(0,0,&sample)&&sample.radius==3.6f&&sample.color.green==.78f&&sample.color.blue==.24f,"gold shares broader brighter spill"); + objects[0].object.outgoing_change_colors[2].blue=1; + objects[0].object.outgoing_change_colors[2].green=0; + objects[0].object.outgoing_function_values[0]=1; + CHECK(emitter_sample(0,0,&sample)&&sample.color.red==1&&sample.color.blue==0&&sample.color.green==0,"shield light follows full shader hit flash"); + objects[0].object.outgoing_function_values[0]=.5f; + CHECK(emitter_sample(0,0,&sample)&&sample.color.blue==.5f,"shield flash blends with the evaluated shader value"); + objects[0].object.outgoing_function_values[0]=0; + objects[0].object.body_vitality=0; + CHECK(emitter_sample(0,0,&sample)&&sample.strength==0,"dead Jackal has no shield illumination"); + objects[0].object.body_vitality=1; + marker_x=24;CHECK(emitter_sample(0,0,&sample)&&sample.strength>0&&sample.strength<0.4f,"distance boundary fades before admission cutoff"); + marker_x=26;CHECK(emitter_sample(0,0,&sample)&&sample.strength==0,"distant emitter stays stock");marker_x=1; + objects[0].object.type=_object_type_scenery;names[0]="scenery\\c_field_generator\\c_field_generator"; + CHECK(!emitter_sample(0,0,&sample),"stationary setting independent");stationary_on=1; + objects[0].object.maximum_body_vitality=objects[0].object.body_vitality=0; + CHECK(emitter_sample(0,0,&sample)&&sample.strength>0&&sample.kind==2,"indestructible shield base eligible"); + objects[0].object.outgoing_function_values[0]=1; + CHECK(emitter_sample(0,0,&sample)&&sample.color.red==1&&sample.color.blue==0,"stationary flash matches shader too"); + objects[0].object.outgoing_function_values[0]=0; + objects[0].object.region_permutations[0]=1; + CHECK(emitter_sample(0,0,&sample)&&sample.strength==0,"shield-off permutation overrides marker"); + objects[0].object.region_permutations[0]=0; + objects[0].object.type=_object_type_weapon;names[0]="weapons\\fuel rod gun\\fuel rod"; + CHECK(!emitter_sample(0,0,&sample),"fuel setting independent");fuel_on=1; + CHECK(emitter_sample(0,0,&sample)&&sample.kind==1,"dropped rods remain luminous"); + objects[0].object.parent_object_index=42;inventory=1; + CHECK(!emitter_sample(0,0,&sample),"holstered weapon rejected");inventory=0; + CHECK(emitter_sample(0,0,&sample),"held current weapon eligible"); + names[0]="weapons\\fuel rod gun\\hunter fuel rod"; + CHECK(!emitter_sample(0,0,&sample),"no phantom rods on model-less Hunter gun"); + names[0]="characters\\hunter\\hunter";objects[0].object.type=_object_type_biped;objects[0].object.parent_object_index=NONE; + CHECK(emitter_sample(0,0,&sample)&&sample.kind==1&&sample.color.green==1,"Hunter rods share fuel-rod setting and profile"); + CHECK(!strcmp(last_marker,"rodflare")&&sample.position.x==marker_x,"Hunter source follows the forearm rod marker"); + marker_missing=1;CHECK(!emitter_sample(0,0,&sample),"missing Hunter rods do not invent a light");marker_missing=0; + fuel_on=0;CHECK(!emitter_sample(0,0,&sample),"Hunter glow off with existing fuel-rod switch");fuel_on=1; + names[0]="characters\\jackal\\jackal";objects[0].object.type=0;objects[0].object.parent_object_index=NONE; + objects[0].object.maximum_body_vitality=objects[0].object.body_vitality=1; + covenant_emitter_lighting_update(); + for(i=0;i<6;i++)frame(1.0f/30); + slow=emitters[0].strength;covenant_emitter_lighting_frame_end(); + CHECK(disconnects==1&&storage[0].color.blue==0,"dark and disconnected between simulation ticks"); + covenant_emitter_lighting_forget();now=0;covenant_emitter_lighting_update(); + frame(1.0f/120);CHECK(emitters[0].strength>0,"fade advances between simulation ticks"); + for(i=1;i<24;i++)frame(1.0f/120); + fast=emitters[0].strength;CHECK(fabs(slow-fast)<0.0001,"frame-rate independent easing"); + old=allocs;frame(0);CHECK(allocs==old&&emitters[0].strength==fast,"split views do not advance fade"); + marker_x=2;frame(1.0f/120);CHECK(storage[allocs-1].position.x==2,"rendered marker follows light"); + covenant_emitter_lighting_submitted(emitters[0].light,3); + CHECK(covenant_emitter_lighting_selected(3),"submitted emitter selects soft path without projectile setting"); + CHECK(covenant_emitter_lighting_radius(emitters[0].light,.1f)==3.6f,"bounds cover full light"); + objects[0].object.shield_vitality=0;frame(1.0f/120); + CHECK(emitters[0].strength>0&&emitters[0].strength0&&emitters[0].strength<0.2f,"recovered shield eases back in"); + now=-1;old=deletes;covenant_emitter_lighting_update();CHECK(deletes==old+1,"clock rollback discards old light"); + objects[0].object.shield_vitality=1;count=10;covenant_emitter_lighting_update();frame(.1f); + old=allocs;frame(.1f);CHECK(allocs==old,"stable bounded identities"); + for(i=0,old=0;i<8;i++)old+=emitters[i].active;CHECK(old==8,"eight-light cap"); + shield_on=0;covenant_emitter_lighting_frame_end(); + for(i=0;i<8;i++)CHECK(!emitters[i].active,"disable releases all owned lights"); + shield_on=1;count=1;marker_missing=1;old=allocs;frame(.1f);CHECK(allocs==old,"missing marker remains stock"); + marker_missing=0;missing=1;frame(.1f);frame(.1f);CHECK(allocs==old,"missing template remains stock"); + missing=0;fail=1;frame(.1f);frame(.1f);CHECK(allocs==old,"allocation failure remains stock"); + fail=0;frame(.1f);frame(.1f);count=0;old=deletes;frame(.1f);CHECK(deletes==old+1,"deletion releases owned light"); + covenant_emitter_lighting_forget();CHECK(!covenant_emitter_lighting_selected(3),"map forget clears identities"); + shield_on=fuel_on=stationary_on=0;count=1;old=allocs;frame(.1f); + CHECK(allocs==old,"all options off allocate nothing"); + stationary_on=1;objects[0].object.type=_object_type_scenery;names[0]="scenery\\c_field_generator\\c_field_generator"; + frame(.01f);frame(.01f); + CHECK(covenant_emitter_lighting_occlusion_ignore(emitters[0].light)==0,"stationary shield cannot occlude itself"); + CHECK(covenant_emitter_lighting_occlusion_ignore(NONE)==NONE,"unowned light has no occlusion exclusion"); + stationary_on=0;CHECK(covenant_emitter_lighting_occlusion_ignore(emitters[0].light)==NONE,"disabled source has no exclusion"); + objects[0].object.type=_object_type_weapon;names[0]="weapons\\assault rifle\\assault rifle"; + objects[0].object.parent_object_index=42;inventory=0;marker_x=1; + CHECK(!emitter_sample(0,0,&sample),"ammo setting independent and off");ammo_on=1; + CHECK(emitter_sample(0,0,&sample)&&sample.kind==3&&sample.radius>.9f&&sample.strength==.65f,"third person counter strength unchanged"); + CHECK(fabs(sample.position.x-.82f)<.0001&&fabs(sample.position.z-.027744f)<.0001,"third person counter offset"); + first_person=1; + CHECK(emitter_sample(0,0,&sample)&&sample.position.x==5&&fabs(sample.position.y+.18f)<.0001,"first person follows rotated rendered marker"); + CHECK(fabs(sample.position.z-.025f)<.0001,"first person has separate offset"); + CHECK(fabs(sample.strength*sample.view_gain-1.35f)<.0001,"first person counter has brighter spill"); + CHECK(sample.direction.i==0&&fabs(sample.direction.j+.8f)<.0001&&fabs(sample.direction.k-.6f)<.0001,"screen direction rotates with rendered weapon"); + inventory=1;CHECK(!emitter_sample(0,0,&sample),"holstered counter rejected");inventory=0; + objects[0].object.parent_object_index=NONE;CHECK(!emitter_sample(0,0,&sample),"dropped counter is off"); + objects[0].object.parent_object_index=42;marker_missing=1;CHECK(!emitter_sample(0,0,&sample),"missing counter marker stays stock");marker_missing=0; + first_person=1;frame(.01f);frame(.1f); + slow=storage[emitters[0].light-100].color.blue; + first_person=0;frame(0); + CHECK(fabs(storage[emitters[0].light-100].color.blue-slow*.65f/1.35f)<.0001,"first person boost does not leak into another view"); + first_person=1;frame(0); + CHECK(fabs(storage[emitters[0].light-100].color.blue-slow)<.0001,"view order does not change first person brightness"); + first_person=0;ammo_on=0;old=deletes;frame(.01f); + CHECK(deletes>old,"counter disable releases owned light"); + needler_on=1;names[0]="weapons\\needler\\needler"; + CHECK(emitter_sample(0,0,&sample)&&sample.kind==4,"held Needler admitted independently of AR"); + CHECK(sample.position.x==marker_x&&sample.direction.k==1,"world needle marker and up axis"); + first_person=1; + CHECK(emitter_sample(0,0,&sample)&&sample.position.x==5&&sample.position.y==0,"first person needle marker follows rendered pose"); + CHECK(sample.direction.k==1,"needle spill follows model up"); + inventory=1;CHECK(!emitter_sample(0,0,&sample),"holstered Needler rejected");inventory=0; + objects[0].object.parent_object_index=NONE;CHECK(!emitter_sample(0,0,&sample),"dropped Needler rejected"); + objects[0].object.parent_object_index=42;marker_missing=1;CHECK(!emitter_sample(0,0,&sample),"missing needle marker stays stock");marker_missing=0; + screen.red=screen.green=screen.blue=0; + needler_lighting_material(&other_shader,&screen);CHECK(screen.red==0,"other materials unchanged"); + needler_lighting_material(&needle_shader,&screen);CHECK(screen.red==1&&screen.blue==.85f,"needle mask emits pink"); + frame(.01f);frame(.1f);covenant_emitter_lighting_submitted(emitters[0].light,7); + { float axis[3],origin[3],radius;CHECK(covenant_emitter_lighting_cone(7,axis,origin,&radius)==2,"Needler uses broad exposed profile"); } + { struct pixel_shader_definition pixel={{0xC00,0xC00}}; + needler_lighting_transparent(&core_shader,&pixel,1);CHECK(pixel.rgb_outputs[0]==0x10C00,"FP crystal RGB boosted"); + needler_lighting_transparent(&crystal_shader,&pixel,2);CHECK(pixel.rgb_outputs[1]==0x10C00,"world crystal RGB boosted"); + pixel.rgb_outputs[0]=0x18C00;needler_lighting_transparent(&core_shader,&pixel,1);CHECK(pixel.rgb_outputs[0]==0x18C00,"custom biased stage preserved"); + pixel.rgb_outputs[0]=0xC00;needler_lighting_transparent(&core_shader,&pixel,0);needler_lighting_transparent(&core_shader,&pixel,9);CHECK(pixel.rgb_outputs[0]==0xC00,"stage bounds checked"); + pixel.rgb_outputs[0]=0xC00;needler_lighting_transparent(&other_shader,&pixel,1);CHECK(pixel.rgb_outputs[0]==0xC00,"unrelated transparent shader preserved"); + needler_on=0;needler_lighting_transparent(&core_shader,&pixel,1);CHECK(pixel.rgb_outputs[0]==0xC00,"disabled transparent material stock");needler_on=1; + } + needler_on=0;old=deletes;frame(.01f);CHECK(deletes>old,"Needler disable releases light"); + screen.red=0;needler_lighting_material(&needle_shader,&screen);CHECK(screen.red==0,"disabled needle material stock"); + needler_on=1;screen_present=0;covenant_emitter_lighting_forget(); + needler_lighting_material(&needle_shader,&screen);CHECK(screen.red==0,"map change invalidates needle material cache"); + needler_on=0;ambient_mode=1;count=1;objects[0].object.type=_object_type_vehicle; + objects[0].object.parent_object_index=NONE;names[0]="fixture vehicle";frame(.01f);frame(.1f); + CHECK(emitters[0].active&&emitters[1].active&&emitters[0].light!=emitters[1].light,"two components retain distinct bounded identities"); + CHECK(storage[emitters[0].light-100].position.x==1&&storage[emitters[1].light-100].position.x==4,"component positions do not overwrite one another"); + CHECK(covenant_emitter_lighting_vehicle_occlusion(emitters[0].light)&&covenant_emitter_lighting_vehicle_occlusion(emitters[1].light),"both components request chassis blocking"); + ambient_mode=0;covenant_emitter_lighting_frame_end();CHECK(!emitters[0].active&&!emitters[1].active,"vehicle disable releases both components"); + ambient_mode=2;objects[0].object.type=_object_type_biped;frame(.01f);frame(.1f); + stream_x=20;frame(.05f);slow=emitters[0].position.x; + CHECK(slow>10&&slow<20,"flame centroid eases between tick positions"); + frame(0);CHECK(emitters[0].position.x==slow,"repeated view does not advance centroid"); + stream_live=0;old=deletes;frame(.01f);CHECK(!emitters[0].active&&deletes>old,"empty owner mask still releases expired stream light"); + ambient_mode=1;ambient_count=count=4; + for(i=0;i<4;i++) { objects[i].object.type=_object_type_vehicle;names[i]="fixture vehicle"; } + frame(.01f);frame(.1f); + for(i=0,old=0;i<8;i++)old+=emitters[i].active;CHECK(old==8,"ambient sources can fill the shared budget"); + count=5;ammo_on=1;inventory=4;objects[4].object.type=_object_type_weapon; + objects[4].object.parent_object_index=42;names[4]="weapons\\assault rifle\\assault rifle"; + frame(.01f);frame(.1f); + for(i=0,old=0;i<8;i++)old+=emitters[i].active&&emitters[i].kind==3&&emitters[i].object==4; + CHECK(old==1,"ambient saturation must not starve an existing held-weapon light"); + old=allocs;frame(.1f);CHECK(allocs==old,"priority admission does not churn stable lights"); + for(i=0,old=0;i<8;i++)old+=emitters[i].active;CHECK(old==8,"priority retains the original allocation budget"); + return 0; +} diff --git a/tools/harness/tests/covenant_lighting.c b/tools/harness/tests/covenant_lighting.c new file mode 100644 index 0000000000..d7bc8ae4c4 --- /dev/null +++ b/tools/harness/tests/covenant_lighting.c @@ -0,0 +1,135 @@ +#include "harness.h" +#define NUMBEROF(a) (sizeof(a)/sizeof((a)[0])) +#include +#define MAX(a,b) ((a) > (b) ? (a) : (b)) +typedef struct { real red, green, blue; } real_rgb_color; +typedef struct { real elements[13]; } real_matrix4x3; +enum { _object_type_projectile = 5, _object_mask_projectile = 1, _object_invisible_bit = 0, + MAXIMUM_NUMBER_OF_ATTACHMENTS_PER_OBJECT = 8 }; +struct object_datum { long definition_index; struct { short type; long flags; struct { int size; } node_matrices; real_point3d bounding_sphere_center; } object; }; +struct object_attachment_definition { struct { long group_tag, index; } type; }; +struct block { int count; }; +struct object_definition { struct { struct block attachments; struct { long index; } model; } object; }; +static struct object_attachment_definition authored_attachment = {{'ligh',99}}; +#define TAG_BLOCK_GET_ELEMENT(b,i,t) (&authored_attachment) +static struct object_definition definition; +struct observer_result { real_point3d position; }; +static struct observer_result camera; +static real_vector3d zero, forward = {1,0,0}; +static const real_vector3d *global_zero_vector3d = &zero, *global_forward3d = &forward; +static struct object_datum objects[10]; +static int count = 10, enabled = 1, allocs, deletes, disconnects, submits, fail, missing, tag_queries; +static const char *name = "weapons\\needler\\needle"; +static struct { int active, connected; long owner; real red; } storage[64]; +struct object_iterator { long index; }; +static void object_iterator_new(struct object_iterator *i, int mask, int flags) { i->index = -1; } +static void *object_iterator_next(struct object_iterator *i) { return ++i->index < count ? &objects[i->index] : NULL; } +static struct object_datum *object_try_and_get(long i) { return i >= 0 && i < count ? &objects[i] : NULL; } +static const char *tag_get_name(long i) { tag_queries++; return name; } +static long exhaust_tag=77; +static int exhaust_queries; +static long tag_loaded(long group,const char *tag) +{ + CHECK(group=='ligh'&&!strcmp(tag,"weapons\\fuel rod gun\\fuel rod exhaust"),"only the known flight light is resolved"); + exhaust_queries++;return exhaust_tag; +} +static struct object_definition *object_definition_get(long i) { return &definition; } +static short local_player_get_next(short i) { return i == NONE ? 0 : NONE; } +static const struct observer_result *observer_get_camera(short i) { return &camera; } +static real distance3d(const real_point3d *a, const real_point3d *b) { return a->x - b->x; } +int lighting_config_boolean(const char *n) { return enabled; } +long light_port_glow_definition_get(void) { return missing ? NONE : 99; } +static long light_new_unattached(long d,long o,short n,const real_point3d *p,const real_vector3d *v,real s) +{ + if (fail) return NONE; + storage[allocs].active=storage[allocs].connected=1; storage[allocs].owner=o; + return 100+allocs++; +} +boolean light_port_glow_set(long l,long o,const real_rgb_color *c,real r) +{ + int i=(int)l-100; + if (i<0 || i>=allocs || !storage[i].active || storage[i].owner!=o) return FALSE; + storage[i].red=c->red; return TRUE; +} +static void light_delete(long l) { storage[l-100].active=0; deletes++; } +static void light_disconnect_from_map(long l) { CHECK(storage[l-100].connected,"disconnect requires connected light"); storage[l-100].connected=0; disconnects++; } +static void light_reconnect_to_map(long l) { CHECK(!storage[l-100].connected,"connect requires disconnected light"); storage[l-100].connected=1; } +void plasma_occlusion_submit(long l,long r) { submits++; } +#include "under_test.inc" +static void color_checks(void) +{ + real_rgb_color authored={.6f,.8f,.5f},color; + name="weapons\\fuel rod gun\\fuel rod"; + color=authored;enabled=0;covenant_lighting_color(0,77,&color); + CHECK(!memcmp(&color,&authored,sizeof(color))&&exhaust_queries==0,"disabled colour stays authored without resolving tags"); + enabled=1;color=authored;covenant_lighting_color(NONE,77,&color); + CHECK(!memcmp(&color,&authored,sizeof(color)),"ownerless effect untouched"); + objects[0].object.type=0;covenant_lighting_color(0,77,&color); + CHECK(!memcmp(&color,&authored,sizeof(color)),"non-projectile untouched");objects[0].object.type=5; + name="vehicles\\banshee\\banshee fuel rod";covenant_lighting_color(0,77,&color); + CHECK(!memcmp(&color,&authored,sizeof(color)),"other fuel-rod profiles keep their colour"); + name="weapons\\fuel rod gun\\fuel rod";covenant_lighting_color(0,78,&color); + CHECK(!memcmp(&color,&authored,sizeof(color)),"unrelated attached light untouched"); + covenant_lighting_color(0,77,&color); + CHECK(color.red==authored.red*.30f&&color.green==authored.green&&color.blue==authored.blue*.20f,"flight light is greener with unchanged green intensity"); + CHECK(authored.red==.6f&&authored.green==.8f&&authored.blue==.5f,"authored source remains unchanged"); + color=authored;covenant_lighting_color(0,77,&color); + CHECK(color.red==authored.red*.30f&&exhaust_queries==1,"fresh submissions do not compound and tag lookup is cached"); + color.red=color.green=color.blue=0;covenant_lighting_color(0,77,&color); + CHECK(color.red==0&&color.green==0&&color.blue==0,"authored dark intervals stay dark"); + covenant_lighting_forget();exhaust_tag=NONE;color=authored;covenant_lighting_color(0,77,&color); + covenant_lighting_color(0,77,&color); + CHECK(!memcmp(&color,&authored,sizeof(color))&&exhaust_queries==2,"missing map tag stays stock and is cached"); + covenant_lighting_forget();exhaust_tag=78;covenant_lighting_color(0,77,&color); + CHECK(!memcmp(&color,&authored,sizeof(color)),"old map handle is rejected after transition"); + covenant_lighting_color(0,78,&color); + CHECK(color.red==authored.red*.30f&&exhaust_queries==3,"new map handle is resolved after transition"); +} +int main(int argc,char **argv) +{ + int i, before; + long held; + for(i=0;i<10;i++) { objects[i].object.node_matrices.size=sizeof(real_matrix4x3); objects[i].object.type=5; objects[i].object.bounding_sphere_center.x=1; } + if(argc>1&&!strcmp(argv[1],"color")) { color_checks();return 0; } + CHECK(covenant_lighting_scale(NULL)==0 && covenant_lighting_scale("unknown")==0,"exact profile admission"); + for(i=0;i + +#include "under_test.inc" + +static int same(unsigned char const *a, unsigned char const *b, size_t size) +{ + return memcmp(a, b, size) == 0; +} + +/* a zone effect's (feedback, vibration) strength / amplitude 1-8 in its first active zone */ +static int first_level(unsigned char const *effect) +{ + unsigned long active = effect[1] | (unsigned long)effect[2] << 8; + unsigned long bits = effect[3] | (unsigned long)effect[4] << 8 | (unsigned long)effect[5] << 16 | + (unsigned long)effect[6] << 24; + int zone; + + for (zone = 0; zone < 10 && !(active & (1UL << zone)); zone++) + ; + return zone < 10 ? (int)((bits >> (3 * zone)) & 7) + 1 : 0; +} + +static int is_off(unsigned char const *effect) +{ + unsigned char off[DUALSENSE_EFFECT_SIZE]; + + dualsense_effect_off(off); + return same(effect, off, sizeof(off)); +} + +/* R2 by the state at a strength */ +static void held_at(unsigned char effect[DUALSENSE_EFFECT_SIZE], struct dualsense_weapon_state const *state, int percent) +{ + dualsense_right_held(effect, state, percent); +} + +static void effects(void) +{ + unsigned char effect[DUALSENSE_EFFECT_SIZE]; + + dualsense_effect_off(effect); + CHECK(effect[0] == 0x05 && effect[1] == 0 && effect[10] == 0, "off is mode 5 and zeros"); + /* feedback from zone 3, strength 4: zones 3-9 active, each level 3 */ + dualsense_effect_feedback(effect, 3, 4); + CHECK(effect[0] == 0x21 && effect[1] == 0xf8 && effect[2] == 0x03, "feedback zones: %02x %02x", effect[1], effect[2]); + CHECK(first_level(effect) == 4, "feedback level %d", first_level(effect)); + /* a strength of 0 is off, out of range numbers are clamped */ + dualsense_effect_feedback(effect, 3, 0); + CHECK(is_off(effect), "strength 0 is off"); + dualsense_effect_feedback(effect, 99, 99); + CHECK(effect[0] == 0x21 && effect[1] == 0x00 && effect[2] == 0x02 && first_level(effect) == 8, + "clamped to zone 9, strength 8: %02x %02x", effect[1], effect[2]); + /* the span: zones 1-2 only */ + dualsense_effect_feedback_span(effect, 1, 2, 2); + CHECK(effect[0] == 0x21 && effect[1] == 0x06 && effect[2] == 0x00, "span zones: %02x %02x", effect[1], effect[2]); + /* the click: zones 4 and 7, strength 5 stored as 4 */ + dualsense_effect_weapon(effect, 4, 7, 5); + CHECK(effect[0] == 0x25 && effect[1] == 0x90 && effect[2] == 0x00 && effect[3] == 4, "weapon: %02x %02x %02x", + effect[1], effect[2], effect[3]); + dualsense_effect_weapon(effect, 0, 0, 3); + CHECK(effect[1] == 0x0c && effect[3] == 2, "a click starts at zone 2 and ends after it: %02x", effect[1]); + /* vibration: amplitude in the zones, frequency in byte 9 */ + dualsense_effect_vibration(effect, 3, 5, 30); + CHECK(effect[0] == 0x26 && effect[1] == 0xf8 && effect[9] == 30 && first_level(effect) == 5, "vibration"); +} + +static void kinds(void) +{ + /* (needler, rate, charging, heat, zoom levels, no projectile, plasma rifle type) */ + CHECK(dualsense_weapon_kind(0, 3.5f, 0, 0, 0, 0, 0) == DUALSENSE_WEAPON_SEMI, "pistol"); + CHECK(dualsense_weapon_kind(0, 1.0f, 0, 0, 0, 0, 0) == DUALSENSE_WEAPON_HEAVY, "shotgun"); + CHECK(dualsense_weapon_kind(0, 15.0f, 0, 0, 0, 0, 0) == DUALSENSE_WEAPON_AUTOMATIC, "assault rifle"); + CHECK(dualsense_weapon_kind(0, 2.0f, 0, 0, 2, 0, 0) == DUALSENSE_WEAPON_SNIPER, "sniper rifle"); + CHECK(dualsense_weapon_kind(0, 2.0f, 0, 0, 1, 0, 0) == DUALSENSE_WEAPON_SEMI, "one zoom level is no sniper rifle"); + CHECK(dualsense_weapon_kind(0, 3.0f, 0.4f, 0, 0, 0, 0) == DUALSENSE_WEAPON_CHARGE, "plasma pistol"); + CHECK(dualsense_weapon_kind(1, 8.0f, 0, 0.1f, 0, 0, 0) == DUALSENSE_WEAPON_NEEDLER, "needler"); + CHECK(dualsense_weapon_kind(0, 8.0f, 0, 0.01f, 0, 0, 1) == DUALSENSE_WEAPON_PLASMA_HEAT, "plasma rifle"); + CHECK(dualsense_weapon_kind(0, 8.0f, 0, 0.01f, 0, 0, 0) == DUALSENSE_WEAPON_FLAME, "flamethrower"); + CHECK(dualsense_weapon_kind(0, 0, 0, 0, 0, 1, 0) == DUALSENSE_WEAPON_CARRY, "ball and flag"); + CHECK(!strcmp(dualsense_weapon_kind_name(DUALSENSE_WEAPON_SNIPER), "sniper"), "name"); + /* only Sony's DualSense and DualSense Edge: other makers' PS5-type pads are left alone */ + CHECK(dualsense_is_dualsense(0x054c, 0x0ce6) && dualsense_is_dualsense(0x054c, 0x0df2), "DualSense, Edge"); + CHECK(!dualsense_is_dualsense(0x054c, 0x09cc) && !dualsense_is_dualsense(0x20d6, 0x0ce6) && + !dualsense_is_dualsense(0, 0), "DualShock 4, another maker's pad"); +} + +static void held(void) +{ + struct dualsense_weapon_state state; + unsigned char effect[DUALSENSE_EFFECT_SIZE]; + + memset(&state, 0, sizeof(state)); + /* no weapon, a carried ball: off */ + held_at(effect, &state, 100); + CHECK(is_off(effect), "no weapon is off"); + state.kind = DUALSENSE_WEAPON_CARRY; + held_at(effect, &state, 100); + CHECK(is_off(effect), "a carried ball is off"); + /* the pistol's click, strength 4 */ + state.kind = DUALSENSE_WEAPON_SEMI; + held_at(effect, &state, 100); + CHECK(effect[0] == 0x25 && effect[1] == 0x90 && effect[3] == 3, "pistol click: %02x %02x %02x", effect[0], effect[1], + effect[3]); + /* the weapon's state beats the shape: readying and reloading free, empty the dry click, overheated locked */ + state.readying = 1; + held_at(effect, &state, 100); + CHECK(is_off(effect), "readying is free"); + state.readying = 0; + state.reloading = 1; + held_at(effect, &state, 100); + CHECK(is_off(effect), "reloading is free"); + state.reloading = 0; + state.empty = 1; + held_at(effect, &state, 100); + CHECK(effect[0] == 0x25 && effect[1] == 0x80 && effect[2] == 0x01 && effect[3] == 1, "dry click: %02x %02x %02x", + effect[0], effect[1], effect[3]); + state.empty = 0; + state.kind = DUALSENSE_WEAPON_PLASMA_HEAT; + state.overheated = 1; + state.ticks = 4; + held_at(effect, &state, 100); + CHECK(effect[0] == 0x21 && first_level(effect) == 8, "overheated is locked: %02x", effect[0]); + state.ticks = 0; + held_at(effect, &state, 100); + CHECK(effect[0] == 0x26, "the throb: %02x", effect[0]); + state.overheated = 0; + /* heat raises the plasma rifle's hold from 2 to 6 */ + state.heat = 1.0f; + held_at(effect, &state, 100); + CHECK(first_level(effect) == 6, "hot: %d", first_level(effect)); + /* the assault rifle buzzes at its rate of fire while it fires, holds lightly otherwise */ + memset(&state, 0, sizeof(state)); + state.kind = DUALSENSE_WEAPON_AUTOMATIC; + state.rate_of_fire = 15.0f; + state.firing = 1; + held_at(effect, &state, 100); + CHECK(effect[0] == 0x26 && effect[9] == 15, "automatic firing at 15 Hz: %02x %d", effect[0], effect[9]); + /* the plasma pistol charging hums, faster once charged */ + memset(&state, 0, sizeof(state)); + state.kind = DUALSENSE_WEAPON_CHARGE; + held_at(effect, &state, 100); + CHECK(effect[0] == 0x21, "uncharged hold"); + state.charge = 0.5f; + held_at(effect, &state, 100); + CHECK(effect[0] == 0x26 && effect[9] == 25 && first_level(effect) == 2, "charging hum: %d %d", effect[9], + first_level(effect)); + state.charge = 1.0f; + held_at(effect, &state, 100); + CHECK(effect[9] == 40 && first_level(effect) == 3, "charged hum: %d %d", effect[9], first_level(effect)); +} + +static void strength(void) +{ + struct dualsense_weapon_state state; + unsigned char effect[DUALSENSE_EFFECT_SIZE], hair[DUALSENSE_EFFECT_SIZE]; + int kind; + + CHECK(dualsense_strength_percent("light") == DUALSENSE_STRENGTH_LIGHT, "light"); + CHECK(dualsense_strength_percent("normal") == 100, "normal"); + CHECK(dualsense_strength_percent("strong") == DUALSENSE_STRENGTH_STRONG, "strong"); + CHECK(dualsense_strength_percent("") == 100 && dualsense_strength_percent("LIGHT") == 100, "anything else is normal"); + dualsense_effect_feedback_span(hair, 1, 2, 2); + /* light: every weapon's hold or click is the hair trigger's tick */ + for (kind = DUALSENSE_WEAPON_SEMI; kind < DUALSENSE_WEAPON_KINDS; kind++) + { + if (kind == DUALSENSE_WEAPON_CARRY) + continue; + memset(&state, 0, sizeof(state)); + state.kind = (enum dualsense_weapon_kind)kind; + state.rate_of_fire = 8.0f; + held_at(effect, &state, DUALSENSE_STRENGTH_LIGHT); + CHECK(same(effect, hair, sizeof(hair)), "kind %d on light is the hair trigger: %02x %02x", kind, effect[0], + effect[1]); + } + /* strong: a hold two steps up, never above 6; a click two steps up, never above 7 */ + memset(&state, 0, sizeof(state)); + state.kind = DUALSENSE_WEAPON_SNIPER; + held_at(effect, &state, DUALSENSE_STRENGTH_STRONG); + CHECK(effect[0] == 0x21 && first_level(effect) == 6, "sniper hold on strong: %d", first_level(effect)); + state.kind = DUALSENSE_WEAPON_AUTOMATIC; + held_at(effect, &state, DUALSENSE_STRENGTH_STRONG); + CHECK(first_level(effect) == 4, "automatic hold on strong: %d", first_level(effect)); + state.kind = DUALSENSE_WEAPON_HEAVY; + held_at(effect, &state, DUALSENSE_STRENGTH_STRONG); + CHECK(effect[0] == 0x25 && effect[3] == 6, "shotgun click on strong: %d", effect[3]); + /* the dry click: a step firmer on strong */ + state.empty = 1; + held_at(effect, &state, DUALSENSE_STRENGTH_STRONG); + CHECK(effect[3] == 2, "dry click on strong"); +} + +static void events(void) +{ + unsigned char effect[DUALSENSE_EFFECT_SIZE]; + int ms; + + /* the pistol's shot: a snap from zone 0; the assault rifle's: none (its firing shape does it) */ + ms = dualsense_event(effect, DUALSENSE_WEAPON_SEMI, DUALSENSE_EVENT_SHOT, 100); + CHECK(ms == 35 && effect[0] == 0x21 && first_level(effect) == 7, "pistol shot kick: %d ms", ms); + ms = dualsense_event(effect, DUALSENSE_WEAPON_AUTOMATIC, DUALSENSE_EVENT_SHOT, 100); + CHECK(ms == 0 && is_off(effect), "automatic shot has no kick"); + /* the plasma pistol's blast when charged, its ordinary pulse otherwise */ + ms = dualsense_event(effect, DUALSENSE_WEAPON_CHARGE, DUALSENSE_EVENT_SHOT_CHARGED, 100); + CHECK(ms == 240 && effect[0] == 0x26 && effect[9] == 15, "charged blast: %d ms", ms); + ms = dualsense_event(effect, DUALSENSE_WEAPON_CHARGE, DUALSENSE_EVENT_SHOT, 100); + CHECK(ms == 70 && effect[9] == 40, "plasma pistol shot: %d ms", ms); + ms = dualsense_event(effect, DUALSENSE_WEAPON_HEAVY, DUALSENSE_EVENT_SHOT, 100); + CHECK(ms == 130 && effect[0] == 0x26 && effect[9] == 30, "shotgun shot kick: %d ms", ms); + /* light: kicks at most 2; strong: two steps up, at most 8 */ + dualsense_event(effect, DUALSENSE_WEAPON_SEMI, DUALSENSE_EVENT_SHOT, DUALSENSE_STRENGTH_LIGHT); + CHECK(first_level(effect) == 2, "light kick: %d", first_level(effect)); + dualsense_event(effect, DUALSENSE_WEAPON_SEMI, DUALSENSE_EVENT_SHOT, DUALSENSE_STRENGTH_STRONG); + CHECK(first_level(effect) == 8, "strong kick: %d", first_level(effect)); +} + +static void left(void) +{ + unsigned char effect[DUALSENSE_EFFECT_SIZE], tick[DUALSENSE_EFFECT_SIZE]; + + dualsense_effect_feedback_span(tick, 1, 2, 2); + dualsense_left_effect(effect, 1, 0, 0, 100); + CHECK(effect[0] == 0x21 && first_level(effect) == 2 && effect[1] == 0xfc, "zoomed hold"); + dualsense_left_effect(effect, 1, 3, 0, DUALSENSE_STRENGTH_STRONG); + CHECK(first_level(effect) == 3, "zoomed hold on strong"); + dualsense_left_effect(effect, 1, 3, 0, DUALSENSE_STRENGTH_LIGHT); + CHECK(is_off(effect), "zoomed on light is free"); + dualsense_left_effect(effect, 0, 3, 0, 100); + CHECK(same(effect, tick, sizeof(tick)), "grenades in hand: the hair tick"); + dualsense_left_effect(effect, 0, 3, 1, 100); + CHECK(is_off(effect), "a throw wound up is free"); + dualsense_left_effect(effect, 0, 0, 0, 100); + CHECK(effect[0] == 0x25 && effect[3] == 1, "no grenades: the dry click"); +} + +static void lights(void) +{ + int number; + + /* the player lights: SDL's patterns with the "at once" bit, back to the player */ + CHECK(dualsense_player_lights(1) == 0x24 && dualsense_player_lights(2) == 0x2a && + dualsense_player_lights(3) == 0x35 && dualsense_player_lights(4) == 0x3b, "patterns"); + CHECK(dualsense_player_lights(0) == 0 && dualsense_player_lights(5) == 0, "no pattern for another number"); + for (number = 1; number <= 4; number++) + CHECK(dualsense_player_index_of_lights(dualsense_player_lights(number)) == number - 1, "round trip %d", number); +} + +static void reports(void) +{ + unsigned char body[DUALSENSE_BODY_SIZE], report[DUALSENSE_BLUETOOTH_REPORT_SIZE], again[DUALSENSE_BLUETOOTH_REPORT_SIZE]; + unsigned char hidp = 0xA2; + unsigned long crc; + size_t size; + int i; + + for (i = 0; i < DUALSENSE_BODY_SIZE; i++) + body[i] = (unsigned char)(i + 1); + /* the CRC-32 check value */ + CHECK(dualsense_crc32(0, (unsigned char const *)"123456789", 9) == 0xCBF43926UL, "crc of 123456789"); + CHECK(dualsense_crc32(dualsense_crc32(0, (unsigned char const *)"1234", 4), (unsigned char const *)"56789", 5) == + 0xCBF43926UL, "crc continued"); + /* USB: report 0x02, the body, padded to 48 */ + size = dualsense_output_report(report, sizeof(report), 0, 5, body); + CHECK(size == DUALSENSE_USB_REPORT_SIZE && report[0] == 0x02 && same(report + 1, body, sizeof(body)), "usb"); + /* Bluetooth: 0x31, the sequence in the high nibble, 0x10, the body, the CRC of 0xA2 and the first 74 bytes */ + size = dualsense_output_report(report, sizeof(report), 1, 0x13, body); + CHECK(size == DUALSENSE_BLUETOOTH_REPORT_SIZE && report[0] == 0x31 && report[1] == 0x30 && report[2] == 0x10 && + same(report + 3, body, sizeof(body)), "bluetooth framing: %02x %02x", report[0], report[1]); + crc = dualsense_crc32(dualsense_crc32(0, &hidp, 1), report, 74); + CHECK(report[74] == (crc & 0xff) && report[75] == ((crc >> 8) & 0xff) && report[76] == ((crc >> 16) & 0xff) && + report[77] == ((crc >> 24) & 0xff), "bluetooth crc"); + dualsense_output_report(again, sizeof(again), 1, 0x14, body); + CHECK(!same(report + 74, again + 74, 4) && again[1] == 0x40, "the sequence number is in the crc"); + /* a write's errno as an outcome */ + CHECK(dualsense_write_result_of_errno(EAGAIN) == DUALSENSE_WRITE_BUSY && + dualsense_write_result_of_errno(ENODEV) == DUALSENSE_WRITE_GONE && + dualsense_write_result_of_errno(EACCES) == DUALSENSE_WRITE_REFUSED, "errno"); +} + +/* the link: only what changed is written, in one report, enable bits for those fields only */ +static void link_usb(void) +{ + struct dualsense_link link; + unsigned char body[DUALSENSE_BODY_SIZE], held[DUALSENSE_EFFECT_SIZE], off[DUALSENSE_EFFECT_SIZE]; + int fields; + + dualsense_effect_weapon(held, 4, 7, 6); + dualsense_effect_off(off); + dualsense_link_init(&link, 0); + CHECK(dualsense_link_due(&link, 0, body) == 0, "nothing wanted, nothing written"); + dualsense_link_want_triggers(&link, held, off); + fields = dualsense_link_due(&link, 0, body); + CHECK(fields == DUALSENSE_FIELD_TRIGGERS, "triggers due: %d", fields); + CHECK(body[DUALSENSE_BODY_ENABLE1] == (DUALSENSE_ENABLE1_RIGHT_TRIGGER | DUALSENSE_ENABLE1_LEFT_TRIGGER) && + body[DUALSENSE_BODY_ENABLE2] == 0, "only the trigger bits: %02x %02x", body[0], body[1]); + CHECK(same(body + DUALSENSE_BODY_RIGHT_TRIGGER, held, sizeof(held)) && + same(body + DUALSENSE_BODY_LEFT_TRIGGER, off, sizeof(off)), "the bytes"); + dualsense_link_result(&link, fields, DUALSENSE_WRITE_SENT, 0); + /* the same again is no write; a changed trigger is one; a lightbar joins as its own field */ + dualsense_link_want_triggers(&link, held, off); + CHECK(dualsense_link_due(&link, 1, body) == 0 && dualsense_link_due(&link, 2, body) == 0, "unchanged: no write"); + dualsense_link_want_triggers(&link, off, off); + dualsense_link_want_lightbar(&link, 1, 2, 3); + dualsense_link_want_player_lights(&link, 0x24); + fields = dualsense_link_due(&link, 3, body); + CHECK(fields == DUALSENSE_FIELDS, "all three fields: %d", fields); + CHECK(body[DUALSENSE_BODY_ENABLE2] == (DUALSENSE_ENABLE2_LIGHTBAR | DUALSENSE_ENABLE2_PLAYER_LIGHTS) && + body[DUALSENSE_BODY_RED] == 1 && body[DUALSENSE_BODY_GREEN] == 2 && body[DUALSENSE_BODY_BLUE] == 3 && + body[DUALSENSE_BODY_PLAYER_LIGHTS] == 0x24, "lightbar bytes"); + dualsense_link_result(&link, fields, DUALSENSE_WRITE_SENT, 3); + /* only the lightbar changes: only its bit */ + dualsense_link_want_lightbar(&link, 9, 2, 3); + fields = dualsense_link_due(&link, 4, body); + CHECK(fields == DUALSENSE_FIELD_LIGHTBAR && body[DUALSENSE_BODY_ENABLE1] == 0 && + body[DUALSENSE_BODY_ENABLE2] == DUALSENSE_ENABLE2_LIGHTBAR, "only the lightbar: %d", fields); + dualsense_link_result(&link, fields, DUALSENSE_WRITE_SENT, 4); + /* forced: sent though unchanged, once */ + dualsense_link_force(&link, DUALSENSE_FIELD_TRIGGERS); + fields = dualsense_link_due(&link, 5, body); + CHECK(fields == DUALSENSE_FIELD_TRIGGERS, "forced: %d", fields); + dualsense_link_result(&link, fields, DUALSENSE_WRITE_SENT, 5); + CHECK(dualsense_link_due(&link, 6, body) == 0, "a refresh is sent once"); + dualsense_link_want_lightbar(&link, 0, 0, 0); + dualsense_link_drop(&link, DUALSENSE_FIELD_LIGHTBAR); + CHECK(dualsense_link_due(&link, 7, body) == 0, "dropped fields are not written"); +} + +static void link_bluetooth(void) +{ + struct dualsense_link link; + unsigned char body[DUALSENSE_BODY_SIZE], one[DUALSENSE_EFFECT_SIZE], two[DUALSENSE_EFFECT_SIZE]; + int fields; + + dualsense_effect_feedback(one, 2, 3); + dualsense_effect_feedback(two, 2, 6); + dualsense_link_init(&link, 1); + dualsense_link_want_triggers(&link, one, one); + fields = dualsense_link_due(&link, 1000, body); + CHECK(fields == DUALSENSE_FIELD_TRIGGERS, "the first report goes at once"); + dualsense_link_result(&link, fields, DUALSENSE_WRITE_SENT, 1000); + /* a change inside the window waits; a later one replaces it; the latest goes as the window opens */ + dualsense_link_want_triggers(&link, two, two); + CHECK(dualsense_link_due(&link, 1010, body) == 0, "waits for the window"); + dualsense_link_want_triggers(&link, one, two); + CHECK(dualsense_link_due(&link, 1049, body) == 0, "still waits"); + dualsense_link_want_triggers(&link, two, one); + fields = dualsense_link_due(&link, 1050, body); + CHECK(fields == DUALSENSE_FIELD_TRIGGERS && same(body + DUALSENSE_BODY_RIGHT_TRIGGER, two, sizeof(two)) && + same(body + DUALSENSE_BODY_LEFT_TRIGGER, one, sizeof(one)), "the latest goes as the window opens"); + /* the window ignored (at exit) */ + dualsense_link_result(&link, fields, DUALSENSE_WRITE_SENT, 1050); + dualsense_link_want_triggers(&link, one, one); + CHECK(dualsense_link_due(&link, 1051, body) == 0, "inside the window"); + CHECK(dualsense_link_due_now(&link, 1051, body) == DUALSENSE_FIELD_TRIGGERS, "due now ignores the window"); + /* busy: kept, tried again a window later */ + dualsense_link_result(&link, DUALSENSE_FIELD_TRIGGERS, DUALSENSE_WRITE_BUSY, 1051); + CHECK(dualsense_link_due(&link, 1060, body) == 0 && dualsense_link_due(&link, 1100, body) == 0, + "busy: not at once"); + CHECK(dualsense_link_due(&link, 1101, body) == DUALSENSE_FIELD_TRIGGERS, "busy: tried again"); + /* gone: the pad has nothing from us, everything is sent again */ + dualsense_link_result(&link, DUALSENSE_FIELD_TRIGGERS, DUALSENSE_WRITE_SENT, 1101); + CHECK(dualsense_link_due(&link, 1200, body) == 0, "nothing to write"); + dualsense_link_result(&link, DUALSENSE_FIELD_TRIGGERS, DUALSENSE_WRITE_GONE, 1200); + CHECK(dualsense_link_due(&link, 1200, body) == DUALSENSE_FIELD_TRIGGERS, "gone: everything again"); +} + +static void bind(void) +{ + unsigned int bound[4] = { 0, 0, 0, 0 }; + + dualsense_bind(bound, 4, 0, 7); + dualsense_bind(bound, 4, 1, 9); + CHECK(bound[0] == 7 && bound[1] == 9, "two pads"); + /* pad 7 unplugged: port 1's handle is gone and never set again; pad 9 moves to port 0 */ + dualsense_bind(bound, 4, 0, 9); + CHECK(bound[0] == 9 && bound[1] == 0, "a pad that moved is bound to its new port only"); + dualsense_bind(bound, 4, 4, 9); + dualsense_bind(bound, 4, -1, 9); + CHECK(bound[0] == 9 && bound[1] == 0 && bound[2] == 0 && bound[3] == 0, "out of range: nothing"); +} + +int main(int argc, char **argv) +{ + const char *name = argc > 1 ? argv[1] : ""; + + if (!strcmp(name, "effects")) + effects(); + else if (!strcmp(name, "kinds")) + kinds(); + else if (!strcmp(name, "held")) + held(); + else if (!strcmp(name, "strength")) + strength(); + else if (!strcmp(name, "events")) + events(); + else if (!strcmp(name, "left")) + left(); + else if (!strcmp(name, "lights")) + lights(); + else if (!strcmp(name, "reports")) + reports(); + else if (!strcmp(name, "link-usb")) + link_usb(); + else if (!strcmp(name, "link-bluetooth")) + link_bluetooth(); + else if (!strcmp(name, "bind")) + bind(); + else + { + fprintf(stderr, "unknown case %s\n", name); + return 2; + } + return 0; +} diff --git a/tools/harness/tests/dynamic_shader_isolation.c b/tools/harness/tests/dynamic_shader_isolation.c new file mode 100644 index 0000000000..9718b4b4b5 --- /dev/null +++ b/tools/harness/tests/dynamic_shader_isolation.c @@ -0,0 +1,134 @@ +#include "harness.h" +typedef unsigned long DWORD; +typedef unsigned int GLuint; +typedef int BOOL; +#define XGPU_VERTEX_ATTRIBUTE_COUNT 16 +#define D3DRS_PS_MAX 64 +#define GL_VERTEX_SHADER 1 +struct nv2a_vertex_lighting; +struct nv2a_pixel_shader_key; +struct plasma_occlusion_uniforms { int enabled; }; +struct program_entry { GLuint program; int plasma_model_slots; struct plasma_occlusion_uniforms plasma_occlusion; }; +static struct { const char *dump_shaders; } debug_settings; +static int compiles, hashes, pp = 1, fail_compile, fail_link, last_lit, last_optional; +static int gpu_calls, bound, looked_up; +static float mask0, mask1; +static char *nv2a_vertex_shader_to_glsl(const DWORD *words, unsigned long count, + unsigned long packed, const struct nv2a_vertex_lighting *lighting, BOOL plasma) +{ + char *result = malloc(3); + result[0] = plasma ? '1' : '0'; result[1] = lighting ? '1' : '0'; result[2] = 0; + return result; +} +static GLuint xgpu_compile_shader(int kind, const char *source, const char *label) +{ compiles++; return fail_compile && source[0]=='1' ? 0 : compiles; } +static void shader_hash_set(GLuint shader, const char *source) { hashes++; } +static BOOL per_pixel_lighting(void) { return pp; } +static GLuint fragment_shader_get(const struct nv2a_pixel_shader_key *key); +static struct program_entry *program_get(GLuint vs, GLuint fs, BOOL optional) +{ + static struct program_entry entries[64]; + last_optional = optional; + if (!vs || (fail_link && last_lit && optional)) return NULL; + CHECK(vs < 64, "bounded lazy variants"); entries[vs].program = vs; + return &entries[vs]; +} +static void platform_log(const char *format, ...) {} +static int glGetUniformLocation(GLuint program, const char *name) +{ gpu_calls++; looked_up++; return 42; } +static void plasma_occlusion_model_initialize(GLuint program, struct plasma_occlusion_uniforms *uniforms) +{ gpu_calls++; } +static void plasma_occlusion_bind_model(const struct plasma_occlusion_uniforms *uniforms) +{ gpu_calls++; bound++; } +static void glUniform2f(int location, float a, float b) +{ gpu_calls++; mask0=a; mask1=b; } +#include "under_test.inc" +static GLuint fragment_shader_get(const struct nv2a_pixel_shader_key *key) +{ + last_lit = key->per_pixel_lighting != 0; + CHECK(!key->plasma_model || key->per_pixel_lighting==2, "only feature per-pixel sources need a different key"); + return 1 + key->per_pixel_lighting + key->plasma_model*3; +} +int main(int argc, char **argv) +{ + struct vertex_shader_object program = {0}; + struct nv2a_pixel_shader_key key = {0}; + struct program_entry *stock, *enhanced; + struct program_entry entry = {1, -1, {0}}; + int n, base, immediate, lit; + program.lighting.lights=2; device.vertex_shader=&program; +#ifndef HALO_ANDROID + program.plasma_model=TRUE; +#endif + if (!strcmp(argv[1], "gpu")) + { + initialize(&entry, FALSE); bind_model(&entry, 0); + CHECK(!gpu_calls, "stock path makes no feature GPU calls, including uniform lookups"); + initialize(&entry, TRUE); +#ifndef HALO_ANDROID + CHECK(looked_up==1 && gpu_calls==2, "enhanced initialization is lazy"); + bind_model(&entry, 2); CHECK(bound==1 && mask0==0 && mask1==1, "selected slots uploaded unchanged"); +#else + bind_model(&entry, 2); + CHECK(!gpu_calls && !looked_up && !bound && !mask0 && !mask1, "Android excludes all optional GPU setup even with a selected mask"); +#endif + base=gpu_calls; bind_model(&entry, 0); + CHECK(gpu_calls==base, "disable skips even a previously enhanced program's GPU setup"); + return 0; + } + if (!strcmp(argv[1], "failure")) + { + fail_link=1; + enhanced=draw_program_get(&program,FALSE,&key,1); + CHECK(enhanced, "per-vertex fallback remains available"); +#ifndef HALO_ANDROID + CHECK(program.plasma_lighting_failed && !program.lighting_failed && !key.per_pixel_lighting && !key.plasma_model, + "enhanced link failure is isolated and clears the fragment key"); +#endif + stock=draw_program_get(&program,FALSE,&key,0); + CHECK(stock && key.per_pixel_lighting==2 && !last_optional, "stock per-pixel path survives an enhanced failure"); + memset(&program,0,sizeof(program)); program.lighting.lights=2; +#ifndef HALO_ANDROID + program.plasma_model=TRUE; +#endif + fail_link=0; fail_compile=1; + draw_program_get(&program,FALSE,&key,1); base=compiles; + draw_program_get(&program,FALSE,&key,1); + CHECK(compiles==base, "failed variants are not recompiled each draw"); + CHECK(draw_program_get(&program,FALSE,&key,0) && key.per_pixel_lighting==2, "enhanced compile failure leaves stock usable"); + return 0; + } + if (!strcmp(argv[1], "unmarked")) + { + program.lighting.lights=0; + CHECK(draw_program_get(&program,FALSE,&key,1) && !key.plasma_model && !key.per_pixel_lighting, + "unmarked shaders retain per-vertex lighting and a stock fragment"); +#ifndef HALO_ANDROID + CHECK(last_optional, "instruction-recognized lighting does not depend on per-pixel registration"); + program.plasma_model=FALSE; +#endif + draw_program_get(&program,FALSE,&key,1); + CHECK(!last_optional, "unrelated shaders stay stock even with a selected mask"); + return 0; + } + for (lit=0;lit<2;lit++) for (immediate=0;immediate<2;immediate++) + { + pp=lit; base=compiles; + stock=draw_program_get(&program,immediate,&key,0); + CHECK(stock && !last_optional && !key.plasma_model && compiles==base+1, "off compiles only the stock variant"); + enhanced=draw_program_get(&program,immediate,&key,1); +#ifndef HALO_ANDROID + CHECK(enhanced && enhanced!=stock && last_optional && compiles==base+2, "on creates a distinct lazy variant"); +#else + CHECK(enhanced==stock && !last_optional && compiles==base+1, "Android always reuses stock"); +#endif + base=compiles; + for(n=0;n<20;n++) + { + CHECK(draw_program_get(&program,immediate,&key,0)==stock && !key.plasma_model, "off restores the exact cached stock program"); + CHECK(draw_program_get(&program,immediate,&key,(n&1)?2:3)==enhanced, "slot changes reuse one enhanced variant"); + } + CHECK(compiles==base && hashes==compiles, "toggles do not recompile or bypass binary-cache registration"); + } + return 0; +} diff --git a/tools/harness/tests/elevator_correction.c b/tools/harness/tests/elevator_correction.c index 7b4fffaaf8..108d39d72f 100644 --- a/tools/harness/tests/elevator_correction.c +++ b/tools/harness/tests/elevator_correction.c @@ -79,6 +79,12 @@ int main(int argc, char **argv) { objects[1].biped.elevator_object_index = 2; objects[1].object.position.z = 10; own->time = 100; own->unit_index = 1; own->position.z = 13.2f; own->elevator_index = 2; now = 100 + delay; + if (!strcmp(case_name,"scripted")) { + s.scripted_pose=TRUE;s.position.z=14; + distributed_correct_own_unit(&p,1,&s); + CHECK(objects[1].object.position.z==14,"scripted pose incorrectly reused input prediction"); + return 0; + } if (strstr(case_name,"-up")) {own->position.z=10; s.position.z=13.2f;} if (!strcmp(case_name,"jump")) objects[1].biped.flags = FLAG(_biped_airborne_bit); if (!strcmp(case_name,"walk-off")) objects[1].biped.elevator_ticks = 59; diff --git a/tools/harness/tests/elevator_prediction.c b/tools/harness/tests/elevator_prediction.c index 4dd14921c2..cad6c6540b 100644 --- a/tools/harness/tests/elevator_prediction.c +++ b/tools/harness/tests/elevator_prediction.c @@ -19,9 +19,8 @@ unit there. #include "harness.h" -/* Legacy movement: the MCC authority hook is inactive. */ -static boolean mcc_script_effects_host_movement(void) { return FALSE; } - +static boolean mcc_movement; +static boolean mcc_script_effects_host_movement(void) { return mcc_movement; } #include #include @@ -234,6 +233,13 @@ static real taken_height(long elevator_index, real velocity, real client_z) int main(int argc, char **argv) { char const *case_name = argc > 1 ? argv[1] : ""; + CASE("mcc-host-movement") + { + mcc_movement = TRUE; + CHECK(taken_height(NONE, 0.0f, 10.4f) == 10.0f, + "MCC enhanced movement must not accept client positions"); + return 0; + } /* going up, the client's word a round trip (200 ms) behind: the host's copy rides the host's elevator, and goes across as the client says */ diff --git a/tools/harness/tests/enhanced_controller.c b/tools/harness/tests/enhanced_controller.c new file mode 100644 index 0000000000..7f39314a33 --- /dev/null +++ b/tools/harness/tests/enhanced_controller.c @@ -0,0 +1,111 @@ +#include "harness.h" +#include +#define BOTS_MAXIMUM 63 +#define TICKS_PER_SECOND 30 +#define BOTS_SEARCHES_A_TICK 3 +#define _object_mask_item 1 +#define _unit_control_jump_bit 0 +enum { _bots_goal_none, _bots_goal_enemy, _bots_goal_roam, _bots_goal_item, _bots_goal_enhanced, _bots_goal_vehicle }; +enum { game_engine_slayer, game_engine_ctf, game_engine_king }; +struct bots_bot { + long player_index, goal_surface_index, goal_tick, goal_serial, path_failures, climb_until_tick, objective_retry_tick; + long intent_surface, target_player_index, target_last_surface_index, target_seen_tick; + long item_index, item_first_press_tick, item_check_tick; + short goal_kind, intent_kind; + boolean hunting; + real_point3d goal_point, intent_point, target_last_position; + struct { boolean valid; } path; +}; +static struct { struct bots_bot bots[BOTS_MAXIMUM]; long search_cursor, tick_searches; + long search_wait[BOTS_MAXIMUM], search_seen[BOTS_MAXIMUM]; + struct { real_point3d home[2]; } ctf; +} bots_globals; +static long now=100, parent=NONE; +static int seeking, carrying, hill, powerup_calls, urgent, failed; +struct player_datum { long unit_index; short team_index; }; +static struct player_datum player; +struct unit_datum { int unused; }; +static struct unit_datum unit; +struct object_datum { struct { long parent_object_index; real_point3d position; } object; }; +struct item_datum { struct { long parent_object_index; real_point3d position; } object; }; +static struct { int game_engine_index; } variant; +static long game_time_get(void) { return now; } +static struct player_datum *player_get(long i) { (void)i; return &player; } +static struct unit_datum *unit_get(long i) { (void)i; return &unit; } +static long bots_vehicle_parent(long i) { (void)i; return parent; } +static boolean enhanced_bots_carrying(long i) { (void)i; return carrying; } +static boolean bots_ctf_carrying(struct bots_bot *bot) { (void)bot; return carrying; } +static boolean enhanced_bots_holding_hill(long i) { (void)i; return hill; } +static boolean bots_vehicle_seeking(long i) { (void)i; return seeking; } +static void bots_vehicle_cancel(long i) { (void)i; seeking=FALSE; } +static boolean bots_vehicle_goal(long i,long u,real_point3d const *d,real_point3d *g,long *s) +{ (void)i;(void)u; CHECK(d->x == 100,"seat lost strategic destination");g->x=10;g->y=g->z=0;*s=2;return seeking; } +static boolean bots_vehicle_player_goal(long i,long u,real_point3d const *d,real_point3d *g,long *s) +{ (void)i;(void)u;(void)d;(void)g;(void)s;return FALSE; } +static boolean enhanced_bots_goal(long i,long p,real_point3d const *pos,boolean only,real_point3d *g,long *s) +{ (void)i;(void)p;(void)pos;if (only && !urgent && !carrying) return FALSE;g->x=100;g->y=g->z=0;*s=1;return TRUE; } +static boolean bots_powerup_goal(struct bots_bot *b,struct unit_datum *u,real_point3d const *p,boolean f) +{ (void)b;(void)u;(void)p;(void)f;powerup_calls++;return FALSE; } +#define game_engine_get_variant() (&variant) +static void *object_try_and_get_and_verify_type(long i,int t) { (void)i;(void)t;return NULL; } +static struct object_datum *object_get(long i) { (void)i;return NULL; } +static void bots_item_set_unreachable(struct bots_bot *b,long i) { (void)b;(void)i; } +static long bots_find_item(struct bots_bot *b,struct unit_datum *u,real_point3d const *p,real r) +{ (void)b;(void)u;(void)p;(void)r;return NONE; } +static long bots_surface_below(real_point3d const *p,real_point3d *g) { *g=*p;return 1; } +static void bots_pick_roam_goal(struct bots_bot *b,real_point3d const *p) { (void)p;b->goal_kind=_bots_goal_roam; } +static void enhanced_bots_failed(long i) { (void)i;failed++; } +static void bots_navigation_reset_bot(long i) { (void)i; } +enum { _collision_test_structure_bit, _collision_test_front_facing_surfaces_bit, _collision_test_objects_bit, +_collision_test_objects_scenery_bit, _collision_test_objects_machines_bit, _collision_test_objects_vehicles_bit }; +struct collision_result { int unused; }; +static int capture_wall; +static void vector_from_points3d(real_point3d const *a,real_point3d const *b,real_vector3d *d) +{ d->i=b->x-a->x;d->j=b->y-a->y;d->k=b->z-a->z; } +static boolean collision_test_vector(unsigned long f,real_point3d const *p,real_vector3d const *v,long u,struct collision_result *h) +{ (void)f;(void)p;(void)v;(void)u;(void)h;return capture_wall; } +#include "under_test.inc" +int main(int argc,char **argv) +{ + struct bots_bot *bot=&bots_globals.bots[0]; + real_point3d position={0,0,0}, goal={100,0,0}; + real direction=0; + unsigned long flags=0; + long i,t,served[BOTS_MAXIMUM]={0}; + CHECK(argc==2,"case"); + bot->target_player_index=NONE;bot->item_check_tick=1000; + variant.game_engine_index=game_engine_ctf; + if (!strcmp(argv[1],"seat")) { + bots_set_goal(bot,_bots_goal_enhanced,&goal,1); + seeking=TRUE;bots_choose_goal(bot,0,&position,FALSE); + CHECK(bot->goal_kind==_bots_goal_vehicle,"seat not selected"); + bot->path.valid=TRUE;i=bot->goal_serial; + for(t=0;t<60;t++){now++;bots_choose_goal(bot,0,&position,FALSE);} + CHECK(bot->path.valid && bot->goal_serial==i,"seat path invalidated each tick"); + carrying=TRUE;bots_choose_goal(bot,0,&position,FALSE); + CHECK(!seeking && bot->goal_kind==_bots_goal_enhanced,"carrier kept boarding intent"); + } else if (!strcmp(argv[1],"objectives")) { + bot->target_player_index=1;bot->target_seen_tick=now;bot->target_last_surface_index=3; + bots_choose_goal(bot,0,&position,FALSE); + CHECK(bot->goal_kind==_bots_goal_enhanced,"CTF chased last seen enemy"); + hill=TRUE;variant.game_engine_index=game_engine_king;powerup_calls=0; + bots_choose_goal(bot,0,&position,FALSE); + CHECK(!powerup_calls,"hill holder diverted to powerup"); + bots_goal_failed(bot);bots_choose_goal(bot,0,&position,FALSE); + CHECK(failed==1 && bot->goal_kind==_bots_goal_roam,"failed objective immediately reacquired"); + now+=301;bots_choose_goal(bot,0,&position,FALSE); + CHECK(bot->goal_kind==_bots_goal_enhanced,"objective never retried"); + } else if (!strcmp(argv[1],"capture")) { + carrying=TRUE;bots_globals.ctf.home[0].x=1;bots_globals.ctf.home[0].z=0.8f;now=112; + CHECK(enhanced_bots_capture_approach(0,&position,&direction,&flags),"no stand approach"); + CHECK(TEST_FLAG(flags,_unit_control_jump_bit),"raised stand not approached with jump"); + capture_wall=1;CHECK(!enhanced_bots_capture_approach(0,&position,&direction,&flags),"capture cut through base wall"); + capture_wall=0;carrying=FALSE;CHECK(!enhanced_bots_capture_approach(0,&position,&direction,&flags),"noncarrier moved"); + } else if (!strcmp(argv[1],"fairness")) { + for(t=0;t<100;t++){now++;bots_globals.tick_searches=0; + for(i=0;i=3,"search starvation at bot %ld",i); + now+=4;bots_globals.tick_searches=0;CHECK(bots_search_turn(62),"abandoned request blocked searches"); + } else return 2; + return 0; +} diff --git a/tools/harness/tests/enhanced_flight.c b/tools/harness/tests/enhanced_flight.c new file mode 100644 index 0000000000..25ad41072a --- /dev/null +++ b/tools/harness/tests/enhanced_flight.c @@ -0,0 +1,311 @@ +#define real_point3d harness_point3d +#include "harness.h" +#undef real_point3d +#include +#include +typedef union { struct { real x,y,z; }; real n[3]; } real_point3d; +#define BOTS_MAXIMUM 63 +#define TICKS_PER_SECOND 30 +#define REAL_MAX FLT_MAX +#define MIN(a,b) ((a)<(b)?(a):(b)) +#define MAX(a,b) ((a)>(b)?(a):(b)) +#define PIN(a,l,h) MIN(MAX(a,l),h) +#define csmemset memset +enum { _collision_test_structure_bit, _collision_test_front_facing_surfaces_bit, +_collision_test_objects_bit, _collision_test_objects_scenery_bit, +_collision_test_objects_machines_bit, _collision_test_objects_vehicles_bit }; +enum { _unit_control_weapon_primary_trigger_bit, _unit_control_jump_bit, _unit_control_crouch_modifier_bit }; +struct collision_result { real t; real_point3d point; struct { real_vector3d n; } plane; }; +struct object_datum { struct { real_point3d position, bounding_sphere_center; real bounding_sphere_radius, scale, body_vitality; +real_vector3d up, forward, translational_velocity; } object; long definition_index; struct { byte on_ground_ticks; } vehicle; } craft; +#define vehicle_datum object_datum +#define vehicle_datum_get object_get +struct player_action { struct { real i,j; } throttle; struct { real yaw,pitch; } desired_facing; +real primary_trigger; unsigned long control_flags; }; +static long now, calls; +static int wall, sealed, ceiling, distant, object_wall, ridge, roof; +static long game_time_get(void) { return now; } +static struct object_datum *object_get(long index) { CHECK(index==1,"craft id"); return &craft; } +static void vector_from_points3d(real_point3d const *a, real_point3d const *b, real_vector3d *v) +{ v->i=b->x-a->x; v->j=b->y-a->y; v->k=b->z-a->z; } +static real magnitude3d(real_vector3d const *v) { return (real)sqrt(v->i*v->i+v->j*v->j+v->k*v->k); } +static boolean collision_test_vector(unsigned long flags, real_point3d const *a, real_vector3d const *d, +long ignore, struct collision_result *hit) +{ + real t, y, z; + calls++; + memset(hit,0,sizeof(*hit)); + CHECK(ignore==1,"did not ignore own hull"); + if (object_wall && TEST_FLAG(flags,_collision_test_objects_bit)) return TRUE; + hit->t=0.5f; + if (roof && a->z>10 && a->z+d->k<10 && fabs(a->x)<10 && fabs(a->y)<10) return TRUE; + if (sealed || (ceiling && (a->z > 12 || a->z+d->k > 12))) return TRUE; + if (ridge && d->k < -1000 && a->x >= 20 && a->x <= 40) { hit->point.z=40;hit->plane.n.k=1;return TRUE; } + if (a->z >= 0 && a->z+d->k < 0) { hit->point.z=0; hit->plane.n.k=1; return TRUE; } + if (wall && fabs(d->i)>0.001f) { + t=(20-a->x)/d->i; y=a->y+t*d->j; z=a->z+t*d->k; + if (t>0 && t<1 && fabs(y)<(distant?1000:10) && z<(distant?1000:35)) return TRUE; + } + return FALSE; +} +#define MAXIMUM_MASS_POINTS_PER_PHYSICS 32 +struct unit_definition { struct { struct { long index; } physics; } object; } unit_tag; +struct mass_point_definition { real_point3d position; real radius; } mass[32]; +struct physics_definition { struct { long count; } mass_points; real_point3d center_of_mass; real radius; } physics_tag; +#define TAG_BLOCK_GET_ELEMENT(block,index,type) (&mass[index]) +static struct unit_definition *unit_definition_get(long index) { return &unit_tag; } +static struct physics_definition *physics_definition_get(long index) { return &physics_tag; } +static long config_integer(char const *name) { return 0; } +static void platform_log(char const *format, ...) { } +#include "under_test.inc" +int main(int argc, char **argv) +{ + struct player_action action; + real_point3d start={{0,0,20}}, goal={{60,0,20}}; + struct flight_state *state=&flights[0]; + int i; + CHECK(argc==2,"case"); + memset(&action,0,sizeof(action)); + craft.object.position=craft.object.bounding_sphere_center=start; + craft.object.bounding_sphere_radius=2;craft.object.scale=1;unit_tag.object.physics.index=NONE; + craft.object.up.k=craft.object.forward.i=1; + enhanced_flight_reset(0); state->vehicle=1; state->radius=state->height=2; state->spacing=8;state->cruise_height=28; + if (!strcmp(argv[1],"clear") || !strcmp(argv[1],"wall") || !strcmp(argv[1],"sealed")) { + wall=!strcmp(argv[1],"wall"); sealed=!strcmp(argv[1],"sealed"); + flight_begin(state,&start,&goal); + for(i=0;i<1000 && state->searching;i++) { + now=i; calls=0; flight_search(0,state); + CHECK(calls<=784,"unbounded per-tick collision work %ld",calls); + CHECK(state->count<=FLIGHT_NODES && state->expanded<=256,"node or expansion overflow"); + } + CHECK(!state->searching,"search never completed"); + if(sealed) CHECK(!state->step_count && state->retry>now,"unreachable craft never backs off"); + else { + real_point3d previous=start; + CHECK(state->step_count>0,"no route"); + if(wall) CHECK(state->step_count>1,"wall ignored"); + for(i=0;istep_count;i++) { + CHECK(flight_clear(1,&previous,&state->steps[i],2,2),"route clips wall"); + previous=state->steps[i]; + } + CHECK(flight_distance(&previous,&goal)<0.01f,"wrong destination"); + } + } else if (!strcmp(argv[1],"vertical")) { + goal=start;goal.z+=30; + enhanced_flight_reset(0); + enhanced_flight_action(0,1,TRUE,&goal,FALSE,FALSE,&action); + CHECK(!action.throttle.i && TEST_FLAG(action.control_flags,_unit_control_jump_bit),"hovering aircraft missed vertical climb"); + goal.z=start.z-15;now=8; + enhanced_flight_action(0,1,TRUE,&goal,TRUE,FALSE,&action); + CHECK(!action.throttle.i && TEST_FLAG(action.control_flags,_unit_control_crouch_modifier_bit),"hovering aircraft missed vertical descent"); + } else if (!strcmp(argv[1],"forward_flight")) { + real_point3d previous=start; + goal=start;goal.z+=16; + state->hovering=FALSE; + flight_begin(state,&start,&goal); + for(i=0;i<2000 && state->searching;i++) { now=i;calls=0;flight_search(0,state);CHECK(calls<=784,"work budget"); } + CHECK(!state->searching && state->step_count>1,"forward-flight aircraft took vertical shortcut"); + for(i=0;istep_count;i++) { + real dx=state->steps[i].x-previous.x,dy=state->steps[i].y-previous.y; + CHECK(fabs(state->steps[i].z-previous.z)<=0.5f*sqrt(dx*dx+dy*dy)+.001f,"unflyable vertical or steep route"); + previous=state->steps[i]; + } + CHECK(flight_distance(&previous,&goal)<.01f,"sloped route missed destination"); + } else if (!strcmp(argv[1],"fighter_landing")) { + goal=start;goal.z=0; + enhanced_flight_action(0,1,FALSE,&goal,TRUE,FALSE,&action); + CHECK(action.throttle.i>0 && action.desired_facing.pitch<0,"fighter tried unsupported vertical descent"); + CHECK(!TEST_FLAG(action.control_flags,_unit_control_crouch_modifier_bit),"fighter relied on crouch lift"); + sealed=1;now++; + enhanced_flight_action(0,1,FALSE,&goal,TRUE,FALSE,&action); + CHECK(!action.throttle.i,"landing drove into wall"); + sealed=0;craft.object.position.z=craft.object.bounding_sphere_center.z=1;now++; + enhanced_flight_action(0,1,FALSE,&goal,TRUE,FALSE,&action); + CHECK(enhanced_flight_landing(0) && enhanced_flight_can_exit(1),"low fighter cannot finish landing"); + craft.object.translational_velocity.i=.2f;craft.object.translational_velocity.k=-.15f;now++; + enhanced_flight_action(0,1,FALSE,&goal,TRUE,FALSE,&action); + CHECK(action.throttle.i>0 && action.throttle.i<.6f && action.desired_facing.pitch>0,"low fighter lost velocity correction while braking"); + craft.object.position.z=craft.object.bounding_sphere_center.z=4;now++; + enhanced_flight_action(0,1,FALSE,&goal,TRUE,FALSE,&action); + CHECK(action.throttle.i>0 && action.throttle.i<.6f && action.desired_facing.pitch>0,"low fighter failed to slow before touchdown"); + start.z=2;goal=start;goal.x+=10;goal.z=-1; + CHECK(!flight_clear(1,&start,&goal,2,2),"ordinary route crossed ground"); + CHECK(flight_sweep(1,&start,&goal,2,2,TRUE),"touchdown rejected upward ground"); + } else if (!strcmp(argv[1],"low_approach")) { + goal.x=45;goal.z=0;craft.object.translational_velocity.i=.6f;craft.object.translational_velocity.k=-.15f; + enhanced_flight_action(0,1,FALSE,&goal,TRUE,FALSE,&action); + CHECK(enhanced_flight_landing(0) && action.throttle.i<.6f && action.desired_facing.pitch>0, + "low fighter waited until directly over goal before arresting descent"); + } else if (!strcmp(argv[1],"dynamic_hull")) { + unit_tag.object.physics.index=0;physics_tag.mass_points.count=1;mass[0].radius=1; + CHECK(flight_clear(1,&start,&goal,2,2),"authored mass point route was blocked"); + object_wall=1; + CHECK(!flight_clear(1,&start,&goal,2,2),"authored hull ignored dynamic obstruction"); + } else if (!strcmp(argv[1],"terrain")) { + ridge=1;goal.z=0; + CHECK(flight_cruise_height(1,&start,&goal,2)==48,"cruise route ignored intervening ridge"); + start.z=80; + CHECK(flight_cruise_height(1,&start,&goal,2)==80,"cruise descended early toward floor"); + } else if (!strcmp(argv[1],"landing_site")) { + roof=1;goal=start;goal.z=0; + enhanced_flight_action(0,1,TRUE,&goal,TRUE,FALSE,&action); + CHECK(state->landing_checked && state->landing_ready,"roofed objective had no nearby landing site"); + CHECK(fabs(state->landing.x)>=10 || fabs(state->landing.y)>=10,"aircraft tried to descend through base roof"); + CHECK(flight_distance(&state->landing,&goal)<30,"landing site too far from objective"); + CHECK(!TEST_FLAG(action.control_flags,_unit_control_crouch_modifier_bit),"hover approach descended before aligning with open column"); + enhanced_flight_reset(0);sealed=1;now++; + enhanced_flight_action(0,1,TRUE,&goal,TRUE,FALSE,&action); + CHECK(state->failed && state->landing_checked,"unreachable landing site did not enter recovery"); + } else if (!strcmp(argv[1],"winged")) { + unit_tag.object.physics.index=0;physics_tag.mass_points.count=1;physics_tag.radius=2; + craft.object.translational_velocity.i=.5f;craft.object.translational_velocity.k=-.4f; + goal.x=100;goal.z=0; + enhanced_flight_action(0,1,FALSE,&goal,TRUE,FALSE,&action); + CHECK(!state->hovering && action.throttle.i>=.6f,"speed-dependent lift lost during approach"); + CHECK(action.desired_facing.pitch>0,"falling fighter did not arrest descent"); + state->phase=_flight_land;now++; + enhanced_flight_action(0,1,FALSE,&goal,TRUE,FALSE,&action); + CHECK(action.throttle.i>=.6f && action.desired_facing.pitch>0,"landing cut lift before touchdown"); + craft.object.position.x=craft.object.bounding_sphere_center.x=goal.x-12;now++; + enhanced_flight_action(0,1,FALSE,&goal,TRUE,FALSE,&action); + CHECK(fabs(action.desired_facing.yaw)>1,"landing left the objective on an unbounded straight glide"); + craft.vehicle.on_ground_ticks=5;now++; + enhanced_flight_action(0,1,FALSE,&goal,TRUE,FALSE,&action); + CHECK(action.throttle.i<0,"landed fighter did not brake"); + } else if (!strcmp(argv[1],"climb_progress")) { + goal=start;goal.x=500;goal.z=0;state->destination=goal; + state->step_count=1;state->steps[0]=start;state->steps[0].z=200; + state->remaining=1;state->progress_tick=0; + for(i=0;i<60;i++) { + now=i*TICKS_PER_SECOND;craft.object.position.z=craft.object.bounding_sphere_center.z=20+i; + enhanced_flight_action(0,1,TRUE,&goal,FALSE,FALSE,&action); + CHECK(!state->failed,"active climb mistaken for a stuck objective"); + } + } else if (!strcmp(argv[1],"lookahead")) { + state->destination=goal;state->hovering=TRUE;state->step_count=4; + for(i=0;i<4;i++) { state->steps[i]=start;state->steps[i].x=8*(i+1); } + enhanced_flight_action(0,1,TRUE,&goal,FALSE,FALSE,&action); + CHECK(state->step==3 && action.throttle.i>0,"transport chased every small grid cell"); + wall=1;state->step=0;now=8; + enhanced_flight_action(0,1,TRUE,&goal,FALSE,FALSE,&action); + CHECK(state->step==1,"lookahead shortcut crossed a wall"); + } else if (!strcmp(argv[1],"hold")) { + wall=1;craft.object.translational_velocity.k=-.02f; + enhanced_flight_action(0,1,TRUE,&goal,FALSE,FALSE,&action); + CHECK(!action.throttle.i && TEST_FLAG(action.control_flags,_unit_control_jump_bit),"pending route let hover craft fall out of flight"); + craft.object.translational_velocity.k=.03f;now=1; + enhanced_flight_action(0,1,TRUE,&goal,FALSE,FALSE,&action); + CHECK(!action.throttle.i && TEST_FLAG(action.control_flags,_unit_control_crouch_modifier_bit),"waiting craft did not damp upward drift"); + } else if (!strcmp(argv[1],"mass_budget")) { + unit_tag.object.physics.index=0;physics_tag.mass_points.count=32;wall=1; + flight_begin(state,&start,&goal); + for(i=0;i<1000 && state->searching;i++) { + now=i;calls=0;flight_search(0,state); + CHECK(calls<=3520,"unbounded authored-hull collision work %ld",calls); + } + CHECK(!state->searching && state->step_count>0,"authored-hull planner did not complete"); + } else if (!strcmp(argv[1],"partial")) { + wall=distant=1;goal.x=6000; + flight_begin(state,&start,&goal); + for(i=0;i<1000 && state->searching;i++) { now=i;flight_search(0,state); } + CHECK(!state->searching && state->step_count>0,"bounded search discarded useful partial progress"); + CHECK(state->count<=FLIGHT_NODES && state->step_count<=FLIGHT_STEPS,"partial route exceeded bounds"); + for(i=0;istep_count;i++) { + real_point3d previous=i?state->steps[i-1]:start; + CHECK(flight_clear(1,&previous,&state->steps[i],2,2),"partial route crosses barrier"); + } + CHECK(flight_distance(&state->steps[state->step_count-1],&goal)0 && action.desired_facing.pitch==0 && TEST_FLAG(action.control_flags,_unit_control_jump_bit),"no takeoff"); + craft.object.forward.i=-1; + enhanced_flight_action(0,1,TRUE,&goal,FALSE,FALSE,&action); + CHECK(action.throttle.i==0 && fabs(action.desired_facing.yaw)<0.01f && TEST_FLAG(action.control_flags,_unit_control_jump_bit),"parked aircraft drove into wall instead of turning toward exit"); + craft.object.forward.i=1;craft.vehicle.on_ground_ticks=5; + enhanced_flight_action(0,1,FALSE,&goal,FALSE,FALSE,&action); + CHECK(action.throttle.i>=.8f && action.desired_facing.pitch>0,"grounded fighter could not build takeoff airspeed"); + craft.object.forward.i=-1;craft.vehicle.on_ground_ticks=0; + sealed=1; action.throttle.i=1;action.desired_facing.yaw=0; + enhanced_flight_action(0,1,TRUE,&goal,FALSE,FALSE,&action); + CHECK(action.throttle.i==0 && !TEST_FLAG(action.control_flags,_unit_control_jump_bit),"takeoff through obstruction"); + CHECK(cos(action.desired_facing.yaw)<-0.999f && action.desired_facing.pitch==0,"route wait leaked combat steering into aircraft"); + } else if (!strcmp(argv[1],"clearance")) { + wall=1; start.y=goal.y=11; + CHECK(flight_clear(1,&start,&goal,0,0),"center ray blocked"); + CHECK(!flight_clear(1,&start,&goal,2,2),"wide custom hull clipped wall"); + } else if (!strcmp(argv[1],"retarget")) { + action.desired_facing.yaw=3.0f; now=0; + enhanced_flight_action(0,1,TRUE,&goal,FALSE,FALSE,&action); + CHECK(fabs(action.desired_facing.yaw)<.1f,"combat aim hijacked flight"); + goal.y=60; now=8; + enhanced_flight_action(0,1,TRUE,&goal,FALSE,FALSE,&action); + CHECK(flights[0].destination.y==60,"stale destination"); + CHECK(fabs(action.desired_facing.yaw-0.785398f)<0.01f,"aircraft did not receive the absolute route heading"); + enhanced_flight_reset(0); + CHECK(flights[0].vehicle==NONE && !flights[0].step_count,"flight leaked across respawn"); + } else if (!strcmp(argv[1],"braking")) { + craft.object.translational_velocity.i=1.0f; + enhanced_flight_action(0,1,TRUE,&goal,TRUE,FALSE,&action); + CHECK(state->phase==_flight_approach && action.throttle.i==0,"fast custom craft did not brake early"); + craft.object.translational_velocity.i=.01f;now=1; + enhanced_flight_action(0,1,TRUE,&goal,TRUE,FALSE,&action); + CHECK(state->phase==_flight_approach,"slowing craft switched back to cruise"); + } else if (!strcmp(argv[1],"recovery")) { + enhanced_flight_action(0,1,TRUE,&goal,TRUE,FALSE,&action); + now=46*TICKS_PER_SECOND; + enhanced_flight_action(0,1,TRUE,&goal,TRUE,FALSE,&action); + CHECK(enhanced_flight_failed(0) && !action.throttle.i && TEST_FLAG(action.control_flags,_unit_control_crouch_modifier_bit),"blocked aircraft never recovered to ground"); + enhanced_flight_reset(0); + CHECK(!enhanced_flight_failed(0),"recovery leaked into a later vehicle"); + } else if (!strcmp(argv[1],"shape")) { + craft.object.bounding_sphere_radius=12; + CHECK(flight_height(1)==12,"missing shape did not retain sphere"); + unit_tag.object.physics.index=0;physics_tag.mass_points.count=2; + mass[0].position.y=11;mass[0].radius=1; + mass[1].position.z=-1;mass[1].radius=1; + CHECK(flight_height(1)==2,"flat aircraft required wingspan in vertical clearance"); + craft.object.scale=2; + CHECK(flight_height(1)==2,"render scale incorrectly changed engine physics hull"); + craft.object.scale=0; + CHECK(flight_height(1)==2,"engine default scale was treated as missing physics"); + ceiling=1;start.z=goal.z=6; + unit_tag.object.physics.index=NONE; + CHECK(!flight_clear(1,&start,&goal,12,12),"sphere fixture did not meet hangar roof"); + unit_tag.object.physics.index=0; + CHECK(flight_clear(1,&start,&goal,12,flight_height(1)),"thin aircraft could not leave low hangar"); + physics_tag.center_of_mass.z=-10; + CHECK(!flight_clear(1,&start,&goal,12,flight_height(1)),"center of mass offset omitted from hull sweep"); + physics_tag.center_of_mass.z=-3; + CHECK(flight_height(1)==4,"center of mass offset omitted from height"); + physics_tag.center_of_mass.z=0; + craft.object.up.j=1;craft.object.up.k=0; + CHECK(flight_height(1)==12,"banked wing clearance ignored attitude"); + craft.object.up.j=0;craft.object.up.k=1; + craft.object.position.z=craft.object.bounding_sphere_center.z=6; + goal.z=0;state->radius=12;state->cruise_height=8; + enhanced_flight_action(0,1,TRUE,&goal,FALSE,FALSE,&action); + CHECK(state->target.z==8 && state->step_count>0 && action.throttle.i>0,"flat craft cruise target was above the hangar ceiling"); + physics_tag.mass_points.count=33; + CHECK(flight_height(1)==12,"invalid shape count was used"); + } else CHECK(0,"unknown case"); + return 0; +} diff --git a/tools/harness/tests/enhanced_objective_policy.c b/tools/harness/tests/enhanced_objective_policy.c new file mode 100644 index 0000000000..29e674fdc5 --- /dev/null +++ b/tools/harness/tests/enhanced_objective_policy.c @@ -0,0 +1,42 @@ +#include "harness.h" +enum { _bots_goal_objective=1 }; +struct bots_bot { long player_index,goal_surface_index; short goal_kind; real_point3d goal_point; }; +static struct { struct bots_bot bots[1]; } bots_globals; +struct player_datum { long unit_index; }; +static struct player_datum player; +static int ctf=1,king,defender,carrier,on_hill,tactics; +static struct player_datum *player_get(long i) { (void)i; return &player; } +static void bots_tactics_check(long i,long p) { (void)i;(void)p; } +static boolean bots_ctf_active(void) { return ctf; } +static boolean bots_king_active(void) { return king; } +static boolean bots_ctf_defender(struct bots_bot *b,struct player_datum *p) { (void)b;(void)p;return defender; } +static boolean bots_ctf_carrying(struct bots_bot *b) { (void)b;return carrier; } +static boolean bots_ctf_urgent_goal(struct bots_bot *b,struct player_datum *p,real_point3d const *pos) +{ (void)b;(void)p;(void)pos;return carrier; } +static boolean bots_ctf_choose_goal(struct bots_bot *b,struct player_datum *p,real_point3d const *pos) +{ (void)p;(void)pos;b->goal_kind=_bots_goal_objective;b->goal_point.x=100;return TRUE; } +static boolean bots_king_choose_goal(struct bots_bot *b,struct player_datum *p,real_point3d const *pos) +{ (void)b;(void)p;(void)pos;return king; } +static boolean bots_king_on_hill(long u) { (void)u;return on_hill; } +static boolean infection_enabled(void) { return FALSE; } +static boolean infection_unit_is_zombie(long u) { (void)u;return FALSE; } +static boolean bots_infection_goal(struct bots_bot *b,struct player_datum *p,real_point3d const *pos) +{ (void)b;(void)p;(void)pos;return FALSE; } +static void bots_tactics_objective(long i) { (void)i; } +static boolean bots_tactics_goal(long i,long p,real_point3d const *pos,real_point3d *g,long *s) +{ (void)i;(void)p;(void)pos;g->x=20;*s=1;tactics++;return TRUE; } +#include "under_test.inc" +int main(int argc,char **argv) { + real_point3d pos={0,0,0},goal;long surface; + CHECK(argc==2,"case"); + defender=!strcmp(argv[1],"defender");carrier=!strcmp(argv[1],"carrier"); + if(!strcmp(argv[1],"hill")) {ctf=0;king=1;} + CHECK(enhanced_bots_goal(0,0,&pos,FALSE,&goal,&surface),"no goal"); + if(!strcmp(argv[1],"attacker")) { + CHECK(!tactics && goal.x==100,"attacker abandoned flag for vantage"); + CHECK(enhanced_bots_advancing(0,0),"attacker stopped advancing in combat"); + } else if(defender) { CHECK(tactics==1,"defender lost covering vantage");CHECK(!enhanced_bots_advancing(0,0),"defender became attacker"); } + else if(carrier) CHECK(!tactics && enhanced_bots_advancing(0,0),"carrier abandoned return"); + else {CHECK(enhanced_bots_advancing(0,0),"off-hill bot stopped");on_hill=1;CHECK(!enhanced_bots_advancing(0,0),"hill holder left");} + return 0; +} diff --git a/tools/harness/tests/first_person_interpolation.c b/tools/harness/tests/first_person_interpolation.c index 6df40d615c..3c6f74c191 100644 --- a/tools/harness/tests/first_person_interpolation.c +++ b/tools/harness/tests/first_person_interpolation.c @@ -1,148 +1,165 @@ #include "harness.h" #include +#include -#include "config.inc" +#define MAXIMUM_LOCAL_PLAYERS 4 +#define MAXIMUM_INTERPOLATED_NODES 64 +#define MAXIMUM_INTERPOLATED_OBJECTS 1 +#define REAL_MAX FLT_MAX -/* One local player's first-person weapon of two nodes, drawn from a camera at -the origin looking along x (render_interpolation.c). Each tick the game poses -the nodes in the world from the camera; each frame between ticks the pose is -blended from the last tick's. */ -#define WEAPON 0x10002L -#define OTHER_WEAPON 0x10003L -#define GRAPH 0x20004L -#define OTHER_GRAPH 0x20005L -#define NODES 2 -#define PI 3.14159265f - -struct render_camera { real_point3d position; real_vector3d forward, up; }; -static void cross_product3d(real_vector3d const *a, real_vector3d const *b, real_vector3d *result) +typedef struct { - result->i = a->j * b->k - a->k * b->j; - result->j = a->k * b->i - a->i * b->k; - result->k = a->i * b->j - a->j * b->i; -} -static void set_real_point3d(real_point3d *point, real x, real y, real z) { point->x = x; point->y = y; point->z = z; } + real scale; + union + { + real n[4][3]; + struct { real_vector3d forward, left, up; real_point3d position; }; + }; +} real_matrix4x3; +struct render_camera { real_point3d position; real_vector3d forward, up; }; +static struct { long object_index; } *interpolated_objects; +static int interpolated_cameras[MAXIMUM_LOCAL_PLAYERS]; static long interpolation_tick; static boolean interpolation_rendering = TRUE; -static real interpolation_fraction; - +static real interpolation_fraction = 0.5f; +static void cross_product3d(real_vector3d const *a, real_vector3d const *b, real_vector3d *r) +{ + r->i = a->j*b->k-a->k*b->j; + r->j = a->k*b->i-a->i*b->k; + r->k = a->i*b->j-a->j*b->i; +} +static void set_real_point3d(real_point3d *p, real x, real y, real z) { p->x=x; p->y=y; p->z=z; } #include "under_test.inc" -static struct render_camera camera = { { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }; -static real_matrix4x3 nodes[NODES]; +static struct render_camera camera = {{0,0,0},{1,0,0},{0,0,1}}; +static real_matrix4x3 identity = {1, {{{1,0,0},{0,1,0},{0,0,1},{0,0,0}}}}; +static real_matrix4x3 nodes[64]; +static long weapon = 0x10001, graph = 0x20002; +static short local, count = 2; -/* a node so far along x, turned so far about z */ -static void pose(short node, real x, real angle) +static void pose(real position, real angle) { - real_matrix4x3 *matrix = &nodes[node]; - - matrix->scale = 1.0f; - matrix->forward.i = (real)cos(angle); - matrix->forward.j = (real)sin(angle); - matrix->forward.k = 0.0f; - matrix->left.i = -matrix->forward.j; - matrix->left.j = matrix->forward.i; - matrix->left.k = 0.0f; - matrix->up.i = 0.0f; - matrix->up.j = 0.0f; - matrix->up.k = 1.0f; - set_real_point3d(&matrix->position, x, 0.0f, 0.0f); + short i; + real_matrix4x3 camera_matrix, node = identity; + matrix4x3_from_point_and_vectors(&camera_matrix, &camera.position, &camera.forward, &camera.up); + node.position.x = position; + node.forward.i = node.left.j = (real)cos(angle); + node.forward.j = (real)sin(angle); + node.left.i = -node.forward.j; + for (i=0; i<64; i++) matrix4x3_multiply(&camera_matrix, &node, &nodes[i]); } - -/* a frame drawn a fraction into a tick, both nodes so far along x */ -static void frame(long tick, real fraction, long weapon, long graph, real x) +static void draw(void) { - interpolation_tick = tick; - interpolation_fraction = fraction; - pose(0, x, 0.0f); - pose(1, x, 0.0f); - render_interpolation_first_person(0, weapon, graph, nodes, NODES, &camera); + render_interpolation_first_person(local, weapon, graph, nodes, count, &camera); } - -static void expect(real x) +static void tick(long tick_index, real position) { - CHECK(fabs(nodes[0].position.x - x) < 1e-4f && fabs(nodes[1].position.x - x) < 1e-4f, - "drawn at %f and %f, not %f", nodes[0].position.x, nodes[1].position.x, x); + interpolation_tick = tick_index; + pose(position, 0); + draw(); +} +static void expect(real value) +{ + CHECK(fabs(nodes[0].position.x-value)<1e-5f, "position %f expected %f", nodes[0].position.x, value); } int main(int argc, char **argv) { - char const *case_name = argc > 1 ? argv[1] : ""; - - frame(10, 1.0f, WEAPON, GRAPH, 0.0f); - /* a melee swings the weapon further in a tick than any limit that would - tell it from another weapon: it is blended all the same */ - CASE("melee") - { - frame(11, 0.25f, WEAPON, GRAPH, 0.8f); - expect(0.2f); - frame(11, 0.75f, WEAPON, GRAPH, 0.8f); - expect(0.6f); - /* (from the tick's pose, not the last frame drawn) */ - frame(12, 0.5f, WEAPON, GRAPH, 1.6f); - expect(1.2f); - } - /* another weapon of as many nodes: drawn as it is, then blended */ - CASE("weapon") - { - frame(11, 0.5f, OTHER_WEAPON, GRAPH, 0.1f); - expect(0.1f); - frame(12, 0.5f, OTHER_WEAPON, GRAPH, 0.2f); - expect(0.15f); - } - CASE("graph") - { - frame(11, 0.5f, WEAPON, OTHER_GRAPH, 0.1f); - expect(0.1f); - } - /* a weapon changed between two frames of a tick */ - CASE("within a tick") - { - frame(11, 0.25f, WEAPON, GRAPH, 0.4f); - expect(0.1f); - frame(11, 0.75f, OTHER_WEAPON, GRAPH, 0.2f); - expect(0.2f); - frame(12, 0.5f, OTHER_WEAPON, GRAPH, 0.4f); - expect(0.3f); - } - /* the view away from first person for a while */ - CASE("gap") - { - frame(14, 0.5f, WEAPON, GRAPH, 0.4f); - expect(0.4f); - } - CASE("not a number") - { - interpolation_tick = 11; - interpolation_fraction = 0.5f; - pose(0, 0.4f, 0.0f); - pose(1, 0.4f, 0.0f); - nodes[1].position.y = NAN; - render_interpolation_first_person(0, WEAPON, GRAPH, nodes, NODES, &camera); - CHECK(nodes[0].position.x == 0.4f, "a pose with a node not a number blended"); - } - /* a node set back by half a turn snaps; the other still blends */ - CASE("half turn") - { - interpolation_tick = 11; - interpolation_fraction = 0.5f; - pose(0, 0.4f, 0.0f); - pose(1, 0.0f, PI); - render_interpolation_first_person(0, WEAPON, GRAPH, nodes, NODES, &camera); - CHECK(fabs(nodes[0].position.x - 0.2f) < 1e-4f, "the other node not blended"); - CHECK(nodes[1].forward.i < -0.999f, "half a turn blended: forward (%f, %f)", - nodes[1].forward.i, nodes[1].forward.j); - } - /* a large turn short of half a turn is blended */ - CASE("large turn") - { - interpolation_tick = 11; - interpolation_fraction = 0.5f; - pose(0, 0.0f, 0.0f); - pose(1, 0.0f, 170.0f * PI / 180.0f); - render_interpolation_first_person(0, WEAPON, GRAPH, nodes, NODES, &camera); - CHECK(fabs(atan2(nodes[1].forward.j, nodes[1].forward.i) - 85.0f * PI / 180.0f) < 1e-3f, - "170 degrees not blended halfway: forward (%f, %f)", nodes[1].forward.i, nodes[1].forward.j); - } - return 0; + const char *case_name = argc>1 ? argv[1] : ""; + tick(10, 0); + CASE("fast-motion") + { + int frame; + /* A valid continuous pose can move beyond the former 0.25 limit. + Sample the same tick at 120 Hz, including a rotating chamber. */ + for (frame=0; frame<4; frame++) + { + real qz, qw, expected_rotation; + interpolation_tick = 11; + interpolation_fraction = frame*0.25f; + pose(0.6f, 1.5707963268f); + draw(); + expect(0.6f*interpolation_fraction); + qz=interpolation_fraction*(real)sqrt(.5); + qw=1-interpolation_fraction+qz; + expected_rotation=2*qw*qz/(qw*qw+qz*qz); + CHECK(fabs(nodes[0].forward.j-expected_rotation)<1e-5f, "rotation not interpolated"); + } + tick(12, 0.8f); + expect(0.75f); /* Previous is the raw 0.6 pose, never the last blend. */ + } + CASE("weapon-change") { weapon += 0x10000; tick(11, .1f); expect(.1f); tick(12,.2f); expect(.15f); } + CASE("graph-change") { graph++; tick(11,.1f); expect(.1f); } + CASE("same-tick-change") + { + tick(11,.1f); expect(.05f); + weapon++; tick(11,.2f); expect(.2f); + tick(12,.3f); expect(.25f); + } + CASE("node-count") { tick(11,.1f); count=3; tick(11,.2f); expect(.2f); tick(12,.3f); expect(.25f); } + CASE("gap") { tick(13,.1f); expect(.1f); tick(14,.2f); expect(.15f); } + CASE("disabled") + { + tick(11,.1f); interpolation_rendering=FALSE; tick(11,.12f); expect(.12f); + interpolation_rendering=TRUE; tick(11,.14f); expect(.14f); + tick(12,.16f); expect(.15f); + } + CASE("reset") { tick(11,.1f); render_interpolation_reset(); tick(11,.2f); expect(.2f); tick(12,.3f); expect(.25f); } + CASE("players") { local=1; tick(10,.8f); tick(11,.9f); expect(.85f); local=0; tick(11,.1f); expect(.05f); } + CASE("camera") + { + camera.position.x=40; + camera.forward.i=0; camera.forward.j=1; + tick(11,.2f); + expect(40); + CHECK(fabs(nodes[0].position.y-.1f)<1e-5f, "pose not blended in camera space"); + } + CASE("invalid") + { + tick(11,.1f); + local=-1; tick(11,.2f); expect(.2f); + local=4; tick(11,.2f); expect(.2f); + local=0; count=65; tick(11,.2f); expect(.2f); + count=2; tick(12,.3f); expect(.3f); + interpolation_tick=13; pose(.4f,0); nodes[1].position.x=NAN; draw(); expect(.4f); + CHECK(isnan(nodes[1].position.x), "invalid node unexpectedly blended"); + tick(14,.5f); expect(.5f); + } + CASE("capacity") + { + count=64; tick(11,.1f); expect(.1f); tick(12,.2f); expect(.15f); + CHECK(fabs(nodes[63].position.x-.15f)<1e-5f, "last valid node not blended"); + count=0; tick(12,.22f); expect(.22f); count=64; tick(13,.24f); expect(.24f); + } + CASE("missing") + { + weapon=NONE; tick(11,.1f); expect(.1f); + weapon=0x10001; tick(12,.12f); expect(.12f); + graph=NONE; tick(13,.14f); expect(.14f); + graph=0x20002; tick(14,.16f); expect(.16f); + } + CASE("chamber-reset") + { + int frame; + for (frame=0; frame<4; frame++) + { + interpolation_tick=11; interpolation_fraction=frame*.25f; + pose(.1f,0); + /* Only the tube node resets. The other node keeps moving. */ + nodes[1].forward.i=nodes[1].left.j=-1; + draw(); expect(.1f*interpolation_fraction); + CHECK(nodes[1].forward.i == -1 && nodes[1].forward.j == 0, + "authored half-turn reset generated an extra spin"); + } + interpolation_tick=12; interpolation_fraction=.5f; + pose(.2f,0); nodes[1].forward.i=nodes[1].left.j=-1; + draw(); expect(.15f); + CHECK(nodes[1].forward.i == -1, "half-turn reset poisoned next tick"); + } + CASE("large-rotation") + { + interpolation_tick=11; pose(.1f,2.9670597284f); draw(); expect(.05f); + CHECK(fabs(nodes[0].forward.j-.9961947f)<1e-5f, "ordinary 170-degree rotation snapped"); + } + return 0; } diff --git a/tools/harness/tests/first_person_legs.c b/tools/harness/tests/first_person_legs.c new file mode 100644 index 0000000000..96c92380ab --- /dev/null +++ b/tools/harness/tests/first_person_legs.c @@ -0,0 +1,387 @@ +/* The local player's own legs in first person (port/linux/game/first_person_legs.c) */ +#include "harness.h" +#include +#define MIN(a, b) ((a) < (b) ? (a) : (b)) +#define MAX(a, b) ((a) > (b) ? (a) : (b)) +#define PIN(x, lo, hi) MIN(MAX((x), (lo)), (hi)) +#define _pi ((real)3.14159265358979323846f) +#define MAXIMUM_LOCAL_PLAYERS 4 +#define MAXIMUM_NODES_PER_MODEL 64 +#define TAG_BLOCK_GET_ELEMENT(block, index, type) (&((type *)(block)->address)[index]) +typedef unsigned short word; +typedef struct { real scale; real_vector3d forward, left, up; real_point3d position; } real_matrix4x3; +struct tag_block { long count; void *address; }; +struct model_node { short parent_node_index; }; +struct model { struct tag_block nodes; }; +struct biped_definition +{ + struct { struct { long index; } model; } object; + struct { short runtime_pelvis_node_index, runtime_head_node_index; } biped; +}; +struct object_datum +{ + long definition_index; + struct + { + unsigned long flags; + real_vector3d forward; + short type; + word damage_flags; + long parent_object_index; + struct { short size, offset; } node_matrices; + } object; +}; +enum { _object_type_biped = 0, _object_type_vehicle = 1 }; +enum { _object_invisible_bit = 0 }; +enum { _object_dead_bit = 2 }; +enum { _director_perspective_first_person = 0, _director_perspective_third_person = 1 }; + +static real_vector3d const zero_vector = {0, 0, 0}; +static real_vector3d const *global_zero_vector3d = &zero_vector; +static real normalize3d(real_vector3d *v) +{ + real length = sqrtf(v->i * v->i + v->j * v->j + v->k * v->k); + if (length > 0) { v->i /= length; v->j /= length; v->k /= length; } + return length; +} + +static int setting = 1; +static int config_boolean(const char *name) { (void)name; return setting; } +static unsigned long config_changes(void) { static unsigned long changes; return ++changes; } +static int logs; +static void platform_log(const char *format, ...) { (void)format; logs++; } +static char const *tag_get_name(long index) { (void)index; return "characters\\cyborg\\cyborg"; } + +/* two local players, each with a biped (objects 0 and 1, definitions 10 and 11) */ +static short perspective[MAXIMUM_LOCAL_PLAYERS]; +static struct { long unit_index; } players[2] = {{0}, {1}}; +static struct object_datum objects[2]; +static struct biped_definition definitions[2]; +static struct model model; +static struct model_node skeleton[16]; +static real_matrix4x3 node_matrices[2][16]; +static short director_get_perspective(short local) { return perspective[local]; } +static long local_player_get_player_index(short local) { return local < 2 ? local : NONE; } +#define player_get(index) (&players[index]) +static struct object_datum *object_try_and_get(long index) { return index >= 0 && index < 2 ? &objects[index] : NULL; } +#define biped_definition_get(index) (&definitions[(index) - 10]) +static struct model *model_definition_get(long index) { (void)index; return &model; } +static real_matrix4x3 *object_get_node_matrices(long index) { return node_matrices[index]; } +/* the matrices as the last tick left them (object_get_node_matrices': between ticks) */ +static real_matrix4x3 tick_nodes[2][16]; +static void *object_header_block_get(long index, void *reference) { (void)reference; return tick_nodes[index]; } +/* the view */ +static struct { struct { real_point3d position; real_vector3d forward, up; real vertical_field_of_view; } camera; } render; +/* the vertical angle of a view this many degrees across at 16:9 */ +static real vertical_of(double degrees) { return (real)(2.0 * atan(tan(degrees * 3.14159265358979323846 / 360.0) * (9.0 / 16.0))); } +static real dot_product3d(real_vector3d const *a, real_vector3d const *b) { return a->i * b->i + a->j * b->j + a->k * b->k; } +#define REAL_MAX 3.402823466e+38F +static int geometry_ready = 1, geometry_resets; +static boolean first_person_legs_geometry_prepare(long definition, struct model const *model, boolean const *upper, boolean const *lower) +{ (void)definition; (void)model; (void)upper; (void)lower; return geometry_ready; } +static real first_person_legs_geometry_setback(long definition, real_matrix4x3 const *nodes, real_point3d const *pivot, + real cosine, real sine, real_vector3d const *view, real_point3d const *eye, real fov, real minimum) +{ (void)definition; (void)nodes; (void)pivot; (void)cosine; (void)sine; (void)view; (void)eye; (void)fov; return minimum; } +static void first_person_legs_geometry_reset(void) { geometry_resets++; } +#include "under_test.inc" + +/* 0 frame; 1 pelvis; 2 spine, 3 spine1, 4 head, 9 clavicle; 5 l thigh, 6 l calf; 7 r thigh, 8 r calf; 10 a node +on the frame (a gun's) */ +enum { FRAME, PELVIS, SPINE, SPINE1, HEAD, L_THIGH, L_CALF, R_THIGH, R_CALF, CLAVICLE, GUN, NODES }; +static short const parents[NODES] = {NONE, FRAME, PELVIS, SPINE, SPINE1, PELVIS, L_THIGH, PELVIS, R_THIGH, SPINE1, FRAME}; + +static void world(void) +{ + short i, o; + for (i = 0; i < NODES; i++) skeleton[i].parent_node_index = parents[i]; + model.nodes.count = NODES; + model.nodes.address = skeleton; + for (o = 0; o < 2; o++) { + memset(&objects[o], 0, sizeof(objects[o])); + objects[o].definition_index = 10 + o; + objects[o].object.type = _object_type_biped; + objects[o].object.parent_object_index = NONE; + objects[o].object.forward.i = 1; + objects[o].object.node_matrices.size = (short)(NODES * sizeof(real_matrix4x3)); + definitions[o].object.model.index = 5; + definitions[o].biped.runtime_pelvis_node_index = PELVIS; + definitions[o].biped.runtime_head_node_index = HEAD; + for (i = 0; i < NODES; i++) { + memset(&node_matrices[o][i], 0, sizeof(real_matrix4x3)); + node_matrices[o][i].scale = 1; + node_matrices[o][i].forward.i = 1; + node_matrices[o][i].left.j = 1; + node_matrices[o][i].up.k = 1; + node_matrices[o][i].position.x = 10.f * o + i; + node_matrices[o][i].position.z = (real)i; + } + } + memcpy(tick_nodes, node_matrices, sizeof(tick_nodes)); + /* (looking ahead along +x, as the body faces) */ + memset(&render, 0, sizeof(render)); + /* Keep the closure outside the view for the basic pose tests. The + clipping cases below place the eye close to the actual waist. */ + render.camera.position.x = 10.f; + render.camera.forward.i = 1; + render.camera.up.k = 1; + render.camera.vertical_field_of_view = vertical_of(90.0); + perspective[0] = perspective[1] = _director_perspective_first_person; + setting = 1; + logs = 0; + first_person_legs_reset(); +} + +static int same_place(real_matrix4x3 const *a, real_matrix4x3 const *b, real dx) +{ + return fabsf(a->position.x - (b->position.x + dx)) < 1e-5f && fabsf(a->position.y - b->position.y) < 1e-5f && + fabsf(a->position.z - b->position.z) < 1e-5f; +} + +int main(int argc, char **argv) +{ + char const *case_name = argc > 1 ? argv[1] : ""; + real const back = -FIRST_PERSON_LEGS_SET_BACK; + world(); + CASE("off") { + int before; + CHECK(first_person_legs_node_matrices(0, 0), "enable before disabling"); + before = geometry_resets; + setting = 0; + CHECK(!first_person_legs_node_matrices(0, 0), "off, the body is not drawn in its own view"); + CHECK(geometry_resets == before + 1, "disable releases private geometry"); + setting = 1; + CHECK(first_person_legs_node_matrices(0, 0), "enable rebuilds the pose"); + } + CASE("legs") { + real_matrix4x3 const *pose = first_person_legs_node_matrices(0, 0); + short i; + CHECK(pose != NULL, "the player's own biped on foot"); + for (i = 0; i < NODES; i++) { + CHECK(same_place(&pose[i], &node_matrices[0][i], back), "node %d has its original position", i); + CHECK(pose[i].scale == node_matrices[0][i].scale, "node %d keeps its scale", i); + } + CHECK(!first_person_legs_models[0].omitted[SPINE] && first_person_legs_models[0].omitted[HEAD], + "retain the torso, omit the head"); + CHECK(first_person_legs_models[0].lower[L_THIGH] && !first_person_legs_models[0].lower[PELVIS] && + !first_person_legs_models[0].lower[SPINE], "surface clearance distinguishes legs from torso"); + } + CASE("geometry-failure") { + geometry_ready = 0; + CHECK(!first_person_legs_node_matrices(0, 0), "unsafe/incomplete geometry hides the optional body"); + } + CASE("geometry-reset") { + int before = geometry_resets; + first_person_legs_reset(); + CHECK(geometry_resets == before + 1, "map reset releases the private geometry"); + } + CASE("setback") { + real_matrix4x3 const *pose; + /* (looking 60 degrees down, straight down, straight up: the view's heading, level, each time) */ + real const views[3][6] = {{0.5f, 0, -0.8660254f, 0.8660254f, 0, 0.5f}, {0, 0, -1, 1, 0, 0}, {0, 0, 1, -1, 0, 0}}; + short v; + for (v = 0; v < 3; v++) { + render.camera.forward.i = views[v][0]; render.camera.forward.j = views[v][1]; render.camera.forward.k = views[v][2]; + render.camera.up.i = views[v][3]; render.camera.up.j = views[v][4]; render.camera.up.k = views[v][5]; + pose = first_person_legs_node_matrices(0, 0); + CHECK(pose && same_place(&pose[L_CALF], &node_matrices[0][L_CALF], back), "the whole set-back, level (view %d)", v); + } + /* (the first node's axis up the spine, as a pelvis's is: the body's facing is the object's) */ + node_matrices[0][FRAME].forward.i = 0; node_matrices[0][FRAME].forward.k = 1; + node_matrices[0][FRAME].up.i = -1; node_matrices[0][FRAME].up.k = 0; + memcpy(tick_nodes[0], node_matrices[0], sizeof(tick_nodes[0])); + pose = first_person_legs_node_matrices(0, 0); + CHECK(pose && same_place(&pose[L_CALF], &node_matrices[0][L_CALF], back), "no turn: the body faces the view"); + } + CASE("turn") { + /* (the body faces +x, the view +y: turned about the pelvis, set back along -y) */ + real_matrix4x3 const *pose; + /* (the first node's axis up the spine, as a pelvis's is) */ + node_matrices[0][FRAME].forward.i = 0; node_matrices[0][FRAME].forward.k = 1; + node_matrices[0][FRAME].up.i = -1; node_matrices[0][FRAME].up.k = 0; + memcpy(tick_nodes[0], node_matrices[0], sizeof(tick_nodes[0])); + render.camera.forward.i = 0; render.camera.forward.j = 1; + render.camera.position.y = 10.f; + pose = first_person_legs_node_matrices(0, 0); + CHECK(pose != NULL, "drawn"); + CHECK(fabsf(pose[L_CALF].position.x - 1.f) < 1e-5f && + fabsf(pose[L_CALF].position.y - (5.f - FIRST_PERSON_LEGS_SET_BACK)) < 1e-5f && + fabsf(pose[L_CALF].position.z - 6.f) < 1e-5f, + "a calf 5 ahead of the pelvis turns about the hips, set back from the view (%g %g)", + pose[L_CALF].position.x, pose[L_CALF].position.y); + CHECK(fabsf(pose[L_CALF].forward.i) < 1e-5f && fabsf(pose[L_CALF].forward.j - 1.f) < 1e-5f, + "its axes turned with it"); + CHECK(fabsf(pose[L_CALF].up.k - 1.f) < 1e-5f, "about the vertical"); + /* (a jump's half turn: the body still faces +x, the view -x) */ + render.camera.forward.i = -1; render.camera.forward.j = 0; + render.camera.position.x = -10.f; + pose = first_person_legs_node_matrices(0, 0); + CHECK(pose && fabsf(pose[L_CALF].position.x - (-4.f + FIRST_PERSON_LEGS_SET_BACK)) < 1e-5f, + "half turned, still ahead of the view, not behind it (%g)", pose ? pose[L_CALF].position.x : 0); + } + CASE("pivot") { + real const headings[3][2] = {{0.f, 1.f}, {-1.f, 0.f}, {0.f, -1.f}}; + short root, turn; + /* Both a separate offset root and the stock layout, with the pelvis at node zero. */ + for (root = 0; root < 2; root++) { + short pelvis = root ? FRAME : PELVIS; + world(); + definitions[0].biped.runtime_pelvis_node_index = pelvis; + skeleton[SPINE].parent_node_index = pelvis; + skeleton[L_THIGH].parent_node_index = pelvis; + skeleton[R_THIGH].parent_node_index = pelvis; + node_matrices[0][pelvis].position.x = 0.1f; + node_matrices[0][pelvis].position.y = 0.2f; + memcpy(tick_nodes, node_matrices, sizeof(tick_nodes)); + for (turn = 0; turn < 3; turn++) { + real_matrix4x3 const *pose; + real_point3d expected = node_matrices[0][pelvis].position; + render.camera.forward.i = headings[turn][0]; + render.camera.forward.j = headings[turn][1]; + render.camera.position.x = expected.x + headings[turn][0] * 10.f; + render.camera.position.y = expected.y + headings[turn][1] * 10.f; + expected.x -= headings[turn][0] * FIRST_PERSON_LEGS_SET_BACK; + expected.y -= headings[turn][1] * FIRST_PERSON_LEGS_SET_BACK; + pose = first_person_legs_node_matrices(0, 0); + CHECK(pose && fabsf(pose[pelvis].position.x - expected.x) < 1e-5f && + fabsf(pose[pelvis].position.y - expected.y) < 1e-5f && + fabsf(pose[pelvis].position.z - expected.z) < 1e-5f, + "pelvis %d stays anchored when the view turns %d", pelvis, turn); + CHECK(memcmp(node_matrices, tick_nodes, sizeof(tick_nodes)) == 0, + "the world pose remains unchanged"); + } + } + } + CASE("interpolated") { + /* (between ticks the drawn pose has turned 30 degrees on from the tick's: the body's facing goes with it) */ + real_matrix4x3 const *pose; + real const c = 0.8660254f, s = 0.5f; + short i; + for (i = 0; i < NODES; i++) { + real x = node_matrices[0][i].position.x - 1.f, y = node_matrices[0][i].position.y; + node_matrices[0][i].position.x = 1.3f + c * x - s * y; + node_matrices[0][i].position.y = 0.2f + s * x + c * y; + node_matrices[0][i].forward.i = c; node_matrices[0][i].forward.j = s; + node_matrices[0][i].left.i = -s; node_matrices[0][i].left.j = c; + } + pose = first_person_legs_node_matrices(0, 0); + CHECK(pose && fabsf(pose[L_CALF].forward.i - 1.f) < 1e-5f && fabsf(pose[L_CALF].forward.j) < 1e-5f, + "the drawn body faces the view, whatever the tick's"); + CHECK(fabsf(pose[PELVIS].position.x - (1.3f - FIRST_PERSON_LEGS_SET_BACK)) < 1e-5f && + fabsf(pose[PELVIS].position.y - 0.2f) < 1e-5f && + fabsf(pose[L_CALF].position.x - (6.3f - FIRST_PERSON_LEGS_SET_BACK)) < 1e-5f && + fabsf(pose[L_CALF].position.y - 0.2f) < 1e-5f, + "the interpolated pelvis anchors the turned pose, not the tick's pelvis or the root"); + } + CASE("fov-shape") { + real_matrix4x3 baseline[NODES]; + real const fovs[] = {20.f, 90.f, 110.f, 120.f, 150.f}; + short f, i; + render.camera.position.x = 0.3f; + render.camera.position.y = -0.2f; + render.camera.position.z = 2.7f; + render.camera.vertical_field_of_view = vertical_of(20.f); + memcpy(baseline, first_person_legs_node_matrices(0, 0), sizeof(baseline)); + for (f = 0; f < 5; f++) { + real_matrix4x3 const *pose; + real dx, dy; + render.camera.vertical_field_of_view = vertical_of(fovs[f]); + pose = first_person_legs_node_matrices(0, 0); + CHECK(pose != NULL, "the legs remain drawn"); + dx = pose[PELVIS].position.x - baseline[PELVIS].position.x; + dy = pose[PELVIS].position.y - baseline[PELVIS].position.y; + for (i = 0; i < NODES; i++) { + CHECK(fabsf(pose[i].position.x - baseline[i].position.x - dx) < 1e-4f && + fabsf(pose[i].position.y - baseline[i].position.y - dy) < 1e-4f && + pose[i].position.z == baseline[i].position.z && + pose[i].scale == baseline[i].scale, + "FOV %g translates the whole pose without deforming node %d", fovs[f], i); + } + } + } + CASE("pitch-stable") { + real const views[][6] = { + {1, 0, 0, 0, 0, 1}, {0.5f, 0, -0.8660254f, 0.8660254f, 0, 0.5f}, + {0, 0, -1, 1, 0, 0}, {0, 0, 1, -1, 0, 0} + }; + real_matrix4x3 baseline[NODES]; + short v; + render.camera.position.x = 0.3f; + render.camera.position.y = -0.2f; + render.camera.position.z = 2.7f; + render.camera.vertical_field_of_view = vertical_of(150.f); + memcpy(baseline, first_person_legs_node_matrices(0, 0), sizeof(baseline)); + for (v = 0; v < 4; v++) { + real_matrix4x3 const *pose; + render.camera.forward.i = views[v][0]; render.camera.forward.j = views[v][1]; + render.camera.forward.k = views[v][2]; render.camera.up.i = views[v][3]; + render.camera.up.j = views[v][4]; render.camera.up.k = views[v][5]; + pose = first_person_legs_node_matrices(0, 0); + CHECK(pose && memcmp(pose, baseline, sizeof(baseline)) == 0, + "looking up/down does not move or deform the body (view %d)", v); + } + } + CASE("who") { + CHECK(!first_person_legs_node_matrices(0, 1), "another player's body"); + CHECK(!first_person_legs_node_matrices(-1, 0) && !first_person_legs_node_matrices(MAXIMUM_LOCAL_PLAYERS, 0), + "no such local player"); + CHECK(!first_person_legs_node_matrices(2, 0), "a local player without a player"); + perspective[0] = _director_perspective_third_person; + CHECK(!first_person_legs_node_matrices(0, 0), "third person"); + perspective[0] = _director_perspective_first_person; + objects[0].object.damage_flags = FLAG(_object_dead_bit); + CHECK(!first_person_legs_node_matrices(0, 0), "dead"); + objects[0].object.damage_flags = 0; + objects[0].object.flags = FLAG(_object_invisible_bit); + CHECK(!first_person_legs_node_matrices(0, 0), "hidden"); + objects[0].object.flags = 0; + objects[0].object.parent_object_index = 1; + CHECK(!first_person_legs_node_matrices(0, 0), "riding something"); + objects[0].object.parent_object_index = NONE; + objects[0].object.type = _object_type_vehicle; + CHECK(!first_person_legs_node_matrices(0, 0), "not a biped"); + objects[0].object.type = _object_type_biped; + objects[0].object.node_matrices.size = (short)((NODES - 1) * sizeof(real_matrix4x3)); + CHECK(!first_person_legs_node_matrices(0, 0), "fewer matrices than the model's nodes"); + objects[0].object.node_matrices.size = (short)(NODES * sizeof(real_matrix4x3)); + CHECK(first_person_legs_node_matrices(0, 0) != NULL, "and drawn again"); + } + CASE("unusable") { + definitions[0].biped.runtime_pelvis_node_index = NONE; + CHECK(!first_person_legs_node_matrices(0, 0) && !first_person_legs_node_matrices(0, 0), "no pelvis"); + CHECK(logs == 1, "said once (%d)", logs); + definitions[1].biped.runtime_head_node_index = L_CALF; /* (a head not below the spine: under a leg) */ + skeleton[L_THIGH].parent_node_index = FRAME; + CHECK(!first_person_legs_node_matrices(1, 1), "a head not below the pelvis"); + CHECK(logs == 2, "said once more (%d)", logs); + world(); + skeleton[L_THIGH].parent_node_index = SPINE; + skeleton[R_THIGH].parent_node_index = SPINE; + CHECK(!first_person_legs_node_matrices(0, 0), "no legs below the pelvis but the spine"); + CHECK(logs == 1, "said (%d)", logs); + } + CASE("loops") { + skeleton[SPINE].parent_node_index = SPINE1; /* (spine and spine1 each other's parent) */ + CHECK(!first_person_legs_node_matrices(0, 0), "a loop in a map's parents ends"); + world(); + skeleton[PELVIS].parent_node_index = 40; /* (a parent past the nodes) */ + CHECK(first_person_legs_node_matrices(0, 0) != NULL, "a parent past the nodes is no node"); + } + CASE("split") { + real_matrix4x3 const *first = first_person_legs_node_matrices(0, 0); + real_matrix4x3 const *second; + render.camera.position.x = 20.f; + second = first_person_legs_node_matrices(1, 1); + CHECK(first && second && first != second, "each view's own pose"); + CHECK(same_place(&first[L_CALF], &node_matrices[0][L_CALF], back), "the first view keeps its body's pose"); + CHECK(same_place(&second[L_CALF], &node_matrices[1][L_CALF], back), "the second its own"); + } + CASE("reset") { + definitions[0].biped.runtime_pelvis_node_index = NONE; + CHECK(!first_person_legs_node_matrices(0, 0), "a map whose biped has no legs"); + definitions[0].biped.runtime_pelvis_node_index = PELVIS; /* (the next map's, at the same index) */ + CHECK(!first_person_legs_node_matrices(0, 0), "the same map: as found"); + first_person_legs_reset(); + CHECK(first_person_legs_node_matrices(0, 0) != NULL, "a new map: found again"); + } + return 0; +} diff --git a/tools/harness/tests/first_person_legs_geometry.c b/tools/harness/tests/first_person_legs_geometry.c new file mode 100644 index 0000000000..1ee42f325e --- /dev/null +++ b/tools/harness/tests/first_person_legs_geometry.c @@ -0,0 +1,211 @@ +#include "harness.h" +#include +#define MAX(a,b) ((a) > (b) ? (a) : (b)) +#define REAL_MAX 3.402823466e+38F +#define _pi 3.14159265358979323846f +#define MAXIMUM_GEOMETRIES_PER_MODEL 256 +#define MAXIMUM_PARTS_PER_MODEL_GEOMETRY 32 +#define TAG_BLOCK_GET_ELEMENT(b,i,t) (&((t *)(b)->address)[i]) +#define csmemset memset +#define D3DLOCK_READONLY 1 +typedef unsigned short word; +typedef byte BYTE; +typedef struct { real scale; real_vector3d forward, left, up; real_point3d position; } real_matrix4x3; +struct tag_block { long count; void *address; void *definition; }; +struct model_node { real_matrix4x3 runtime_default_inverse_matrix; }; +struct model { struct tag_block nodes, geometries; }; +struct vertex_buffer { short type; word pad; long count, offset; void *base_address, *hardware_format; }; +struct triangle_buffer { short type; word pad; long count; void *base_address, *hardware_format; }; +struct model_vertex_compressed { + real_point3d position; unsigned long normal, binormal, tangent; + short uv[2]; byte nodes[2]; short node_weight; +}; +enum { _triangle_buffer_type_triangles, _triangle_buffer_type_precompiled_strip }; +enum { _rasterizer_vertex_type_model_compressed = 5 }; +static real_matrix4x3 identity = {1, {1,0,0}, {0,1,0}, {0,0,1}, {0,0,0}}; +static real_point3d origin; +static void matrix4x3_transform_point(real_matrix4x3 const *m, real_point3d const *p, real_point3d *o) +{ + o->x = m->position.x + m->scale * (m->forward.i*p->x + m->left.i*p->y + m->up.i*p->z); + o->y = m->position.y + m->scale * (m->forward.j*p->x + m->left.j*p->y + m->up.j*p->z); + o->z = m->position.z + m->scale * (m->forward.k*p->x + m->left.k*p->y + m->up.k*p->z); +} +static int created, deleted, fail_create, fail_lock, locks; +static short ce_count, mcc_count; +static byte palette[4] = {2,0,1,3}; +static struct vertex_buffer const *palette_key; +short custom_edition_part_palette(struct vertex_buffer const *v, byte const **p) +{ CHECK(v == palette_key, "original vertex descriptor required"); *p = ce_count ? palette : NULL; return ce_count; } +short mcc_cache_part_palette(void const *v, byte const **p) +{ CHECK(v == palette_key, "original MCC descriptor required"); *p = mcc_count ? palette : NULL; return mcc_count; } +void platform_log(char const *s, ...) { (void)s; } +static void IDirect3DVertexBuffer8_Lock(void *b, long offset, long size, BYTE **out, int flags) +{ (void)offset; (void)size; CHECK(flags == D3DLOCK_READONLY, "read-only source"); *out = fail_lock ? NULL : b; locks++; } +#define IDirect3DIndexBuffer8_Lock IDirect3DVertexBuffer8_Lock +static void IDirect3DVertexBuffer8_Unlock(void *b) { (void)b; locks--; } +#define IDirect3DIndexBuffer8_Unlock IDirect3DVertexBuffer8_Unlock +static boolean rasterizer_triangle_buffer_new(struct triangle_buffer *b, short type, long n, void const *p) +{ + if (fail_create) return FALSE; + b->type = type; b->count = n; b->hardware_format = (void *)p; created++; + return TRUE; +} +static void rasterizer_triangle_buffer_delete(struct triangle_buffer *b) +{ if (b->hardware_format) deleted++; memset(b, 0, sizeof(*b)); } +#include "under_test.inc" + +static struct model model; +static struct model_node bones[4]; +static real_matrix4x3 pose[4]; +static struct first_person_legs_geometry geometry; +static struct first_person_legs_source_part part; +static struct model_vertex_compressed vertices[7], original[7]; +static word indices[9] = {0,1,2, 2,3,4, 4,5,6}; +/* 0 torso, 1 thigh, 2 head, 3 second thigh. The head triangle +shares a thigh edge, while the intact torso triangle has no cut edge. */ +static boolean upper[4] = {FALSE,FALSE,TRUE,FALSE}; +static boolean lower[4] = {FALSE,TRUE,FALSE,TRUE}; +static void world(void) +{ + int i; + for (i=0; i<4; i++) bones[i].runtime_default_inverse_matrix = pose[i] = identity; + for (i=0; i<7; i++) { + vertices[i].position.x = 0.2f + i * 0.04f; + vertices[i].position.y = (i % 2) * 0.1f; + vertices[i].position.z = 0.4f + i * 0.02f; + vertices[i].nodes[0] = i < 2 ? 0 : i < 6 ? 3 : 6; + vertices[i].nodes[1] = 255; + vertices[i].node_weight = 32767; + } + memcpy(original, vertices, sizeof(vertices)); + model.nodes.count=4; model.nodes.address=bones; + model.geometries.count=1; model.geometries.address=&geometry; + geometry.parts.count=1; geometry.parts.address=∂ + part.vertex_buffer.type=5; part.vertex_buffer.count=7; part.vertex_buffer.hardware_format=vertices; + part.triangle_buffer.type=0; part.triangle_buffer.count=3; part.triangle_buffer.hardware_format=indices; + palette_key=&part.vertex_buffer; +} +static struct triangle_buffer const *get(void) +{ return first_person_legs_geometry_get(10,&model,upper,lower,&part.vertex_buffer,&part.triangle_buffer); } +static int close_real(real a, real b) { return fabs(a-b) < 0.0001f; } + +int main(int argc, char **argv) +{ + char const *case_name = argc > 1 ? argv[1] : ""; + world(); + CASE("mesh") { + struct triangle_buffer const *out=get(); + CHECK(out && out->count==2, "head triangles removed, torso retained"); + CHECK(memcmp(first_person_legs_parts[0].indices,indices,6*sizeof(word))==0,"intact triangles"); + CHECK(memcmp(vertices,original,sizeof(vertices))==0,"vertices never rewritten"); + CHECK(out!=&part.triangle_buffer && part.triangle_buffer.count==3,"private indices"); + CHECK(get()==out && created==1,"stable buffer for queued shield draws"); + } + CASE("strip") { + boolean keep[7]={1,1,1,1,1,1,1}; + word strip[8]={0,1,2,2,3,4,5,6}, output[18]; + word expected[12]={0,1,2, 3,2,4, 3,4,5, 5,4,6}; + CHECK(first_person_legs_select(strip,6,1,keep,7,output)==4,"degenerate strip"); + CHECK(!memcmp(output,expected,sizeof(expected)),"strip winding survives degenerates"); + } + CASE("weights") { + struct model_vertex_compressed v=vertices[2]; + CHECK(first_person_legs_vertex_kept(&v,4,upper,0,NULL),"unused invalid node ignored"); + v.nodes[1]=6; v.node_weight=32766; + CHECK(!first_person_legs_vertex_kept(&v,4,upper,0,NULL),"even small head influence removed"); + v.node_weight=0; v.nodes[0]=255; v.nodes[1]=3; + CHECK(first_person_legs_vertex_kept(&v,4,upper,0,NULL),"second influence alone"); + v.node_weight=-1; + CHECK(!first_person_legs_vertex_kept(&v,4,upper,0,NULL),"invalid signed weight"); + } + CASE("palette") { + struct model_vertex_compressed v=vertices[2]; + v.nodes[0]=0; + CHECK(!first_person_legs_vertex_kept(&v,4,upper,4,palette),"palette maps head"); + v.nodes[0]=3; + CHECK(first_person_legs_vertex_kept(&v,4,upper,4,palette),"palette maps torso"); + v.nodes[0]=12; + CHECK(!first_person_legs_vertex_kept(&v,4,upper,4,palette),"palette bounds"); + ce_count=4; CHECK(get()!=NULL,"CE palette supported"); + first_person_legs_geometry_reset(); ce_count=0; mcc_count=4; + CHECK(get()!=NULL,"MCC palette supported"); + } + CASE("malformed") { + part.triangle_buffer.count=0; + CHECK(!get() && !first_person_legs_part_count,"empty part does not poison cache"); + part.triangle_buffer.count=3; + indices[8]=7; + CHECK(!first_person_legs_geometry_prepare(10,&model,upper,lower),"invalid triangle hides whole local body"); + CHECK(!first_person_legs_bytes && !locks,"failed buffer cleanup"); + first_person_legs_geometry_reset(); indices[8]=6; part.vertex_buffer.type=4; + CHECK(!first_person_legs_geometry_prepare(10,&model,upper,lower),"unsupported format"); + first_person_legs_geometry_reset(); part.vertex_buffer.type=5; model.nodes.count=65540; + CHECK(!first_person_legs_geometry_prepare(10,&model,upper,lower),"node count cannot wrap"); + } + CASE("failure") { + fail_create=1; + CHECK(!first_person_legs_geometry_prepare(10,&model,upper,lower),"allocation failure hides body"); + CHECK(!first_person_legs_bytes && !locks,"no retained allocation"); + first_person_legs_geometry_reset(); fail_create=0; fail_lock=1; + CHECK(!first_person_legs_geometry_prepare(10,&model,upper,lower),"failed lock"); + first_person_legs_geometry_reset(); fail_lock=0; first_person_legs_bytes=FIRST_PERSON_LEGS_BYTES; + CHECK(!get(),"budget bounded"); + } + CASE("lifecycle") { + CHECK(first_person_legs_geometry_prepare(10,&model,upper,lower),"prepare"); + CHECK(first_person_legs_geometry_prepare(10,&model,upper,lower) && created==1,"cache survives frames"); + first_person_legs_geometry_reset(); + CHECK(deleted==created && !first_person_legs_bytes && !first_person_legs_part_count,"reset releases"); + CHECK(first_person_legs_geometry_prepare(11,&model,upper,lower) && created==2,"new map"); + } + CASE("boundary") { + CHECK(get()!=NULL,"mesh"); + /* Torso vertices 0,1 plus leg vertex 4 at the head cut. Vertex + 5 is only in the removed triangle and must not inflate clearance. */ + CHECK(first_person_legs_parts[0].boundary_count==3,"all non-leg and cut-edge vertices"); + } + CASE("clearance") { + int f, movement; + real fovs[]={20,70,90,110,120,150}; + real_vector3d view={0,1,0}; + real_point3d eye={0,0,1}, pivot={0,0,0}; + vertices[0].nodes[1]=9; vertices[0].node_weight=12000; + bones[0].runtime_default_inverse_matrix.position.z=-0.2f; + CHECK(get()!=NULL,"mesh"); + for(movement=0;movement<6;movement++) for(f=0;f<6;f++) { + int i; + real angle=fovs[f]*_pi/180.f; + real offset, expected=0.16f; + pose[0].position.z=movement*0.13f; + pose[1].position.z=movement*-0.07f; + pose[3].position.z=movement*-0.3f; + eye.z=movement&1 ? 0.65f : 1.f; + offset=first_person_legs_geometry_setback(10,pose,&pivot,0,1,&view,&eye,angle,0.16f); + /* Independent surface reconstruction from original vertices, + inverse bind and animated bones. Test both above/below eye. */ + for(i=0;i<5;i++) if(i<2 || i==4) { + real_point3d a,b,p; + real w=vertices[i].node_weight/32767.f, behind, needed; + int n=vertices[i].nodes[0]/3; + int n2=w==1.f ? 0 : vertices[i].nodes[1]/3; + matrix4x3_transform_point(&bones[n].runtime_default_inverse_matrix,&vertices[i].position,&a); + matrix4x3_transform_point(&pose[n],&a,&p); a=p; + matrix4x3_transform_point(&bones[n2].runtime_default_inverse_matrix,&vertices[i].position,&b); + matrix4x3_transform_point(&pose[n2],&b,&p); b=p; + p.x=a.x*w+b.x*(1-w); p.z=a.z*w+b.z*(1-w); + behind=eye.y-(pivot.y+(p.x-pivot.x)-offset); + needed=fabs(eye.z-p.z)*tan(angle/2)+0.03f/cos(angle/2); + CHECK(behind+0.00001f>=needed,"surface enters view: movement %d FOV %.0f vertex %d",movement,fovs[f],i); + expected=MAX(expected,needed+p.x); + } + CHECK(close_real(offset,expected),"no unnecessary retreat beyond animated surface"); + } + } + CASE("invalid-view") { + real_vector3d view={1,0,0}; + CHECK(get()!=NULL,"mesh"); + CHECK(first_person_legs_geometry_setback(10,pose,&origin,1,0,&view,&origin,0,0.16f)==REAL_MAX,"invalid FOV"); + } + first_person_legs_geometry_reset(); + return 0; +} diff --git a/tools/harness/tests/fragment_source_cache.c b/tools/harness/tests/fragment_source_cache.c new file mode 100644 index 0000000000..0e07720038 --- /dev/null +++ b/tools/harness/tests/fragment_source_cache.c @@ -0,0 +1,85 @@ +#include "harness.h" +typedef unsigned long DWORD; +typedef unsigned int GLuint; +typedef int BOOL; +#define GL_FRAGMENT_SHADER 1 +struct nv2a_pixel_shader_key { DWORD source, unused; }; +static struct { const char *dump_shaders; } debug_settings; +static const char *sources[] = {"shader A", "shader B", "failed shader", "shader A extra"}; +static unsigned int compiles, translations, freed; +static int fail_allocation; +static char *nv2a_pixel_shader_to_glsl(const struct nv2a_pixel_shader_key *key) +{ + char *text = malloc(strlen(sources[key->source]) + 1); + CHECK(text != NULL, "source allocation"); + strcpy(text, sources[key->source]); translations++; + return text; +} +static GLuint xgpu_compile_shader(int type, const char *source, const char *what) +{ + CHECK(type == GL_FRAGMENT_SHADER && !strcmp(what, "pixel"), "changed compile contract"); + compiles++; + return !strcmp(source, sources[2]) ? 0 : compiles; +} +static void *cache_malloc(size_t size) { return fail_allocation ? NULL : malloc(size); } +static void cache_free(void *memory) { freed++; free(memory); } +static void *device_record_new(size_t size) { return cache_malloc(size); } +#define malloc cache_malloc +#define free cache_free +#include "under_test.inc" +#undef malloc +#undef free + +int main(int argc, char **argv) +{ + struct nv2a_pixel_shader_key a = {0, 1}, b = {0, 2}; + GLuint first, second; + unsigned int i, count = 0; + CHECK(argc == 2, "case required"); + if (!strcmp(argv[1], "distinct")) b.source = 1; + if (!strcmp(argv[1], "prefix")) b.source = 3; + if (!strcmp(argv[1], "failure")) a.source = b.source = 2; + if (!strcmp(argv[1], "allocation")) fail_allocation = 1; + first = fragment_shader_get(&a); + second = fragment_shader_get(&b); + if (first) + CHECK(first < shader_hashes_size && shader_hashes[first] == source_hash(sources[a.source]), + "shared fragment missing from program-binary cache hash table"); + if (second) + CHECK(second < shader_hashes_size && shader_hashes[second] == source_hash(sources[b.source]), + "second fragment has the wrong program-binary cache hash"); + if (!strcmp(argv[1], "distinct") || !strcmp(argv[1], "prefix")) + CHECK(first != second && compiles == 2, "different GLSL merged on hash/prefix"); + else if (!strcmp(argv[1], "allocation")) + CHECK(first && second && compiles == 2 && freed == 2, "allocation fallback lost shader/source"); + else + CHECK(first == second && compiles == 1 && freed == 1, "identical source compiled again"); + if (!strcmp(argv[1], "failure")) CHECK(!first && !second, "failed shader returned success"); + CHECK(translations == 2, "full keys incorrectly collapsed before translation"); + CHECK(fragment_shader_get(&a) == first && translations == 2, "recent key regenerated source"); + if (!strcmp(argv[1], "recent")) + { + for (i = 3; i < 20; i++) + { + b.unused = i; + CHECK(fragment_shader_get(&b) == first, "many state keys changed shader"); + } + CHECK(compiles == 1, "recent eviction discarded shared shader"); + CHECK(fragment_shader_get(&a) == first && translations == 19, "full-key bucket missed after recent eviction"); + } + /* Account for owned sources and aliases independently; maps do not own either. */ + for (i = 0; i < FRAGMENT_BUCKETS; i++) + { + struct fragment_source_entry *source = fragment_source_buckets[i]; + struct fragment_entry *key = fragment_buckets[i]; + while (source) + { + struct fragment_source_entry *next = source->next; + count++; free(source->source); free(source); source = next; + } + while (key) { struct fragment_entry *next = key->next; free(key); key = next; } + } + CHECK(freed + count == translations, "source leaked or owned more than once"); + free(shader_hashes); + return 0; +} diff --git a/tools/harness/tests/game_modes.c b/tools/harness/tests/game_modes.c index 8dbe4fde00..1ba32844ea 100644 --- a/tools/harness/tests/game_modes.c +++ b/tools/harness/tests/game_modes.c @@ -71,7 +71,7 @@ int main(int argc,char **argv) /* (a gametype saved before OpenCE's: every byte 0) */ memset(&options,0,sizeof(options)); game_modes_options_sanitize(&options); - CHECK(options.mode==_game_mode_none&&!options.hardcore,"no mode"); + CHECK(options.mode==_game_mode_none&&!options.hardcore&&!options.force_team_spawns,"no mode or forced spawns"); CHECK(options.infection_initial_zombies==1&&options.infection_zombie_speed==150&& options.infection_skull_damage==200&&options.infection_respawn_time==5,"Infection's defaults"); CHECK(options.infection_countdown==0,"a countdown of 0 is one"); @@ -120,6 +120,7 @@ int main(int argc,char **argv) CHECK(options.infection_initial_zombies==1&&options.infection_zombie_speed==150&&options.infection_skull_damage==200&& options.infection_respawn_time==5&&options.infection_countdown==10,"out of range: the defaults"); CHECK(options.gun_game_order==_gun_game_order_strongest_first,"an unknown order"); + CHECK(options.force_team_spawns==TRUE,"forced spawns normalized"); for(int index=0;index<(int)sizeof(options.reserved);index++) CHECK(options.reserved[index]==0,"reserved cleared"); } else CASE("sanitize_keeps") { memset(&options,0,sizeof(options)); diff --git a/tools/harness/tests/game_time_sync.c b/tools/harness/tests/game_time_sync.c new file mode 100644 index 0000000000..3470220e41 --- /dev/null +++ b/tools/harness/tests/game_time_sync.c @@ -0,0 +1,444 @@ +/* The real frame clock and reliable host-update handler, with tick callbacks + * recorded instead of a loaded world. No map or transport assets are needed. */ +#include "harness.h" +#include + +/* The production clock's three booleans are bytes on the supported ILP32 ABI. */ +#define boolean byte +#undef match_assert +#define match_assert(file, line, condition) CHECK(condition, "engine assertion") +#define MIN(a, b) ((a) < (b) ? (a) : (b)) +#define network_event(...) ((void)0) +#define profile_scope(section, code) do { code } while (0); +#include "config.inc" + +struct network_game_client { unsigned long next_update_number; boolean started; }; +struct message_server_game_update { unsigned long update_number; long game_time; }; +struct scenario { short type; }; +static struct scenario scenario_storage, *global_scenario; +static struct network_game_client client; +static boolean network_game_client_late_join_clock_pending; +static struct game_time_globals_struct clock_storage, *game_time_globals = &clock_storage; +static short connection; +static boolean mcc; +static real remote_speed; +static long maximum_server_time, first_tick, previous_tick; +static int ticks, snapshots, sends, frames, speed_frames; +static int allocations, client_starts, server_starts; +static real frame_delta; + +static short game_connection(void) { return connection; } +static boolean network_game_distributed_client(void) { return connection == _game_connection_network_client; } +static struct network_game_client *global_network_game_client_get(void) { return &client; } +static boolean network_game_client_server_has_started_game(struct network_game_client *value) { return value->started; } +static void mcc_game_speed_frame(void) { speed_frames++; } +static real mcc_game_speed_client(real original) { return mcc ? remote_speed : original; } +static boolean halo_fixed_step(void) { return FALSE; } +static void update_client_local_ticks(long count) { maximum_server_time += count; } +static void *global_network_game_server_get(void) { return NULL; } +static void network_game_server_update_ticks(void *server, short count) { (void)server; maximum_server_time += count; } +static long update_client_get_maximum_possible_server_time(void) { return maximum_server_time; } +static void update_client_start(void) { client_starts++; } +static void update_server_start(void) { server_starts++; } +static void *game_state_malloc(char const *name, void *unused, unsigned long size) +{ + (void)unused; + CHECK(!strcmp(name, "game time globals") && size == 32, "saved clock allocation changed"); + allocations++; + return &clock_storage; +} + +static void game_tick(void) +{ + long now = game_time_globals->local_time; + CHECK(!ticks || now == previous_tick + 1, "a simulation tick was skipped or repeated"); + CHECK(ticks == snapshots && sends == (global_scenario ? 0 : ticks), "tick callback ordering changed"); + if (!ticks) first_tick = now; + previous_tick = now; + ticks++; +} + +static void render_interpolation_tick(void) +{ + CHECK(ticks == snapshots + 1 && game_time_globals->local_time == previous_tick, + "snapshot did not follow the same simulation tick"); + snapshots++; +} + +static void network_distributed_tick(void) +{ + CHECK(snapshots == sends + 1 && game_time_globals->local_time == previous_tick + 1, + "state send did not follow clock advancement and snapshot"); + sends++; +} + +static void render_interpolation_frame_begin(void) { } +static void render_interpolation_frame_end(void) { } +static void game_frame(real delta) { frames++; frame_delta = delta; } + +long game_time_get(void); +boolean game_time_menu_scene(void); +#include "under_test.inc" + +static void reset(long time) +{ + /* A real lifecycle reset, so cases do not borrow the prior target. */ + game_time_dispose_from_old_map(); + game_time_initialize_for_new_map(); + game_time_globals->active = TRUE; + game_time_globals->local_time = time; + game_time_globals->server_time = time; + game_time_globals->speed = 1.0f; + game_time_globals->leftover_dt = .005f; + connection = _game_connection_network_client; + memset(&client, 0, sizeof(client)); + client.started = TRUE; + network_game_client_late_join_clock_pending = FALSE; + global_scenario = NULL; + mcc = FALSE; + remote_speed = 1.0f; + maximum_server_time = time; + first_tick = previous_tick = NONE; + ticks = snapshots = sends = frames = speed_frames = 0; + frame_delta = 0.f; +} + +static void host_update(long time) +{ + struct message_server_game_update update; + update.update_number = client.next_update_number; + update.game_time = time; + CHECK(network_game_client_handle_game_update(&client, &update), "valid handler result"); +} + +static void frame(real dt) +{ + long before = game_time_get(); + int before_ticks = ticks; + game_time_update(dt); + CHECK(game_time_get() - before == ticks - before_ticks, "clock jumped without executing the simulation"); + CHECK(game_time_globals->server_time == game_time_get(), "server and local clocks separated"); + CHECK(ticks - before_ticks <= TICKS_PER_SECOND, "frame exceeded the existing tick work limit"); +} + +static void convergence(long lag, boolean scaled) +{ + long host_time = 1000; + int index; + reset(host_time - lag); + mcc = scaled; + remote_speed = scaled ? .5f : 1.0f; + for (index = 0; index < 300; index++) + { + int before = ticks; + if (index % TICKS_PER_SECOND == 0) host_update(host_time); + frame(1.f / (remote_speed * TICKS_PER_SECOND)); + CHECK(ticks - before >= 1 && ticks - before <= 2, "catch-up exceeded twice the normal tick rate"); + host_time++; + CHECK(game_time_get() <= host_time, "catch-up advanced ahead of the known host"); + } + CHECK(host_time - game_time_get() <= 2, "small clock lag remains after ten host updates: %ld", host_time-game_time_get()); + CHECK(ticks > 300 && ticks <= 300 + lag, "missing or excessive actual catch-up ticks"); + CHECK(sends == ticks && snapshots == ticks && previous_tick-first_tick+1 == ticks, + "catch-up omitted simulation, rendering or network publication"); +} + +static void lifecycle(char const *which) +{ + reset(1000); + host_update(1008); + if (!strcmp(which, "new-map")) + { + game_time_globals->initialized = FALSE; + game_time_initialize_for_new_map(); + } + else if (!strcmp(which, "dispose")) game_time_dispose_from_old_map(); + else if (!strcmp(which, "end")) { game_time_end(); game_time_start(); } + else if (!strcmp(which, "set")) game_time_set_distributed(1000); + else if (!strcmp(which, "initialize")) game_time_initialize(); + else CHECK(FALSE, "unknown lifecycle case"); + /* Reactivate without another reset that could conceal the tested one. */ + game_time_globals->initialized = game_time_globals->active = TRUE; + game_time_globals->local_time = game_time_globals->server_time = 1000; + game_time_globals->speed = 1.f; + frame(1.f / TICKS_PER_SECOND + .000001f); + CHECK(ticks == 1, "prior session's target survived %s", which); +} + +static long repeated_target(boolean repeat) +{ + int index; + reset(1000); + host_update(1008); + for (index = 0; index < 30; index++) + { + if (repeat) host_update(1008); + frame(1.f / TICKS_PER_SECOND); + } + CHECK(game_time_get() <= 1038, "stale target was extrapolated into a moving target"); + return game_time_get(); +} + +static void setter_context(char const *which) +{ + reset(1000); + if (!strcmp(which, "local")) connection = _game_connection_local; + else if (!strcmp(which, "host")) connection = _game_connection_network_server; + else if (!strcmp(which, "menu")) + { + scenario_storage.type = _scenario_type_main_menu; + global_scenario = &scenario_storage; + } + else if (!strcmp(which, "inactive")) game_time_globals->active = FALSE; + else if (!strcmp(which, "uninitialized")) game_time_globals->initialized = FALSE; + else CHECK(FALSE, "unknown setter context"); + game_time_synchronize_distributed(1008); + connection = _game_connection_network_client; + global_scenario = NULL; + game_time_globals->initialized = game_time_globals->active = TRUE; + frame(1.f / TICKS_PER_SECOND); + CHECK(ticks == 1, "irrelevant %s timestamp reached a later client frame", which); +} + +int main(int argc, char **argv) +{ + char const *case_name = argc > 1 ? argv[1] : ""; + CHECK(sizeof(long) == 4 && sizeof(clock_storage) == 32, "clock fixture must use the ILP32 layout"); + if (!strncmp(case_name, "lag-", 4)) + { + convergence(strtol(case_name + 4, NULL, 10), FALSE); + return 0; + } + if (!strncmp(case_name, "lifecycle-", 10)) + { + lifecycle(case_name + 10); + return 0; + } + if (!strncmp(case_name, "setter-", 7)) + { + setter_context(case_name + 7); + return 0; + } + CASE("scaled-convergence") { convergence(8, TRUE); return 0; } + CASE("nominal") + { + reset(1000); + host_update(1000); + frame(1.f / TICKS_PER_SECOND); + CHECK(ticks == 1 && fabsf(game_time_globals->leftover_dt-.005f) < .000001f, "nominal frame changed"); + CHECK(game_time_globals->last_local_time_elapsed == 1 && frames == 1 && speed_frames == 1, + "nominal frame accounting changed"); + return 0; + } + CASE("fraction") + { + real ordinary; + reset(1000); + frame(.04f); + ordinary = game_time_globals->leftover_dt; + reset(1000); + host_update(1008); + CHECK(game_time_globals->leftover_dt == .005f, "host time reset the partial tick"); + frame(.04f); + CHECK(ticks == 2 && game_time_globals->leftover_dt == ordinary, "extra ticks changed the frame's fraction"); + CHECK(game_time_globals->last_local_time_elapsed == 2 && frame_delta == .04f, + "tick elapsed or frame duration accounting changed"); + return 0; + } + CASE("work-budget") + { + reset(1000); + game_time_synchronize_distributed(1100); + frame(.5f); + CHECK(ticks == 30, "expected bounded two-times catch-up"); + reset(1000); + game_time_synchronize_distributed(1100); + frame(.9f); + CHECK(ticks == 30, "catch-up must retain thirty-tick frame cap"); + return 0; + } + CASE("target-bound") + { + reset(1000); + host_update(1003); + frame(.067f); + CHECK(game_time_get() == 1003 && ticks == 3, "catch-up overshot the host's actual timestamp"); + return 0; + } + CASE("repeat-target") + { + long once = repeated_target(FALSE), repeated = repeated_target(TRUE); + CHECK(once == repeated, "duplicate target changed total simulation time"); + return 0; + } + CASE("stale-target") + { + reset(1000); + host_update(1008); + host_update(999); + frame(1.f / TICKS_PER_SECOND); + CHECK(ticks == 2, "older time erased newer catch-up evidence"); + return 0; + } + CASE("sub-tick") + { + reset(1000); + host_update(1008); + frame(.001f); + CHECK(!ticks && game_time_globals->last_local_time_elapsed == 0, "catch-up created a tick without normal time"); + return 0; + } + CASE("no-target") + { + int index; + reset(1000); + for (index = 0; index < 30; index++) frame(1.f / TICKS_PER_SECOND); + CHECK(ticks == 30, "client without host time changed speed"); + return 0; + } + CASE("client-ahead") + { + reset(1000); + host_update(990); + frame(1.f / TICKS_PER_SECOND); + CHECK(game_time_get() == 1001 && ticks == 1, "ahead client was rewound or accelerated"); + return 0; + } + CASE("held") + { + reset(1000); + host_update(1008); + client.started = FALSE; + frame(1.f / TICKS_PER_SECOND); + CHECK(!ticks && game_time_globals->last_local_time_elapsed == 0, "waiting client simulated"); + client.started = TRUE; + frame(1.f / TICKS_PER_SECOND); + CHECK(ticks == 2, "ready client lost its valid target"); + return 0; + } + CASE("pause") + { + reset(1000); + host_update(1008); + game_time_set_paused(TRUE); + frame(1.f / TICKS_PER_SECOND); + CHECK(!ticks && !frames && game_time_get_paused(), "normal pause no longer stops the frame clock"); + game_time_set_paused(FALSE); + frame(1.f / TICKS_PER_SECOND); + CHECK(ticks == 2, "resumed client did not process bounded catch-up"); + return 0; + } + CASE("mcc-rate-changes") + { + reset(1000); + mcc = TRUE; + host_update(1008); + remote_speed = 0.f; + frame(1.f / TICKS_PER_SECOND); + CHECK(!ticks && frame_delta == 0.f, "MCC zero speed was bypassed"); + remote_speed = .5f; + frame(1.f / TICKS_PER_SECOND); + CHECK(!ticks, "MCC half speed produced a premature tick"); + frame(1.f / TICKS_PER_SECOND); + CHECK(ticks == 2, "MCC half-speed catch-up budget differs"); + remote_speed = 2.f; + frame(1.f / TICKS_PER_SECOND); + CHECK(ticks == 6, "MCC double-speed catch-up did not use the actual normal budget"); + return 0; + } + CASE("menu") + { + reset(1000); + host_update(1008); + scenario_storage.type = _scenario_type_main_menu; + global_scenario = &scenario_storage; + frame(1.f / TICKS_PER_SECOND); + CHECK(ticks == 1 && !sends, "menu scene used gameplay catch-up or network publication"); + return 0; + } + CASE("local") + { + reset(1000); + host_update(1008); + connection = _game_connection_local; + frame(1.f / TICKS_PER_SECOND); + CHECK(ticks == 1, "local clock used a network target"); + return 0; + } + CASE("host") + { + reset(1000); + host_update(1008); + connection = _game_connection_network_server; + frame(1.f / TICKS_PER_SECOND); + CHECK(ticks == 1, "host clock used a client target"); + return 0; + } + CASE("initial-sync") + { + reset(993); + network_game_client_late_join_clock_pending = TRUE; + host_update(1000); + CHECK(game_time_get() == 1000 && !network_game_client_late_join_clock_pending && + game_time_globals->leftover_dt == 0.f, "first reliable update no longer sets the clock"); + frame(1.f / TICKS_PER_SECOND + .000001f); + CHECK(ticks == 1, "initial synchronization retained a catch-up target"); + return 0; + } + CASE("large-stall") + { + reset(1000); + host_update(1008); + host_update(1031); + CHECK(game_time_get() == 1031 && game_time_globals->leftover_dt == 0.f, + "existing long-stall recovery changed"); + frame(1.f / TICKS_PER_SECOND + .000001f); + CHECK(ticks == 1, "long-stall recovery retained a catch-up target"); + return 0; + } + CASE("invalid-times") + { + reset(1000); + host_update(-1); + host_update(0x40000000L); + frame(1.f / TICKS_PER_SECOND); + CHECK(ticks == 1, "invalid reliable timestamps affected the clock"); + return 0; + } + CASE("invalid-targets") + { + reset(1000); + game_time_synchronize_distributed(-1); + game_time_synchronize_distributed(0x40000000L); + frame(1.f / TICKS_PER_SECOND); + CHECK(ticks == 1, "invalid direct synchronization target affected the clock"); + return 0; + } + CASE("negative-clock") + { + reset(-1); + game_time_synchronize_distributed(1000); + frame(1.f / TICKS_PER_SECOND); + CHECK(ticks == 1 && game_time_get() == 0, "negative clock entered catch-up subtraction"); + return 0; + } + CASE("initialize-start") + { + reset(1000); + host_update(1008); + game_time_globals = NULL; + game_time_synchronize_distributed(2000); + game_time_initialize(); + CHECK(allocations == 1 && !game_time_globals->initialized && !game_time_globals->active, + "actual engine initialization did not reset clock storage"); + game_time_initialize_for_new_map(); + game_time_start(); + CHECK(client_starts == 1 && !server_starts && game_time_globals->active, + "client start did not use its normal queue"); + frame(1.f / TICKS_PER_SECOND + .000001f); + CHECK(ticks == 1, "old session target leaked through actual initialization and start"); + return 0; + } + CHECK(FALSE, "unknown case %s", case_name); + return 2; +} diff --git a/tools/harness/tests/glow_endpoint.c b/tools/harness/tests/glow_endpoint.c new file mode 100644 index 0000000000..e1b97f9a73 --- /dev/null +++ b/tools/harness/tests/glow_endpoint.c @@ -0,0 +1,41 @@ +#include "harness.h" +struct glow_datum { short number_of_markers; real marker_time_index[4]; }; +struct glow_particle { real t; short parent_marker_index; }; +#define PIN(v,lo,hi) ((v)<(lo)?(lo):(v)>(hi)?(hi):(v)) +#define match_vassert(file,line,test,message) CHECK(test, "marker interval missing") +#include "under_test.inc" +int main(int argc, char **argv) +{ + struct glow_datum glow; + struct glow_particle particle; + short count, index; + CHECK(argc==2,"case"); + for (count=2; count<=4; count++) + { + glow.number_of_markers=count; + for (index=0; index +static int values[7], writes; +static const char *keys[] = {"display.weapon_glow", "display.fuel_rod_lighting", + "display.ammo_counter_lighting", "display.needler_lighting", + "display.jackal_shield_lighting", "display.covenant_shield_lighting", "display.plasma_prong_lighting"}; +int config_boolean(const char *name) +{ + int i; + for (i = 0; i < 7; i++) if (!strcmp(keys[i], name)) return values[i]; + return 0; +} +int config_write(const char *name, const char *value) +{ + int i; + for (i = 0; i < 7; i++) if (!strcmp(keys[i], name)) + { + values[i] = !strcmp(value, "true"); writes++; return 1; + } + return 0; +} + +#ifndef _WIN32 +#include +#define _stricmp strcasecmp +#endif +#define NUMBEROF(a) ((short)(sizeof(a)/sizeof((a)[0]))) +#define MAXIMUM_STRINGS 32 +enum {_third_person_player_choice}; +static int third_person_policy(void) { return _third_person_player_choice; } +struct widget_instance { + long definition_tag_index; short type; + struct widget_instance *parent,*child,*next; + union {struct {short selected_index,number_of_items;} list;} parameters; +}; +struct player_profile {byte fields[8];}; +#include "under_test_types.inc" +static struct {char const *name;short field;long default_value;} profile_settings[1]={{"profile.none",0,0}}; +static struct player_profile *player_ui_get_edit_player_profile(void) { return NULL; } +static byte *profile_setting_field(struct player_profile *p,short f) { return p->fields+f; } +static boolean profile_setting_boolean(short f) { return FALSE; } +static boolean config_default(const char *n,char *t,unsigned int size) { snprintf(t,size,"false");return TRUE; } +static boolean config_text(const char *n,char *t,unsigned int size) { snprintf(t,size,"%s",config_boolean(n)?"true":"false");return TRUE; } +static void platform_log(const char *format,...) {} +static int player_link_needed_master(void) { return -1; } +static int player_link_begin(int master) { return 0; } +static void player_link_unlink(void) {} +static struct pc_menu_setting group_setting={7,"lighting.weapon_glow",2,{"false","true"},NONE}; +static struct pc_menu_setting prong_setting={8,"display.plasma_prong_lighting",2,{"false","true"},NONE}; +static struct pc_menu_setting *pc_menu_setting_get(long i) { return i==7?&group_setting:i==8?&prong_setting:NULL; } +static boolean main_menu_is_active(void) { return FALSE; } +static boolean network_game_is_active(void) { return FALSE; } +static void main_goto_main_menu(void) { CHECK(0,"lighting must not reload the frontend"); } +#include "under_test.inc" +int main(int argc, char **argv) +{ + char text[32]; + int i; + struct widget_instance spinner; + (void)argc; (void)argv; + CHECK(lighting_menu_text("display.unknown", text, sizeof(text), 0) == -1, + "unrelated controls keep their normal route"); + values[2] = 1; + CHECK(lighting_menu_text("lighting.weapon_glow", text, sizeof(text), 0) == 1 && !strcmp(text, "true"), + "any explicitly enabled member is shown as ON"); + CHECK(!lighting_menu_write("lighting.weapon_glow", "custom") && !writes, "CUSTOM is not a valid selection"); + CHECK(lighting_menu_text("lighting.weapon_glow", text, sizeof(text), 1) && !strcmp(text, "false") && !writes, + "defaults are staged without applying before Save"); + CHECK(values[2] && !values[0], "cancelling staged defaults preserves old preferences"); + CHECK(lighting_menu_write("lighting.weapon_glow", "false"), "save off"); + for (i = 0; i < 4; i++) CHECK(!values[i], "off disables every member"); + CHECK(lighting_menu_write("lighting.weapon_glow", "true"), "save on"); + CHECK(lighting_menu_text("lighting.weapon_glow", text, sizeof(text), 0) && !strcmp(text, "true"), + "reopening reflects saved group"); + CHECK(!values[4] && !values[5], "weapon group does not change shields"); + CHECK(lighting_menu_write("lighting.shield_emitters", "true") && values[4] && values[5], "shield group"); + CHECK(!lighting_menu_write("lighting.weapon_glow", "invalid"), "invalid values do not write"); + memset(&spinner,0,sizeof(spinner));spinner.definition_tag_index=7;spinner.type=2; + spinner.parameters.list.number_of_items=2; + values[0]=values[1]=values[3]=0;values[2]=1;writes=0; + CHECK(setting_load(&spinner)&&spinner.parameters.list.selected_index==1,"menu has only OFF and ON"); + spinner.parameters.list.selected_index=1; + CHECK(!writes&&values[0]==0,"changing spinner is staged"); + CHECK(setting_load(&spinner)&&spinner.parameters.list.selected_index==1&&!writes,"Cancel/reopen discards staged choice"); + CHECK(setting_default_show(&spinner,&group_setting)&&spinner.parameters.list.selected_index==0&&!writes,"Defaults stages OFF without writes"); + CHECK(setting_load(&spinner)&&spinner.parameters.list.selected_index==1&&!writes,"Cancel after Defaults preserves preferences"); + spinner.parameters.list.selected_index=0; + CHECK(setting_changed_save(&spinner,&group_setting)&&writes==4,"Save writes all four group members"); + CHECK(setting_load(&spinner)&&spinner.parameters.list.selected_index==0,"reopened menu reads persisted OFF members"); + spinner.parameters.list.selected_index=1; + CHECK(setting_save(&spinner)&&writes==8,"alternate save handler enables group"); + CHECK(setting_default_show(&spinner,&group_setting)&&setting_save(&spinner)&&writes==12,"alternate save handler applies grouped defaults"); + for(i=0;i<4;i++)CHECK(!values[i],"all weapon members default OFF"); + CHECK(values[4]&&values[5],"weapon defaults do not alter another group"); + spinner.definition_tag_index=8;spinner.parameters.list.number_of_items=2; + CHECK(setting_load(&spinner)&&spinner.parameters.list.selected_index==0,"prong toggle defaults off independently"); + spinner.parameters.list.selected_index=1; + CHECK(!values[6]&&setting_load(&spinner)&&spinner.parameters.list.selected_index==0,"Cancel discards staged prongs"); + spinner.parameters.list.selected_index=1; + CHECK(setting_changed_save(&spinner,&prong_setting)&&values[6],"Save enables standalone prongs"); + CHECK(setting_load(&spinner)&&spinner.parameters.list.selected_index==1,"reopen retains standalone selection"); + CHECK(lighting_menu_write("lighting.weapon_glow","false")&&values[6],"Weapon Glow leaves prongs untouched"); + CHECK(setting_default_show(&spinner,&prong_setting)&&values[6],"Defaults stages prongs without writing"); + CHECK(setting_load(&spinner)&&spinner.parameters.list.selected_index==1,"Cancel defaults preserves prongs"); + CHECK(setting_default_show(&spinner,&prong_setting)&&setting_save(&spinner)&&!values[6],"Save defaults disables prongs"); + return 0; +} diff --git a/tools/harness/tests/lighting_migration.c b/tools/harness/tests/lighting_migration.c new file mode 100644 index 0000000000..aec422a519 --- /dev/null +++ b/tools/harness/tests/lighting_migration.c @@ -0,0 +1,67 @@ +#define _CRT_SECURE_NO_WARNINGS +#include "harness.h" +#include +#include +#include +/* tomlc17 uses C11 assertions; the harness compiles as C99. */ +#ifndef static_assert +#define static_assert _Static_assert +#endif +#include "toml.inc" +#include "under_test.inc" + +static void check_reset(const char *text) +{ + toml_result_t old = toml_parse(text, (int)strlen(text)), result; + char *changed; + size_t i; + CHECK(old.ok, "valid fixture: %s", old.errmsg); + CHECK(lighting_settings_legacy(old.toptab), "legacy fixture needs migration"); + changed = lighting_settings_migrate(text, old.toptab); + CHECK(changed != NULL, "migration produced text"); + result = toml_parse(changed, (int)strlen(changed)); + CHECK(result.ok, "migrated TOML valid: %s", result.errmsg); + for (i = 0; i < 13; i++) + { + toml_datum_t value = toml_seek(result.toptab, lighting_reset_keys[i]); + CHECK(value.type == TOML_UNKNOWN || (value.type == TOML_BOOLEAN && !value.u.boolean), "lighting off"); + } + if (toml_seek(result.toptab, "display.shield_glow_intensity").type == TOML_STRING) + CHECK(!strcmp(toml_seek(result.toptab, "display.shield_glow_intensity").u.s, "default"), "default intensity"); + CHECK(toml_seek(result.toptab, "display.vsync").u.boolean, "unrelated preference preserved"); + CHECK(strstr(changed, "# keep comment"), "comments preserved"); + toml_free(result);toml_free(old);free(changed); +} + +int main(int argc, char **argv) +{ + toml_result_t result; + char text[2048] = "# keep comment\n[display]\nvsync = true\n"; + const char completed[] = "[display]\ndynamic_lighting_reset=true\nweapon_glow=true\n"; + size_t i; + (void)argc;(void)argv; + for (i = 0; i < 13; i++) + { strcat(text, lighting_reset_keys[i] + 8);strcat(text, " = true\n"); } + strcat(text, "shield_glow_intensity = 'light_show'\n"); + check_reset(text); + check_reset("# keep comment\r\n[display]\r\nvsync = true\r\n\"weapon_glow\" = true # light\r\nshield_glow_intensity = \"light_show\"\r\n"); + check_reset("# keep comment\ndisplay = {vsync = true, weapon_glow = true, shield_glow_intensity = 'light_show'}\n"); + check_reset("# keep comment\ndisplay.vsync = true\ndisplay.weapon_glow = true\n"); + check_reset("# keep comment\n[display]\nvsync = true\ndynamic_lighting_reset = false\nshield_glow_intensity = \"\"\"light_\nshow\"\"\"\n"); + result=toml_parse(completed, sizeof(completed)-1); + CHECK(result.ok, "completed migration fixture"); + CHECK(!lighting_settings_legacy(result.toptab), "marker preserves later choices"); + CHECK(lighting_settings_migrate("", result.toptab)==NULL, "no repeated migration"); + CHECK(toml_seek(result.toptab,"display.weapon_glow").u.boolean, "new ON choice retained"); + toml_free(result); + { + const char invalid[] = "[display]\nweapon_glow='invalid'\n"; + result=toml_parse(invalid,sizeof(invalid)-1); + CHECK(result.ok && lighting_settings_legacy(result.toptab), "wrong setting type needs reset"); + CHECK(!lighting_settings_migrate(invalid,result.toptab), "unmigratable file never marked complete"); + toml_free(result); + } + CHECK(lighting_settings_reset_key("display.shield_glow"), "glow reset"); + CHECK(!lighting_settings_reset_key("display.shield_look") && !lighting_settings_reset_key("display.per_pixel_lighting"), "unrelated rendering preserved"); + return 0; +} diff --git a/tools/harness/tests/lightning_tick_shape.c b/tools/harness/tests/lightning_tick_shape.c index 7b6b2b774f..30a4900a26 100644 --- a/tools/harness/tests/lightning_tick_shape.c +++ b/tools/harness/tests/lightning_tick_shape.c @@ -122,8 +122,12 @@ draws them */ struct object_marker { short node_index; real_matrix4x3 node_matrix; real_matrix4x3 matrix; }; static real_point3d marker_start = { 0.0f, 0.0f, 0.0f }; static real_point3d marker_end = { 2.0f, 0.0f, 0.0f }; +/* Fail before random generation, or after it at vertex allocation. */ +static short draw_failure; static short object_get_marker_by_name(long object_index, char const *name, struct object_marker *marker, short count) { + if (draw_failure == 1) + return 0; memset(marker, 0, sizeof(*marker)); marker->matrix.scale = 1.0f; marker->matrix.forward.i = marker->matrix.left.j = marker->matrix.up.k = 1.0f; @@ -139,7 +143,7 @@ static struct bitmap_group bolt_bitmaps = { { 1, &bolt_bitmap, NULL } }; static struct bitmap_group *bitmap_group_get(long index) { return &bolt_bitmaps; } static boolean _texture_cache_bitmap_get_hardware_format(struct bitmap_data *bitmap, boolean a, boolean b) { - return TRUE; + return draw_failure != 2; } struct shader { long type; }; struct shader_effect_definition { struct shader shader; }; @@ -163,6 +167,8 @@ static long drawn_count; static long vertex_buffer_count; static long rasterizer_dynamic_vertices_new(short type, long count) { + if (draw_failure == 3) + return NONE; CHECK(count <= MAXIMUM_VERTICES, "a bolt of %ld vertices", count); vertex_buffer_count = count; return 0; @@ -191,6 +197,7 @@ static struct lightning_definition bolt_definition; #define lightning_definition_get(definition_index) (&bolt_definition) #include "under_test.inc" +#include "after_load.inc" static void define_bolt(void) { @@ -199,7 +206,7 @@ static void define_bolt(void) for (index = 0; index < 2; index++) { memset(&markers[index], 0, sizeof(markers[index])); - strcpy(markers[index].attachment_marker, index ? "end" : "start"); + memcpy(markers[index].attachment_marker, index ? "end" : "start", index ? 4 : 6); markers[index].octaves_to_next_marker = 3; set_real_vector3d(&markers[index].random_position_bounds, 0.1f, 0.1f, 0.1f); markers[index].random_jitter_offset = 0.2f; @@ -320,16 +327,21 @@ int main(int argc, char **argv) /* split screen: each window's bolt is its own, kept for the tick */ CASE("windows-apart") { - struct bolt first0, first1, again0, again1; + struct bolt first[4], again; + short window, previous; game_time = 10; - first0 = frame(lightning, 0, 0); - first1 = frame(lightning, 1, 0); - CHECK(!same_shape(&first0, &first1, 0.0f), "the second window drew the first window's bolt"); - again0 = frame(lightning, 0, 3); - again1 = frame(lightning, 1, 3); - CHECK(same_shape(&first0, &again0, 0.0f) && same_shape(&first1, &again1, 0.0f), - "a window's later frame drew another bolt than its first"); + for (window = 0; window < 4; window++) + { + first[window] = frame(lightning, window, 0); + for (previous = 0; previous < window; previous++) + CHECK(!same_shape(&first[window], &first[previous], 0.0f), "windows share a seed"); + } + for (window = 3; window >= 0; window--) + { + again = frame(lightning, window, 3); + CHECK(same_shape(&first[window], &again, 0.0f), "window %d changed shape", window); + } return 0; } /* a lightning made where another was, in the same tick, draws its own @@ -347,6 +359,104 @@ int main(int argc, char **argv) CHECK(!same_shape(&old, &renewed, 0.0f), "the new lightning drew the old one's bolt"); return 0; } + CASE("tick-zero") + { + struct bolt first, again; + unsigned long before = local_random_seed; + + game_time = 0; + first = frame(lightning, 0, 0); + CHECK(local_random_seed != before, "tick zero was mistaken for an initialized seed"); + again = frame(lightning, 0, 7); + CHECK(same_shape(&first, &again, 0.f), "tick zero changed shape"); + return 0; + } + /* A new map can start at the same time and reuse the same datum slot. + A checkpoint also restores the pool without calling lightning_new. */ + CASE("map-reset") + { + struct bolt first, reset; + + game_time = 0; + first = frame(lightning, 0, 0); + lightnings_initialize_for_new_map(); + reset = frame(lightning, 0, 0); + CHECK(!same_shape(&first, &reset, 0.f), "a new map retained the old map's seed"); + return 0; + } + CASE("checkpoint-load") + { + struct bolt first, restored; + + game_time = 10; + first = frame(lightning, 0, 0); + game_state_call_after_load_procs(); + restored = frame(lightning, 0, 0); + CHECK(!same_shape(&first, &restored, 0.f), "a checkpoint retained a seed from the discarded state"); + return 0; + } + CASE("multiple-lightnings") + { + struct bolt first, last, again; + long other = NONE; + short index; + + game_time = 10; + first = frame(lightning, 0, 0); + for (index = 1; index < 256; index++) + other = lightning_new(0); + CHECK(DATUM_INDEX_TO_ABSOLUTE_INDEX(other) == 255, "did not reach last pool slot"); + CHECK(lightning_new(0) == NONE, "full pool did not refuse allocation"); + last = frame(other, 0, 0); + CHECK(!same_shape(&first, &last, 0.f), "independent lightnings share a seed"); + again = frame(lightning, 0, 3); + CHECK(same_shape(&first, &again, 0.f), "another lightning overwrote the first seed"); + again = frame(other, 0, 3); + CHECK(same_shape(&last, &again, 0.f), "last pool slot did not retain its seed"); + return 0; + } + CASE("failed-redraw") + { + struct bolt first, recovered; + unsigned long before; + short failure; + + game_time = 10; + first = frame(lightning, 0, 0); + for (failure = 1; failure <= 3; failure++) + { + draw_failure = failure; + drawn_count = 0; + before = local_random_seed; + lightning_submit(7, lightning, NULL, NULL); + CHECK(drawn_count == 0, "failure %d unexpectedly drew geometry", failure); + CHECK(local_random_seed == before, "failure %d leaked the cached seed", failure); + CHECK(rasterizer_globals.current_lock_operation == _rasterizer_lock_none, "lock leaked"); + draw_failure = 0; + recovered = frame(lightning, 0, 4); + CHECK(same_shape(&first, &recovered, 0.f), "failure %d lost the tick's shape", failure); + } + return 0; + } + CASE("failed-first-draw") + { + struct bolt recovered, again; + short failure; + + for (failure = 1; failure <= 3; failure++) + { + game_time = failure; + draw_failure = failure; + drawn_count = 0; + lightning_submit(7, lightning, NULL, NULL); + CHECK(drawn_count == 0, "failure %d unexpectedly drew geometry", failure); + draw_failure = 0; + recovered = frame(lightning, 0, 3); + again = frame(lightning, 0, 5); + CHECK(same_shape(&recovered, &again, 0.f), "first-draw failure %d prevented recovery", failure); + } + return 0; + } fprintf(stderr, "unknown case '%s'\n", case_name); return 2; } diff --git a/tools/harness/tests/link_action_menu.c b/tools/harness/tests/link_action_menu.c index 5d04ec935a..5194ced353 100644 --- a/tools/harness/tests/link_action_menu.c +++ b/tools/harness/tests/link_action_menu.c @@ -1,8 +1,14 @@ #include "harness.h" +#ifndef _WIN32 #include +#endif #define MAXIMUM_STRINGS 32 +enum {_third_person_player_choice}; +static int third_person_policy(void){return _third_person_player_choice;} #define NUMBEROF(a) ((short)(sizeof(a)/sizeof((a)[0]))) +#ifndef _WIN32 #define _stricmp strcasecmp +#endif struct widget_instance { long definition_tag_index; short type; struct widget_instance *parent,*child,*next; @@ -28,6 +34,11 @@ static int player_link_begin(int master){begun=master;begin_count++;return 1;} static void player_link_unlink(void){unlink_count++;} static struct pc_menu_setting link_setting={7,"link.action",6,{"none","link_1","link_2","link_3","link_4","unlink"},NONE}; static struct pc_menu_setting *pc_menu_setting_get(long definition_index){return definition_index==7?&link_setting:NULL;} +static boolean main_menu_is_active(void){return FALSE;} +static boolean network_game_is_active(void){return FALSE;} +static void main_goto_main_menu(void){CHECK(0,"link action unexpectedly reloaded the frontend");} +int lighting_menu_text(const char *n,char *t,unsigned int s,int d) { return -1; } +int lighting_menu_write(const char *n,const char *v) { return -1; } #include "under_test.inc" static struct widget_instance spinner; /* the screen opened (the spinner's "port setting load"), the spinner moved diff --git a/tools/harness/tests/listener_motion.c b/tools/harness/tests/listener_motion.c index 3e60ff6941..1fce2abfab 100644 --- a/tools/harness/tests/listener_motion.c +++ b/tools/harness/tests/listener_motion.c @@ -30,6 +30,7 @@ static struct object_datum *object_get(long index) typedef void (*director_camera_update_proc)(void); static void first_person_camera_update(void) {} static void following_camera_update(void) {} +static void third_person_camera_update(void) {} static void dead_camera_update(void) {} static void flying_camera_update(void) {} struct dead_camera { long unit_index; }; @@ -172,9 +173,9 @@ int main(int argc, char **argv) { struct dead_camera dead = { 77 }; director_camera_update_proc cameras[] = { first_person_camera_update, following_camera_update, - dead_camera_update, flying_camera_update }; - long expected[] = { 100, 100, 77, NONE }; - for (player = 0; player < 4; player++) + third_person_camera_update, dead_camera_update, flying_camera_update }; + long expected[] = { 100, 100, 100, 77, NONE }; + for (player = 0; player < 5; player++) { directors[0].camera_proc = cameras[player]; directors[0].camera_data = &dead; diff --git a/tools/harness/tests/lobby_countdown.c b/tools/harness/tests/lobby_countdown.c index d837c24ac0..43aede8109 100644 --- a/tools/harness/tests/lobby_countdown.c +++ b/tools/harness/tests/lobby_countdown.c @@ -20,6 +20,8 @@ test_lobby_countdown.py takes the constants, enums and timer structures #define MIN(a, b) ((a) < (b) ? (a) : (b)) #define CEILING(n, ceiling) ((n) > (ceiling) ? (ceiling) : (n)) #define PIN(n, floor, ceiling) ((n) < (floor) ? (floor) : CEILING((n), (ceiling))) +#define NUMBEROF(array) (sizeof(array) / sizeof((array)[0])) +#define csmemset memset #include "config.inc" @@ -36,22 +38,24 @@ struct network_game_server_client_machine boolean joined; }; -struct network_game_server +struct network_game { - short state; + short player_count; + short minimum_players; struct { - short player_count; - short minimum_players; struct { - struct - { - boolean teams; - } universal_variant; - } variant; - struct network_player players[MAXIMUM_NETWORK_PLAYER_COUNT]; - } game; + boolean teams; + } universal_variant; + } variant; + struct network_player players[MAXIMUM_NETWORK_PLAYER_COUNT]; +}; + +struct network_game_server +{ + short state; + struct network_game game; struct network_game_server_client_machine client_machines[MAXIMUM_NETWORK_MACHINE_COUNT]; struct network_game_server_countdown_state countdown_state; boolean sent_start_game_message; @@ -65,6 +69,11 @@ static boolean network_game_should_accept_remote_connections(void) { return TRUE static boolean splitscreen; static boolean network_game_is_splitscreen_local(void) { return splitscreen; } static boolean network_player_is_valid(struct network_player *player) { return player->valid; } +static int network_bots, network_bots_enabled, network_option, host = TRUE; +static byte owned[BOTS_MAXIMUM]; +static int config_boolean(char const *name) { (void)name; return network_option; } +static void bots_management_reset(void) { } +static struct network_game_server *global_network_game_server_get(void) { return host ? &server : NULL; } static boolean network_game_server_client_machine_is_joined_to_game( struct network_game_server *s, struct network_game_server_client_machine *machine) @@ -160,6 +169,67 @@ static long time_remaining(void) int main(int argc, char **argv) { char const *case_name = argc > 1 ? argv[1] : ""; + long index; + + if (!strncmp(case_name, "bots-", 5) || strstr(case_name, "-bot-start") || strstr(case_name, "-bots-start")) + { + long count = !strcmp(case_name, "one-bot-start") ? 1 : + !strcmp(case_name, "63-bots-start") ? 63 : 31; + boolean blocked = !strcmp(case_name, "bots-team-rule") || !strcmp(case_name, "bots-minimum-rule") || + !strcmp(case_name, "bots-paused") || !strcmp(case_name, "bots-no-machine"); + lobby(!strcmp(case_name, "bots-no-machine") ? 0 : 1); + server.game.variant.universal_variant.teams = TRUE; + network_option = TRUE; + bots_network_session_begin(); + add_player(0, 0); + for (index = 0; index < count; index++) + { + add_player(BOTS_FIRST_MACHINE + index, !strcmp(case_name, "bots-team-rule") ? 0 : (index + 1) % 2); + bots_player_ownership(BOTS_FIRST_MACHINE + index, TRUE); + } + if (!strcmp(case_name, "split-screen-bots-start")) add_player(0, 1); + CHECK(bots_lobby_can_start(&server.game), "owned bots did not extend lone human permission"); + if (!strcmp(case_name, "bots-ownership-lifecycle")) + { + CHECK(!bots_lobby_can_start(NULL), "null game accepted"); + host = FALSE; + CHECK(!bots_lobby_can_start(&server.game), "client granted bot permission"); + host = TRUE; + server.game.players[0].valid = FALSE; + CHECK(!bots_lobby_can_start(&server.game), "bot-only lobby accepted"); + server.game.players[0].valid = TRUE; + bots_network_session_end(); + CHECK(!bots_lobby_can_start(&server.game), "disposed ownership survived"); + bots_network_session_begin(); + CHECK(!bots_lobby_can_start(&server.game), "high-ID humans treated as bots"); + for (index = 0; index < count; index++) bots_player_ownership(BOTS_FIRST_MACHINE + index, TRUE); + CHECK(bots_lobby_can_start(&server.game), "new session ownership refused"); + for (index = 0; index < count; index++) bots_player_ownership(BOTS_FIRST_MACHINE + index, FALSE); + start_now(); + CHECK(!server.countdown_state.active, "unowned high IDs bypassed start gate"); + network_option = FALSE; + bots_network_session_begin(); + for (index = 0; index < count; index++) bots_player_ownership(BOTS_FIRST_MACHINE + index, TRUE); + CHECK(!bots_lobby_can_start(&server.game), "disabled network bots granted permission"); + return 0; + } + if (!strcmp(case_name, "bots-minimum-rule")) server.game.minimum_players = count + 2; + if (!strcmp(case_name, "bots-paused")) server.countdown_state.paused = TRUE; + if (!strcmp(case_name, "bots-second-machine")) + { + join_machine(1); + add_player(1, 0); + CHECK(!bots_lobby_can_start(&server.game), "two human machines called a lone host"); + } + if (!strcmp(case_name, "bots-existing-countdown")) + { + server.countdown_state.active = TRUE; + countdown_timer_set_time_remaining(&server.countdown_state.timer, NETWORK_GAME_COUNTDOWN_TIME); + } + start_now(); + CHECK(server.countdown_state.active == !blocked, "bot lobby countdown: active=%d", server.countdown_state.active); + return 0; + } CASE("split-screen-start-now") { diff --git a/tools/harness/tests/map_share_trust.c b/tools/harness/tests/map_share_trust.c index 96276a69ba..da6d695564 100644 --- a/tools/harness/tests/map_share_trust.c +++ b/tools/harness/tests/map_share_trust.c @@ -9,9 +9,12 @@ seconds apart at most. test_map_share_trust.py takes the constants and structures (config.inc) and the code (under_test.inc). */ +#define _CRT_SECURE_NO_WARNINGS #include "harness.h" typedef unsigned short word; +typedef word message_header; +#include "message_header.inc" #include "config.inc" @@ -29,14 +32,6 @@ typedef unsigned short word; /* the fake world: a clock, the host's game and its machines, a catalog of one file, and what the code under test did */ -struct distributed_message_header -{ - word header; - byte type; - byte count; - long game_time; -}; - struct network_game { struct diff --git a/tools/harness/tests/mcc_ai_deselect.c b/tools/harness/tests/mcc_ai_deselect.c new file mode 100644 index 0000000000..f9d69eadf9 --- /dev/null +++ b/tools/harness/tests/mcc_ai_deselect.c @@ -0,0 +1,119 @@ +/* Native selection state and script policy, using source-extracted functions. */ +#include "harness.h" +#include +#define NUMBEROF(a) (sizeof(a)/sizeof((a)[0])) +#define csmemset memset +#define csstrcmp strcmp +#include "types.inc" + +struct ai_debug_actor_record { boolean valid; long sentinel; }; +static struct { + long selected_squad_index, selected_actor_index; + boolean evaluation_context_valid; + byte evaluation_context[32]; + struct ai_debug_actor_record actor_record[NUMBER_OF_AI_DEBUG_ACTOR_RECORDS]; + boolean idle_look_valid; + long idle_look_unit_index; + short idle_look_prop_count; + long unrelated; +} ai_debug, before; +static struct { boolean ai_initialized_for_map; } ai_state; +#define ai_globals (&ai_state) +static void ai_debug_select_actor(long encounter, long actor); +static long returned, returned_thread; +static void hs_return(long thread, long value) { returned_thread=thread;returned=value; } + +/* The native policy is compiled below; only its unrelated services are mocked. */ +struct hs_function_definition { + char const *name; + boolean (*parse)(short, long); + short parameter_count, parameter_types[1]; +}; +static boolean hs_macro_function_parse(short index, long expression) { return TRUE; } +static struct hs_function_definition native_select={"ai_select", hs_macro_function_parse, 1, {_hs_type_ai}}; +static struct hs_function_definition native_deselect={"ai_deselect", hs_macro_function_parse, 0, {0}}; +static struct hs_function_definition *hs_function_get(short index) { + return index==NATIVE_AI_SELECT ? &native_select : &native_deselect; +} +static struct hs_function_definition *mcc_script_function(short index) { return NULL; } +static boolean mcc_script_call_valid(struct hs_syntax_node const *call, struct data_array *syntax) { return FALSE; } +static boolean mcc_script_call_arguments_valid(struct hs_syntax_node const *call, struct data_array *syntax) { return FALSE; } +static struct data_array syntax_data; +static struct data_array *hs_syntax_data=&syntax_data; +static struct hs_syntax_node nodes[3]; +static void *datum_try_and_get(struct data_array *array, long handle) { + long index=DATUM_INDEX_TO_ABSOLUTE_INDEX(handle); + return handle!=NONE && indexcount && nodes[index].datum_header==(short)((unsigned long)handle>>16) ? nodes+index : NULL; +} +#define hs_type_valid(type) ((type)>=_hs_type_void && (type)1 ? argv[1] : ""; + char const *refused; + long i; + memset(&ai_debug,0x5a,sizeof(ai_debug)); + ai_debug.selected_squad_index=17;ai_debug.selected_actor_index=29; + ai_state.ai_initialized_for_map=TRUE; + returned=999;returned_thread=NONE; + CASE("inactive") ai_state.ai_initialized_for_map=FALSE; + CASE("already-clear") ai_debug.selected_squad_index=ai_debug.selected_actor_index=NONE; + CASE("actor-only") ai_debug.selected_squad_index=NONE; + before=ai_debug; + CASE("clear") { + mcc_ai_deselect_evaluate(0x7007,73,TRUE); + CHECK(ai_debug.selected_squad_index==NONE && ai_debug.selected_actor_index==NONE,"selection"); + CHECK(!ai_debug.evaluation_context_valid && !ai_debug.idle_look_valid,"valid bits"); + CHECK(ai_debug.idle_look_unit_index==NONE && !ai_debug.idle_look_prop_count,"idle look"); + for(i=0;i<(long)sizeof(ai_debug.evaluation_context);i++) CHECK(!ai_debug.evaluation_context[i],"context"); + for(i=0;i +#include +#include +#undef malloc +#undef free +#undef realloc +#undef memcpy +#undef memset +#undef memcmp +static unsigned char tags[4096]; +static int allocations,reads,attempts,fail_at; +void *debug_malloc(unsigned int n,boolean clear,char const *file,long line) { + void *p; if(++attempts==fail_at)return NULL;p=malloc(n);(void)file;(void)line;if(p){allocations++;if(clear)memset(p,0,n);}return p; +} +void debug_free(void *p,char const *file,long line) {(void)file;(void)line;if(p){allocations--;free(p);}} +void *csmemcpy(void *a,void const *b,unsigned long n) {return memcpy(a,b,n);} +void *csmemset(void *a,long v,unsigned long n) {return memset(a,v,n);} +void error(short priority,char const *format,...) {(void)priority;(void)format;} +void mcc_loading_update(enum mcc_loading_stage stage,unsigned long a,unsigned long b) {(void)stage;(void)a;(void)b;} +void mcc_loading_pulse(void) {} +void *mcc_runtime_pointer(struct mcc_runtime *r,uint32_t p,uint32_t n) { + uint32_t base=(uint32_t)r->tags; + return p>=base && p-base<=r->used && n<=r->used-(p-base) ? (void *)p : NULL; +} +int mcc_runtime_read(struct mcc_runtime *r,uint32_t o,uint32_t n,void *out) { + (void)r;reads++;memset(out,(int)o,n);return 1; +} +int mcc_resources_read(struct mcc_runtime *r,unsigned type,char const *name,uint32_t o,uint32_t n,void *out,char const *group) { + (void)type;(void)name;(void)group;return mcc_runtime_read(r,o,n,out); +} +int mcc_vorbis_decode(unsigned char const *b,uint32_t n,uint32_t limit,short **samples,uint32_t *frames,uint32_t *rate,int *channels) { + (void)b;(void)n;(void)limit;(void)samples;(void)frames;(void)rate;(void)channels;return 0; +} +void mcc_vorbis_free(short *p) {free(p);} +#define CHECK(c) do{if(!(c)){fprintf(stderr,"line %d\n",__LINE__);return 1;}}while(0) +int main(void) { + struct mcc_runtime runtime; + struct sound_definition *sound=(void *)(tags+512); + struct sound_pitch_range *range=(void *)(tags+1024); + struct sound_permutation *permutation=(void *)(tags+1536); + uint32_t *entry=(void *)tags; + int rate,nonempty,channels; + for(rate=-2;rate<=2;rate++) for(nonempty=0;nonempty<3;nonempty++) for(channels=0;channels<2;channels++) { + int expected=rate>=-1 && rate<=1 && (rate!=-1 || nonempty<2); + memset(&runtime,0,sizeof(runtime));memset(tags,0,sizeof(tags));reads=0; + runtime.tags=runtime.tag_index=tags;runtime.used=sizeof(tags);runtime.report.tag_count=1; + entry[0]=SOUND_DEFINITION_TAG;entry[4]=(uint32_t)(tags+128);entry[5]=(uint32_t)sound; + sound->sample_rate=(short)rate;sound->encoding=(short)channels; + sound->pitch_ranges.count=1;sound->pitch_ranges.address=range; + range->permutations.count=nonempty ? 1 : 0;range->permutations.address=permutation; + permutation->samples.size=nonempty==2 ? 4 : 0; + CHECK(mcc_audio_prepare(&runtime)==expected); + if(expected) CHECK(sound->sample_rate>=0 && sound->sample_rate<=1 && sound->compression==1); + if(rate<0) CHECK(!reads); + mcc_audio_dispose(&runtime);CHECK(!runtime.audio && !allocations); + mcc_audio_dispose(&runtime);CHECK(!allocations); + } + /* Identical offsets belong to different sound tags, and a reused + * absolute index with the wrong salt cannot read another sound. */ + for(fail_at=0;fail_at<=8;fail_at++) { + unsigned char a[36],b[36]; + int i,ok; + memset(&runtime,0,sizeof(runtime));memset(tags,0,sizeof(tags));attempts=0; + runtime.tags=runtime.tag_index=tags;runtime.used=sizeof(tags);runtime.report.tag_count=2; + for(i=0;i<2;i++) { + uint32_t *e=entry+i*8; + sound=(void *)(tags+512+i*256);range=(void *)(tags+1024+i*96); + permutation=(void *)(tags+1536+i*124); + e[0]=SOUND_DEFINITION_TAG;e[3]=0xe0000000u+i*0x10001u; + e[4]=(uint32_t)(tags+128);e[5]=(uint32_t)sound; + sound->pitch_ranges.count=1;sound->pitch_ranges.address=range; + range->permutations.count=1;range->permutations.address=permutation; + permutation->samples.size=64;permutation->samples.file_offset=i+1; + } + ok=mcc_audio_prepare(&runtime);CHECK(ok==(fail_at==0)); + if(ok) { + CHECK(mcc_audio_read(&runtime,(long)0xe0000000u,0x50000000u,36,a)==1); + CHECK(mcc_audio_read(&runtime,(long)0xe0010001u,0x50000000u,36,b)==1); + CHECK(memcmp(a,b,36)); + CHECK(!mcc_audio_read(&runtime,(long)0xe0020001u,0x50000000u,36,b)); + CHECK(!mcc_audio_read(&runtime,(long)0xe0020002u,0x50000000u,36,b)); + CHECK(!mcc_audio_contains(&runtime,(long)0xe0000000u,0x50000001u,36)); + CHECK(mcc_audio_read(&runtime,(long)0xe0000000u,0x50000024u,0,b)==1); + CHECK(mcc_audio_read(&runtime,(long)0xe0000000u,16,1,b)==-1); + CHECK(mcc_audio_stream_end(&runtime)==0x50000024u); + } + mcc_audio_dispose(&runtime);CHECK(!runtime.audio && !allocations); + CHECK(!mcc_audio_contains(&runtime,(long)0xe0000000u,0x50000000u,1)); + } + return 0; +} diff --git a/tools/harness/tests/mcc_campaign.c b/tools/harness/tests/mcc_campaign.c new file mode 100644 index 0000000000..693ce7a931 --- /dev/null +++ b/tools/harness/tests/mcc_campaign.c @@ -0,0 +1,501 @@ +/* Real MCC handlers with a deterministic local/remote player world. */ +#include "cseries.h" +#include "hs/hs.h" +#include "hs/hs_scenario_definitions.h" +#include "memory/data.h" +#include "game/game.h" +#include "game/cheats.h" +#include "game/players.h" +#include "objects/objects.h" +#include "units/units.h" +#include "units/bipeds.h" +#include "mcc_script_effects.h" +#include "ai/actor_definitions.h" +#include "interface/hud.h" +#include "interface/hud_definitions.h" +#include "scenario/scenario_definitions.h" +#include "mcc_campaign.h" +#include "mcc_game_speed.h" +#include "sound/sound_definitions.h" +#include +#include +#include +#undef memset +#undef memcpy +#undef strcmp +#undef strlen +void mcc_game_speed_reset(void) {} + +#define CHECK(x) do {if(!(x)){fprintf(stderr,"line %d: %s\n",__LINE__,#x);return 1;}}while(0) +static int printed,requests,blocks,restarts,network_restarts,cinematic_skips,vehicle_spawns,weapon_spawns,possessions; +void cheat_all_vehicles(void) {vehicle_spawns++;} +void cheat_all_weapons(void) {weapon_spawns++;} +void main_skip_cinematic(void) {cinematic_skips++;} +void main_reset_map(void) {restarts++;} +boolean mcc_ui_restart_network_game(void) {network_restarts++;return TRUE;} +static struct sound_definition sound; +static struct actor_variant_definition actor_variant; +static long predicted_tag=NONE; +boolean tag_index_is_group(long index,long group) { + return (index==19 && group==ACTOR_VARIANT_DEFINITION_TAG) || (index==20 && group==OBJECT_DEFINITION_TAG); +} +void object_definition_predict(long index) {predicted_tag=index;} +static struct sound_pitch_range ranges[2]; +static struct sound_permutation permutations[3]; +void hs_print(char const *message) {if(strcmp(message,"100% literal"))abort();printed++;} +void *tag_get(long group,long index) { + if(group==ACTOR_VARIANT_DEFINITION_TAG && index==19)return &actor_variant; + if(group!='snd!'||index!=17)abort();return &sound; +} +boolean _sound_cache_sound_request(struct sound_permutation *p,boolean block,boolean load,boolean ref) { + if(p=permutations+3||!load||ref)abort();requests++;blocks+=block;return TRUE; +} +static boolean loaded=TRUE; +static short connection; +static boolean local_coop, online_coop, screen_flashes=TRUE, fading_out; +static short fade_ticks=NONE; +static long fade_start; +boolean game_is_cooperative(void) {return local_coop;} +boolean network_coop_active(void) {return online_coop;} +void player_effect_port_screen_fade_get(real_rgb_color *color,short *ticks,boolean *out,long *start) { + color->red=color->green=color->blue=0;*ticks=fade_ticks;*out=fading_out;*start=fade_start; +} +static long args[7],result,added[4]; +static int count,draws; +static real_point3d drawn; +static struct player_datum players[3]; +static struct biped_datum units[3]; +static int kills, silent_kills; +void unit_kill(long index) {if(!unit_try_and_get(index))abort();kills++;} +void unit_kill_silent(long index) {if(!unit_try_and_get(index))abort();silent_kills++;} +static struct scenario scenario; +static struct scenario_cutscene_flag flags[2]; +static struct hud_globals_definition hud; +static struct data_array player_array,list_array,syntax_array; +struct data_array *player_data=&player_array,*object_list_header_data=&list_array,*hs_syntax_data=&syntax_array; +struct hud_globals_definition *hud_globals=&hud; +real global_gravity=0.0035651792f; +real sound_gain_under_dialog=.7f; +struct cheat_globals cheat; +real object_light_ambient_base=.03f,object_light_ambient_scale=1.0f; +boolean loud_dialog_hack,ignore_player; +static real model_ambient=.2f; +short const hs_external_global_count=9; +static struct hs_external_global_definition globals[9]={{"sound_gain_under_dialog",_hs_type_real,0,&sound_gain_under_dialog}, + {"cheat_infinite_ammo",_hs_type_boolean,0,&cheat.infinite_ammo},{"unsafe",_hs_type_real,0,NULL}, + {"object_light_ambient_base",_hs_type_real,0,&object_light_ambient_base}, + {"object_light_ambient_scale",_hs_type_real,0,&object_light_ambient_scale}, + {"loud_dialog_hack",_hs_type_boolean,0,&loud_dialog_hack}, + {"ai_debug_ignore_player",_hs_type_boolean,0,&ignore_player}, + {"rasterizer_screen_flashes",_hs_type_boolean,0,&screen_flashes}, + {"rasterizer_model_lighting_ambient",_hs_type_real,0,&model_ambient}}; +short hs_find_global_by_name(char const *name) {return !strcmp(name,"ai_debug_ignore_player") ? (short)0x8006 : + !strcmp(name,"rasterizer_screen_flashes") ? (short)0x8007 : + !strcmp(name,"rasterizer_model_lighting_ambient") ? (short)0x8008 : NONE;} +struct hs_external_global_definition *hs_global_external_get(short index) {return &globals[index];} +void *csmemset(void *p,long c,unsigned long n) {return memset(p,c,n);} +void *csmemcpy(void *p,void const *q,unsigned long n) {return memcpy(p,q,n);} +long csstrcasecmp(char const *a,char const *b) {return _stricmp(a,b);} +long csstrcmp(char const *a,char const *b) {return strcmp(a,b);} +unsigned long csstrlen(char const *s) {return (unsigned long)strlen(s);} +void error(short p,char const *f,...) {(void)p;(void)f;} +boolean mcc_cache_tags_loaded(void) {return loaded;} +short game_connection(void) {return connection;} +long game_time_get(void) {return 123;} +long distributed_latest_host_time(void) {return 456;} +struct scenario *global_scenario_get(void) {return &scenario;} +long local_player_get_player_index(short local) {return local==0 ? 0 : local==1 ? 2 : NONE;} +void *datum_try_and_get(struct data_array *data,long index) { + if(data==&player_array)return index>=0&&index<3 ? players+index : NULL; + if(data==&list_array)return index==8 ? &list_array : NULL; + return NULL; +} +void *object_try_and_get_and_verify_type(long index,unsigned long mask) { + return index>=0&&index<3 && (mask&(1u<x=(real)index*4;p->y=p->z=0;return p;} +void unit_get_head_position(long index,real_point3d *p) {object_get_origin(index,p);} +short hud_get_nav_point_render_type(short local,real_point3d const *h,real_point3d const *p,long ref) { + (void)local;(void)h;(void)p;(void)ref;return 0; +} +void custom_render_nav_point(short local,real_point3d const *p,short arrow,short type) { + (void)local;(void)arrow;(void)type;draws++;drawn=*p; +} +static int list_failure; +long object_list_new(void) {count=0;return list_failure ? NONE : 8;} +long data_next_index(struct data_array *data,long index) {(void)data;return index<2 ? index+1 : NONE;} +void object_list_add(long list,long object) {(void)list;added[count++]=object;} +long object_list_get_first(long list,long *cursor) {(void)list;*cursor=0;return 0;} +long object_list_get_next(long list,long *cursor) {(void)list;return ++*cursor==1 ? 2 : NONE;} +boolean hs_macro_function_parse(short f,long x) {(void)f;(void)x;return TRUE;} +boolean hs_parse(long x,short type) {(void)x;(void)type;return TRUE;} +long *hs_macro_function_evaluate(short f,long t,boolean initialize) { + (void)t; + /* The real interpreter rejects a zero-byte argument stack allocation. */ + if(!mcc_campaign_function(f)->parameter_count)abort(); + return initialize ? args : NULL; +} +void hs_return(long thread,long value) {(void)thread;result=value;} +void mcc_sleep_forever_evaluate(short f,long t,boolean i) {(void)f;(void)t;(void)i;} +void mcc_script_finished_evaluate(short f,long t,boolean i) {(void)f;(void)t;(void)i;} +static long bits(real n) {union {real n;long b;} u;u.n=n;return u.b;} +static real number(long b) {union {real n;long b;} u;u.b=b;return u.n;} +static void call(char const *name) { + short id=mcc_campaign_find(name); + struct hs_function_definition *definition=mcc_campaign_function(id); + if(!definition)exit(3); + definition->evaluate(id,0,TRUE); +} +int main(int argc,char **argv) { + unsigned char saved[MCC_CAMPAIGN_SNAPSHOT_BYTES],bad[MCC_CAMPAIGN_SNAPSHOT_BYTES]; + real original=global_gravity; + int i; + CHECK(argc==2); + for(i=0;i<3;i++){players[i].unit_index=i;players[i].team_index=1;units[i].object.bounding_sphere_center.x=(real)i*4;} + hud.waypoint.arrows.count=2;hud.waypoint.arrow_bitmap.index=1; + scenario.cutscene_flags.address=flags;scenario.cutscene_flags.count=2; + flags[1].position.x=10; + mcc_campaign_begin(); + if(!strcmp(argv[1],"model_ambient")) { + CHECK(mcc_campaign_global_settable(8)); + loaded=0;CHECK(!mcc_campaign_global_settable(8));loaded=1; + model_ambient=.1f;mcc_campaign_snapshot(saved); + CHECK(mcc_campaign_validate(saved,sizeof(saved))); + model_ambient=0;CHECK(mcc_campaign_restore(saved,sizeof(saved)));CHECK(model_ambient==.1f); + connection=_game_connection_network_client; + model_ambient=0;CHECK(mcc_campaign_restore(saved,sizeof(saved)));CHECK(model_ambient==.1f); + memcpy(bad,saved,sizeof(saved));bad[0]=5; + CHECK(mcc_campaign_restore(bad,MCC_CAMPAIGN_SNAPSHOT_V5_BYTES));CHECK(model_ambient==.2f); + CHECK(!mcc_campaign_restore(bad,sizeof(bad))); + memcpy(bad,saved,sizeof(saved));*(unsigned long *)(bad+MCC_CAMPAIGN_SNAPSHOT_V5_BYTES)=0x7fc00000UL; + CHECK(!mcc_campaign_restore(bad,sizeof(bad))); + *(unsigned long *)(bad+MCC_CAMPAIGN_SNAPSHOT_V5_BYTES)=0x7f800000UL; + CHECK(!mcc_campaign_restore(bad,sizeof(bad))); + model_ambient=.3f;loaded=0;mcc_campaign_reset_model_lighting();CHECK(model_ambient==.3f); + loaded=1;mcc_campaign_reset_model_lighting();CHECK(model_ambient==.2f); + mcc_campaign_begin();CHECK(model_ambient==.2f); + model_ambient=.3f;mcc_campaign_dispose();CHECK(model_ambient==.2f); + CHECK(!mcc_campaign_restore(saved,sizeof(saved))); + return 0; + } + if(!strcmp(argv[1],"music")) { + CHECK(mcc_campaign_mix_gain(TRUE)==1); + args[0]=bits(.25f);call("sound_set_music_gain"); + CHECK(mcc_campaign_mix_gain(TRUE)==.25f && mcc_campaign_mix_gain(FALSE)==1); + mcc_campaign_snapshot(saved);CHECK(mcc_campaign_validate(saved,sizeof(saved))); + mcc_campaign_begin();CHECK(mcc_campaign_mix_gain(TRUE)==1); + connection=_game_connection_network_client; + CHECK(mcc_campaign_restore(saved,sizeof(saved))); + args[0]=bits(.75f);call("sound_set_music_gain");CHECK(mcc_campaign_mix_gain(TRUE)==.25f); + connection=_game_connection_local; + args[0]=0x7fc00000;call("sound_set_music_gain");CHECK(mcc_campaign_mix_gain(TRUE)==.25f); + args[0]=0x7f800000;call("sound_set_music_gain");CHECK(mcc_campaign_mix_gain(TRUE)==.25f); + args[0]=bits(-1);call("sound_set_music_gain");CHECK(mcc_campaign_mix_gain(TRUE)==.25f); + args[0]=bits(1.01f);call("sound_set_music_gain");CHECK(mcc_campaign_mix_gain(TRUE)==.25f); + memcpy(bad,saved,sizeof(bad));bad[767]=0x7f;CHECK(!mcc_campaign_validate(bad,sizeof(bad))); + memcpy(bad,saved,sizeof(bad));bad[0]=4;CHECK(!mcc_campaign_validate(bad,sizeof(bad))); + CHECK(mcc_campaign_restore(bad,MCC_CAMPAIGN_SNAPSHOT_V4_BYTES));CHECK(mcc_campaign_mix_gain(TRUE)==1); + args[0]=bits(0);call("sound_set_music_gain");CHECK(mcc_campaign_mix_gain(TRUE)==0); + args[0]=bits(1);call("sound_set_music_gain");CHECK(mcc_campaign_mix_gain(TRUE)==1); + args[0]=0;call("sound_enable");CHECK(mcc_campaign_mix_gain(TRUE)==0); + args[0]=1;call("sound_enable");CHECK(mcc_campaign_mix_gain(TRUE)==1); + loaded=FALSE;args[0]=bits(.5f);call("sound_set_music_gain");CHECK(mcc_campaign_mix_gain(TRUE)==1); + loaded=TRUE;CHECK(mcc_campaign_mix_gain(TRUE)==1); + mcc_campaign_dispose();CHECK(mcc_campaign_mix_gain(TRUE)==1); + } else if(!strcmp(argv[1],"team_players")) { + args[0]=1;call("players_on_multiplayer_team");CHECK(result==8 && count==3); + units[1].object.damage_flags=1u<<_object_dead_bit; + players[2].team_index=0;call("players_on_multiplayer_team");CHECK(count==1 && added[0]==0); + args[0]=0;call("players_on_multiplayer_team");CHECK(count==1 && added[0]==2); + players[2].unit_index=NONE;call("players_on_multiplayer_team");CHECK(count==0); + args[0]=1;players[0].quit_out_of_game=TRUE;call("players_on_multiplayer_team");CHECK(count==0); + args[0]=-1;call("players_on_multiplayer_team");CHECK(count==0); + args[0]=HALO_PORT_MAXIMUM_NETWORK_PLAYERS;call("players_on_multiplayer_team");CHECK(count==0); + args[0]=1;players[0].quit_out_of_game=FALSE;loaded=FALSE; + call("players_on_multiplayer_team");CHECK(count==0); + loaded=TRUE;connection=_game_connection_network_client; + call("players_on_multiplayer_team");CHECK(count==1); + list_failure=1;call("players_on_multiplayer_team");CHECK(result==NONE && count==0); + } else if(!strcmp(argv[1],"flashlight")) { + units[0].object.type=_object_type_biped; + args[0]=0;call("unit_get_current_flashlight_state");CHECK(!result); + SET_FLAG(units[0].unit.flags,_unit_integrated_light_on_bit,TRUE); + call("unit_get_current_flashlight_state");CHECK(result); + args[0]=NONE;call("unit_get_current_flashlight_state");CHECK(!result); + args[0]=0x12340000;call("unit_get_current_flashlight_state");CHECK(!result); + args[0]=0;units[0].object.type=_object_type_weapon; + call("unit_get_current_flashlight_state");CHECK(!result); + } else if(!strcmp(argv[1],"cooperative")) { + call("game_is_cooperative");CHECK(!result); + local_coop=TRUE;call("game_is_cooperative");CHECK(result); + local_coop=FALSE;online_coop=TRUE;call("game_is_cooperative");CHECK(result); + online_coop=FALSE;connection=_game_connection_network_server; + call("game_is_cooperative");CHECK(!result); + } else if(!strcmp(argv[1],"fades")) { + CHECK(mcc_campaign_global_settable(7));CHECK(!mcc_campaign_fade_active()); + fade_ticks=0;fading_out=TRUE;CHECK(mcc_campaign_fade_active()); + screen_flashes=FALSE;CHECK(mcc_campaign_fade_active()); + mcc_campaign_snapshot(saved);CHECK(mcc_campaign_validate(saved,sizeof(saved))); + mcc_campaign_begin();CHECK(screen_flashes); + connection=_game_connection_network_client; + CHECK(mcc_campaign_restore(saved,sizeof(saved)));CHECK(!screen_flashes); + fading_out=FALSE;fade_start=100;fade_ticks=30;CHECK(mcc_campaign_fade_active()); + fade_ticks=20;CHECK(!mcc_campaign_fade_active()); + fade_ticks=NONE;CHECK(!mcc_campaign_fade_active()); + memcpy(bad,saved,sizeof(bad));bad[0]=3;CHECK(!mcc_campaign_validate(bad,sizeof(bad))); + bad[13]&=~8;CHECK(mcc_campaign_restore(bad,MCC_CAMPAIGN_SNAPSHOT_V4_BYTES));CHECK(screen_flashes); + mcc_campaign_dispose();CHECK(screen_flashes && !mcc_campaign_fade_active()); + screen_flashes=FALSE;mcc_campaign_begin();screen_flashes=TRUE;mcc_campaign_dispose();CHECK(!screen_flashes); + loaded=FALSE;CHECK(!mcc_campaign_global_settable(7)); + } else if(!strcmp(argv[1],"unit_kill")) { + char const *names[2]={"unit_kill","unit_kill_silent"}; + for(i=0;i<2;i++) { + short id=mcc_campaign_find(names[i]); + struct hs_function_definition *definition=mcc_campaign_function(id); + CHECK(definition && definition->parameter_count==1 && + definition->parameter_types[0]==_hs_type_unit && definition->return_type==_hs_type_void); + args[0]=NONE;call(names[i]);CHECK(!kills && !silent_kills && result==0); + args[0]=0x10000;call(names[i]);CHECK(!kills && !silent_kills); + units[0].object.type=_object_type_scenery; + args[0]=0;call(names[i]);CHECK(!kills && !silent_kills); + units[0].object.type=_object_type_biped; + result=123;definition->evaluate(id,0,FALSE);CHECK(result==123 && !kills && !silent_kills); + loaded=FALSE;call(names[i]);CHECK(!kills && !silent_kills);loaded=TRUE; + connection=_game_connection_network_client;call(names[i]);CHECK(!kills && !silent_kills); + connection=_game_connection_local;call(names[i]);CHECK(kills+silent_kills==1); + connection=_game_connection_network_server; + units[0].object.type=_object_type_vehicle;call(names[i]); + CHECK(kills==(i==0 ? 2 : 0) && silent_kills==(i==1 ? 2 : 0)); + kills=silent_kills=0; + } + } else if(!strcmp(argv[1],"object_predict")) { + actor_variant.unit_reference.index=20; + args[0]=19;call("object_type_predict");CHECK(predicted_tag==20); + predicted_tag=NONE;actor_variant.unit_reference.index=19; + call("object_type_predict");CHECK(predicted_tag==NONE); + args[0]=123;call("object_type_predict");CHECK(predicted_tag==NONE); + args[0]=NONE;call("object_type_predict");CHECK(predicted_tag==NONE); + args[0]=20;call("object_type_predict");CHECK(predicted_tag==20); + predicted_tag=NONE;loaded=FALSE;call("object_type_predict");CHECK(predicted_tag==NONE); + } else if(!strcmp(argv[1],"script_effects")) { + CHECK(mcc_script_effect_global("cheat_jetpack")); + CHECK(!mcc_script_effect_global("cheat_controller")); + cheat.jetpack=TRUE;cheat.super_jump=TRUE;cheat.bottomless_clip=TRUE; + cheat.bump_possession=TRUE;cheat.medusa=TRUE;cheat.omnipotent=TRUE; + cheat.deathless_player=TRUE;cheat.infinite_ammo=TRUE; + CHECK(mcc_script_effects_snapshot()==MCC_EFFECT_MASK); + CHECK(mcc_script_effects_host_movement()); + mcc_campaign_snapshot(saved); + CHECK(mcc_campaign_validate(saved,sizeof(saved))); + mcc_campaign_begin();CHECK(!mcc_script_effects_snapshot()); + CHECK(mcc_campaign_restore(saved,sizeof(saved))); + CHECK(cheat.jetpack && cheat.omnipotent); + connection=_game_connection_network_client; + memset(&cheat,0,sizeof(cheat)); + CHECK(mcc_campaign_restore(saved,sizeof(saved))); + CHECK(!cheat.jetpack && !cheat.bottomless_clip && !cheat.medusa); + CHECK(mcc_campaign_unlimited_ammo() && !cheat.infinite_ammo); + CHECK(mcc_script_effect_enabled(MCC_EFFECT_JETPACK)); + CHECK(mcc_script_effect_enabled(MCC_EFFECT_BOTTOMLESS_CLIP)); + call("cheat_all_vehicles");CHECK(!vehicle_spawns); + CHECK(mcc_script_effects_bump(0,1));CHECK(!possessions); + memcpy(bad,saved,sizeof(saved));bad[0]=2; + CHECK(!mcc_campaign_validate(bad,sizeof(bad))); + memcpy(bad,saved,sizeof(saved));bad[13]|=16; + CHECK(!mcc_campaign_restore(bad,sizeof(bad))); + CHECK(mcc_script_effects_snapshot()==MCC_EFFECT_MASK); + loaded=FALSE;CHECK(!mcc_script_effect_enabled(MCC_EFFECT_JETPACK)); + CHECK(!mcc_script_effect_global("cheat_jetpack")); + CHECK(!mcc_script_effects_bump(0,1)); + call("cheat_all_vehicles");CHECK(!vehicle_spawns); + loaded=TRUE;connection=_game_connection_network_server; + call("cheat_all_vehicles");CHECK(vehicle_spawns==1); + mcc_campaign_dispose();CHECK(!mcc_script_effects_snapshot() && !cheat.jetpack); + call("cheat_all_vehicles");CHECK(vehicle_spawns==1); + } else if(!strcmp(argv[1],"possession")) { + cheat.bump_possession=TRUE; + units[0].unit.player_index=0;units[1].unit.player_index=NONE; + units[0].object.parent_object_index=units[1].object.parent_object_index=NONE; + players[0].local_player_index=NONE; + connection=_game_connection_network_server; + CHECK(mcc_script_effects_bump(0,123));CHECK(!possessions); + units[1].unit.player_index=1; + CHECK(mcc_script_effects_bump(0,1));CHECK(!possessions); + units[1].unit.player_index=NONE;units[1].object.damage_flags=1u<<_object_dead_bit; + CHECK(mcc_script_effects_bump(0,1));CHECK(!possessions); + units[1].object.damage_flags=0;units[1].object.parent_object_index=2; + CHECK(mcc_script_effects_bump(0,1));CHECK(!possessions); + units[1].object.parent_object_index=NONE; + CHECK(mcc_script_effects_bump(0,1));CHECK(possessions==1); + CHECK(players[0].unit_index==1 && units[0].unit.player_index==NONE); + CHECK(units[1].unit.player_index==0 && units[1].biped.bump_ticks==-15); + CHECK(!units[0].object.damage_flags); + CHECK(mcc_script_effects_preserve_body()); + loaded=FALSE;CHECK(!mcc_script_effects_preserve_body()); + } else if(!strcmp(argv[1],"cinematic_abort")) { + short id=mcc_campaign_find("cinematic_abort"); + struct hs_function_definition *definition=mcc_campaign_function(id); + CHECK(definition && definition->return_type==_hs_type_void && !definition->parameter_count); + connection=_game_connection_network_client; + definition->evaluate(id,1,FALSE);CHECK(!cinematic_skips); + connection=_game_connection_network_client;call("cinematic_abort");CHECK(!cinematic_skips); + connection=_game_connection_local;loaded=FALSE;call("cinematic_abort");CHECK(!cinematic_skips); + loaded=TRUE;call("cinematic_abort");CHECK(cinematic_skips==1 && result==0); + connection=_game_connection_network_server;call("cinematic_abort");CHECK(cinematic_skips==2); + } else + if(!strcmp(argv[1],"oct11")) { + args[0]=8;call("list_count_not_dead");CHECK(result==2); + units[2].object.damage_flags=1u<<_object_dead_bit; + call("list_count_not_dead");CHECK(result==1); + args[0]=NONE;call("list_count_not_dead");CHECK(result==0); + args[0]=1234;call("list_count_not_dead");CHECK(result==0); + call("game_time_authoritative");CHECK(result==123); + connection=_game_connection_network_client;call("game_time_authoritative");CHECK(result==456); + args[0]=bits(.1f);call("sound_set_effects_gain");CHECK(mcc_campaign_effects_gain()==1); + connection=_game_connection_local;call("sound_set_effects_gain"); + call("sound_get_effects_gain");CHECK(number(result)==.1f); + mcc_campaign_snapshot(saved);mcc_campaign_begin();CHECK(mcc_campaign_effects_gain()==1); + CHECK(mcc_campaign_restore(saved,sizeof(saved)));CHECK(mcc_campaign_effects_gain()==.1f); + args[0]=0x7fc00000;call("sound_set_effects_gain");CHECK(mcc_campaign_effects_gain()==.1f); + args[0]=bits(-1);call("sound_set_effects_gain");CHECK(mcc_campaign_effects_gain()==.1f); + memcpy(bad,saved,sizeof(saved));bad[0]=1; + CHECK(mcc_campaign_restore(bad,MCC_CAMPAIGN_SNAPSHOT_V1_BYTES));CHECK(mcc_campaign_effects_gain()==1); + loaded=FALSE;CHECK(mcc_campaign_effects_gain()==1); + } else if(!strcmp(argv[1],"bits")) { + struct hs_function_definition *f; + args[0]=6;args[1]=3;call("bitwise_and");CHECK(result==2); + call("bitwise_or");CHECK(result==7); + args[0]=-1;args[1]=1;call("bitwise_right_shift");CHECK(result==0x7fffffff); + args[0]=1;args[1]=31;call("bitwise_left_shift");CHECK((unsigned long)result==0x80000000UL); + args[1]=-1;call("bitwise_left_shift");CHECK(result==0); + call("bitwise_right_shift");CHECK(result==0); + args[1]=32;call("bitwise_left_shift");CHECK(result==1); + args[0]=0;args[1]=31;args[2]=(long)0xffffff01;call("bit_toggle");CHECK((unsigned long)result==0x80000000UL); + args[0]=result;call("bit_test");CHECK(result==1); + args[2]=(long)0xffffff00;call("bit_toggle");CHECK(result==0); + args[0]=7;args[1]=-1;args[2]=1;call("bit_toggle");CHECK(result==7); + call("bit_test");CHECK(result==0); + f=mcc_campaign_function(mcc_campaign_find("bit_toggle")); + CHECK(f->return_type==_hs_type_long_integer && f->parameter_count==3 && + f->parameter_types[1]==_hs_type_short_integer && f->parameter_types[2]==_hs_type_boolean); + result=123;f->evaluate(mcc_campaign_find("bit_toggle"),0,FALSE);CHECK(result==123); + args[0]=8;args[1]=1;call("objects_distance_to_flag");CHECK(number(result)==2.0f); + args[1]=NONE;call("objects_distance_to_flag");CHECK(number(result)==-1.0f); + } else if(!strcmp(argv[1],"abs_real")) { + struct hs_function_definition *definition=mcc_campaign_function(mcc_campaign_find("abs_real")); + CHECK(definition && definition->return_type==_hs_type_real && definition->parameter_count==1); + args[0]=bits(-3.5f);call("abs_real");CHECK(number(result)==3.5f); + args[0]=bits(3.5f);call("abs_real");CHECK(number(result)==3.5f); + args[0]=(long)0x80000000;call("abs_real");CHECK(result==0); + args[0]=0;call("abs_real");CHECK(result==0); + args[0]=(long)0xff800000;call("abs_real");CHECK(result==0x7f800000); + result=123;definition->evaluate(mcc_campaign_find("abs_real"),0,FALSE);CHECK(result==123); + } else if(!strcmp(argv[1],"print_predict")) { + args[1]=(long)"100% literal";args[0]=(long)0xffffff00;call("print_if");CHECK(!printed); + args[0]=1;call("print_if");CHECK(printed==1); + sound.pitch_ranges.count=2;sound.pitch_ranges.address=ranges; + ranges[0].permutations.count=1;ranges[0].permutations.address=permutations; + ranges[1].permutations.count=2;ranges[1].permutations.address=permutations+1; + args[0]=17;args[1]=0;call("sound_impulse_predict");CHECK(requests==3 && !blocks); + args[1]=(long)0xffffff01;call("sound_impulse_predict");CHECK(requests==6 && blocks==3); + args[0]=NONE;call("sound_impulse_predict");CHECK(requests==6); + } else if(!strcmp(argv[1],"players")) { + call("local_players");CHECK(result==8&&count==2&&added[0]==0&&added[1]==2); + units[2].object.damage_flags=1u<<_object_dead_bit; + call("local_players");CHECK(count==1&&added[0]==0); + players[0].unit_index=NONE;call("local_players");CHECK(count==0); + connection=_game_connection_local;call("game_is_authoritative");CHECK(result); + connection=_game_connection_network_server;call("game_is_authoritative");CHECK(result); + connection=_game_connection_network_client;call("game_is_authoritative");CHECK(!result); + } else if(!strcmp(argv[1],"distance")) { + args[0]=8;args[1]=bits(5);args[2]=args[3]=bits(0);call("objects_distance_to_position");CHECK(number(result)==3); + args[0]=NONE;call("objects_distance_to_position");CHECK(number(result)==-1); + args[0]=8;args[1]=0x7fc00000;call("objects_distance_to_position");CHECK(number(result)==-1); + } else if(!strcmp(argv[1],"gravity")) { + args[0]=bits(.25f);call("physics_set_gravity");CHECK(global_gravity==original*.25f); + mcc_campaign_snapshot(saved); + call("physics_constants_reset");CHECK(global_gravity==original); + CHECK(mcc_campaign_restore(saved,sizeof(saved)));CHECK(global_gravity==original*.25f); + args[0]=0x7fc00000;call("physics_set_gravity");CHECK(global_gravity==original*.25f); + connection=_game_connection_network_client;args[0]=bits(2);call("physics_set_gravity");CHECK(global_gravity==original*.25f); + mcc_campaign_begin();CHECK(global_gravity==original); + connection=_game_connection_local;args[0]=bits(2);call("physics_set_gravity");mcc_campaign_dispose();CHECK(global_gravity==original); + loaded=FALSE;CHECK(!mcc_campaign_restore(saved,sizeof(saved))); + mcc_campaign_dispose();CHECK(global_gravity==original); + } else if(!strcmp(argv[1],"controls")) { + sound_gain_under_dialog=.35f;cheat.infinite_ammo=TRUE;mcc_campaign_snapshot(saved); + sound_gain_under_dialog=.88f;cheat.infinite_ammo=FALSE; + CHECK(mcc_campaign_restore(saved,sizeof(saved)) && sound_gain_under_dialog==.35f && cheat.infinite_ammo); + connection=_game_connection_network_client;cheat.infinite_ammo=FALSE; + CHECK(mcc_campaign_restore(saved,sizeof(saved)) && !cheat.infinite_ammo); + mcc_campaign_dispose();CHECK(sound_gain_under_dialog==.7f && !cheat.infinite_ammo); + } else if(!strcmp(argv[1],"navigation")) { + call("breadcrumbs_nav_points_active");CHECK(result==TRUE); + args[0]=0;args[1]=1;args[2]=bits(1);args[3]=bits(2);args[4]=bits(3);args[5]=(long)"test";args[6]=bits(.5f); + call("breadcrumbs_activate_team_nav_point_position");mcc_campaign_render(0);CHECK(draws==1&&drawn.x==1&&drawn.z==3.5f); + mcc_campaign_snapshot(saved); + args[0]=1;args[1]=(long)"test";call("breadcrumbs_deactivate_team_nav_point");draws=0;mcc_campaign_render(0);CHECK(!draws); + CHECK(mcc_campaign_restore(saved,sizeof(saved)));mcc_campaign_render(1);CHECK(draws==1); + players[2].team_index=2;draws=0;mcc_campaign_render(1);CHECK(!draws); + mcc_campaign_begin();args[0]=0;args[1]=1;args[2]=1;args[3]=bits(1); + call("breadcrumbs_activate_team_nav_point_flag");mcc_campaign_render(0);CHECK(draws==1&&drawn.x==10&&drawn.z==1); + args[0]=1;args[1]=1;call("breadcrumbs_deactivate_team_nav_point_flag");draws=0;mcc_campaign_render(0);CHECK(!draws); + args[0]=0;args[1]=1;args[2]=2;args[3]=bits(0);call("breadcrumbs_activate_team_nav_point_object"); + mcc_campaign_render(0);CHECK(draws==1&&drawn.x==8); + units[2].object.damage_flags=1u<<_object_dead_bit;draws=0;mcc_campaign_render(0);CHECK(!draws); + units[2].object.damage_flags=0;args[0]=1;args[1]=2;call("breadcrumbs_deactivate_team_nav_point_object");mcc_campaign_render(0);CHECK(!draws); + loaded=FALSE;mcc_campaign_render(0);CHECK(!draws); + } else if(!strcmp(argv[1],"mute_restart")) { + CHECK(mcc_campaign_mix_gain(FALSE)==1 && mcc_campaign_mix_gain(TRUE)==1); + args[0]=bits(.25f);call("sound_set_effects_gain"); + args[0]=0;call("sound_enable"); + CHECK(mcc_campaign_mix_gain(FALSE)==0 && mcc_campaign_mix_gain(TRUE)==0); + CHECK(mcc_campaign_effects_gain()==.25f); + mcc_campaign_snapshot(saved);mcc_campaign_begin();CHECK(mcc_campaign_mix_gain(TRUE)==1); + connection=_game_connection_network_client; + CHECK(mcc_campaign_restore(saved,sizeof(saved))); + args[0]=1;call("sound_enable");CHECK(mcc_campaign_mix_gain(TRUE)==0); + call("map_reset");CHECK(!restarts && !network_restarts); + connection=_game_connection_network_server;call("map_reset");CHECK(network_restarts==1 && !restarts); + connection=_game_connection_local;call("map_reset");CHECK(restarts==1); + call("sound_enable");CHECK(mcc_campaign_mix_gain(TRUE)==1 && mcc_campaign_mix_gain(FALSE)==.25f); + args[0]=0;call("sound_enable");mcc_campaign_dispose();CHECK(mcc_campaign_mix_gain(TRUE)==1); + loaded=FALSE;call("map_reset");CHECK(restarts==1); + } else if(!strcmp(argv[1],"weapons")) { + call("cheat_all_weapons");CHECK(weapon_spawns==1); + connection=_game_connection_network_client;call("cheat_all_weapons");CHECK(weapon_spawns==1); + connection=_game_connection_network_server;call("cheat_all_weapons");CHECK(weapon_spawns==2); + loaded=FALSE;call("cheat_all_weapons");CHECK(weapon_spawns==2); + loaded=TRUE;mcc_campaign_dispose();call("cheat_all_weapons");CHECK(weapon_spawns==2); + mcc_campaign_begin();call("cheat_all_weapons");CHECK(weapon_spawns==3); + } else if(!strcmp(argv[1],"validation")) { + mcc_campaign_snapshot(saved);CHECK(mcc_campaign_validate(saved,sizeof(saved))); + CHECK(!mcc_campaign_validate(saved,sizeof(saved)-1)); + memcpy(bad,saved,sizeof(saved));bad[0]=7;CHECK(!mcc_campaign_restore(bad,sizeof(bad))); + memcpy(bad,saved,sizeof(saved));bad[13]=16;CHECK(!mcc_campaign_restore(bad,sizeof(bad))); + memcpy(bad,saved,sizeof(saved));{long nan=0x7fc00000;memcpy(bad+4,&nan,4);}CHECK(!mcc_campaign_restore(bad,sizeof(bad))); + memcpy(bad,saved,sizeof(saved));bad[16]=4;CHECK(!mcc_campaign_restore(bad,sizeof(bad))); + CHECK(global_gravity==original); + CHECK(mcc_campaign_global_settable(0));CHECK(mcc_campaign_global_settable(1)); + CHECK(!mcc_campaign_global_settable(2));CHECK(!mcc_campaign_global_settable(9));CHECK(!mcc_campaign_global_settable(-1)); + for(i=3;i<7;i++) CHECK(mcc_campaign_global_settable((short)i)); + loaded=FALSE;CHECK(!mcc_campaign_global_settable(0)); + } else if(!strcmp(argv[1],"lighting_controls")) { + object_light_ambient_base=.6f;object_light_ambient_scale=.8f;loud_dialog_hack=TRUE;ignore_player=TRUE; + mcc_campaign_snapshot(saved);mcc_campaign_begin(); + CHECK(object_light_ambient_base==.03f && object_light_ambient_scale==1 && !loud_dialog_hack && !ignore_player); + connection=_game_connection_network_client; + CHECK(mcc_campaign_restore(saved,sizeof(saved))); + CHECK(object_light_ambient_base==.6f && object_light_ambient_scale==.8f && loud_dialog_hack && !ignore_player); + connection=_game_connection_local;CHECK(mcc_campaign_restore(saved,sizeof(saved)) && ignore_player); + memcpy(bad,saved,sizeof(saved));{long nan=0x7fc00000;memcpy(bad+756,&nan,4);} + CHECK(!mcc_campaign_restore(bad,sizeof(bad))); + mcc_campaign_dispose(); + CHECK(object_light_ambient_base==.03f && object_light_ambient_scale==1 && !loud_dialog_hack && !ignore_player); + } else return 2; + mcc_campaign_dispose();return 0; +} diff --git a/tools/harness/tests/mcc_change_colors.c b/tools/harness/tests/mcc_change_colors.c new file mode 100644 index 0000000000..ab00d83542 --- /dev/null +++ b/tools/harness/tests/mcc_change_colors.c @@ -0,0 +1,50 @@ +#include +#include +typedef float real; +typedef int boolean; +#define TRUE 1 +#define FALSE 0 +#define MIN(a,b) ((a)<(b)?(a):(b)) +#define PIN(x,a,b) ((x)<(a)?(a):(x)>(b)?(b):(x)) +#define TEST_FLAG(v,b) ((v)&(1u<<(b))) +#define _object_runtime_scaled_change_colors_bit 0 +#define NUMBER_OF_OBJECT_CHANGE_COLORS 4 +#define TAG_BLOCK_GET_ELEMENT(b,i,t) ((t *)(b)->address+(i)) +#define CHECK(x) do {if(!(x)){fprintf(stderr,"line %d: %s\n",__LINE__,#x);exit(1);}}while(0) +union real_rgb_color {struct {real red,green,blue;};}; +typedef union real_rgb_color real_rgb_color; +struct object_change_color_definition {short darken_by,scaled_by;unsigned long scale_flags;real_rgb_color color_lower_bound,color_upper_bound;}; +struct object_definition {struct {unsigned long runtime_flags;struct {long count;void *address;} change_colors;} object;}; +struct object_datum {long definition_index;struct {real_rgb_color outgoing_change_colors[4];real values[2];} object;}; +static struct object_definition definition; +static struct object_datum obj; +static int loaded=1,calls; +static int mcc_cache_tags_loaded(void){return loaded;} +static struct object_datum *object_get(long i){(void)i;return &obj;} +static struct object_definition *object_definition_get(long i){(void)i;return &definition;} +static void object_definition_data_error(long i,char const *msg){(void)i;(void)msg;CHECK(0);} +#define OBJECT_INCOMING_FUNCTION_GET_VALUE(o,i) ((o)->object.values[(i)-1]) +static void rgb_colors_interpolate(real_rgb_color *out,unsigned long flags,real_rgb_color const *lo,real_rgb_color const *hi,real f){ + (void)flags;calls++; + out->red=(1-f)*lo->red+f*hi->red;out->green=(1-f)*lo->green+f*hi->green;out->blue=(1-f)*lo->blue+f*hi->blue; +} +/* IMPLEMENTATION */ +int main(void){ + struct object_change_color_definition color={0,1,0,{ { .101961002f,.101961002f,1 } },{ { .309803993f,.309803993f,1 } }}; + int pass; + definition.object.runtime_flags=1;definition.object.change_colors.count=1;definition.object.change_colors.address=&color; + for(pass=0;pass<2;pass++){ + loaded=pass;calls=0;obj.object.values[0]=-.528170288f; + object_compute_change_colors(0); + CHECK(obj.object.outgoing_change_colors[0].red==0&&obj.object.outgoing_change_colors[0].blue==1); + CHECK(calls==!loaded); + } + /* Preserve extrapolation before darkening, rather than clamping the factor. */ + color.color_lower_bound.red=.2f;color.color_upper_bound.red=.8f;color.darken_by=2; + obj.object.values[0]=2;obj.object.values[1]=.5f;calls=0; + object_compute_change_colors(0); + CHECK(obj.object.outgoing_change_colors[0].red>.6999f&&obj.object.outgoing_change_colors[0].red<.7001f&&calls==0); + obj.object.values[0]=.5f;object_compute_change_colors(0);CHECK(calls==1); + color.scale_flags=1;obj.object.values[0]=2;object_compute_change_colors(0);CHECK(calls==2); + return 0; +} diff --git a/tools/harness/tests/mcc_environment_shader.c b/tools/harness/tests/mcc_environment_shader.c new file mode 100644 index 0000000000..a484a82339 --- /dev/null +++ b/tools/harness/tests/mcc_environment_shader.c @@ -0,0 +1,20 @@ +#include "cseries.h" +#include "mcc_environment_shader.h" +#include +static boolean loaded; +static int enabled; +boolean mcc_cache_tags_loaded(void) {return loaded;} +void mcc_environment_shader_set(int value) {enabled=value;} +#define CHECK(x) do {if (!(x)) {fprintf(stderr,"line %d\n",__LINE__);return 1;}} while (0) +int main(void) { + /* Xbox and CE must ignore an identical reserved flag. */ + mcc_environment_shader_begin(8);CHECK(!enabled); + loaded=TRUE;mcc_environment_shader_begin(8);CHECK(enabled); + mcc_environment_shader_end();CHECK(!enabled); + mcc_environment_shader_begin(0);CHECK(!enabled); + mcc_environment_shader_begin(9);CHECK(enabled); + mcc_environment_shader_begin(10);CHECK(!enabled); + mcc_environment_shader_begin(8);CHECK(enabled); + loaded=FALSE;mcc_environment_shader_begin(8);CHECK(!enabled); + return 0; +} diff --git a/tools/harness/tests/mcc_game_speed.c b/tools/harness/tests/mcc_game_speed.c new file mode 100644 index 0000000000..06bf0c5d72 --- /dev/null +++ b/tools/harness/tests/mcc_game_speed.c @@ -0,0 +1,69 @@ +#include "mcc_game_speed.h" +#include "game/game.h" +#include "hs/hs.h" +#include "hs/hs_scenario_definitions.h" +#include "scenario/scenario_definitions.h" +#include "network_distributed.h" +#include +#include +#include +#undef memcpy +#undef strcpy +void *csmemcpy(void *to,void const *from,unsigned long size) {return memcpy(to,from,size);} +char *csstrcpy(char *to,char const *from) {return strcpy(to,from);} + +#define CHECK(x) do { if (!(x)) { fprintf(stderr,"line %d: %s\n",__LINE__,#x);return 1; } } while (0) +static boolean active=TRUE; +static short connection=_game_connection_local; +static real native_speed=1.0f,sent_speed; +static unsigned long wall; +static unsigned messages; +static struct scenario scenario; +static struct hs_global globals[2]; +boolean mcc_cache_tags_loaded(void) {return active;} +short game_connection(void) {return connection;} +boolean game_in_progress(void) {return TRUE;} +real game_time_get_speed(void) {return connection==_game_connection_network_client ? mcc_game_speed_client(1.0f) : native_speed;} +void game_time_set_speed(real speed) {native_speed=speed;} +unsigned long system_milliseconds(void) {return wall;} +struct scenario *global_scenario_get(void) {return &scenario;} +long csstrcasecmp(char const *a,char const *b) {return _stricmp(a,b);} +void error(short priority,char const *format,...) {(void)priority;(void)format;} +void distributed_send(void *message,byte type,short count,word size,short destination) { + if(type!=_distributed_message_mcc_game_speed || count!=1 || + size!=sizeof(struct distributed_message_header)+4 || destination!=_distributed_to_clients_reliably) return; + memcpy(&sent_speed,(byte *)message+sizeof(struct distributed_message_header),4);messages++; +} +int main(void) { + real value;union {uint32_t bits;real number;} bad; + scenario.hs_globals.address=globals;scenario.hs_globals.count=2; + strcpy(globals[0].name,"game_speed_value");globals[0].type=_hs_type_real; + strcpy(globals[1].name,"other");globals[1].type=_hs_type_real; + CHECK(mcc_game_speed_global(0) && !mcc_game_speed_global(1) && !mcc_game_speed_global(2) && !mcc_game_speed_global(0x8000)); + mcc_game_speed_set(0.5f);CHECK(native_speed==0.5f); + mcc_game_speed_set(-1);CHECK(native_speed==0.5f); + bad.bits=0x7fc00000;mcc_game_speed_set(bad.number);CHECK(native_speed==0.5f); + bad.bits=0x7f800000;mcc_game_speed_set(bad.number);CHECK(native_speed==0.5f); + connection=_game_connection_network_server;native_speed=1;wall=1000;mcc_game_speed_reset(); + CHECK(mcc_game_speed_clock(wall)==1000); + wall+=1000;CHECK(mcc_game_speed_clock(wall)==2000); + mcc_game_speed_set(2);wall+=1000;CHECK(mcc_game_speed_clock(wall)==4000); + mcc_game_speed_set(0.5f);wall+=1000;CHECK(mcc_game_speed_clock(wall)==4500); + mcc_game_speed_frame();CHECK(messages==1 && sent_speed==0.5f); + mcc_game_speed_frame();CHECK(messages==1); + mcc_game_speed_set(0);mcc_game_speed_frame();CHECK(messages==2 && sent_speed==0); + wall+=250;mcc_game_speed_frame();CHECK(messages==3 && sent_speed==0); + mcc_game_speed_set(1);mcc_game_speed_frame();CHECK(messages==4 && sent_speed==1); + connection=_game_connection_network_client; + value=0.25f;mcc_game_speed_receive(&value,1);CHECK(game_time_get_speed()==0.25f); + mcc_game_speed_set(10);CHECK(native_speed==1 && game_time_get_speed()==0.25f); + mcc_game_speed_receive(&bad.number,1);CHECK(game_time_get_speed()==0.25f); + value=9;mcc_game_speed_receive(&value,0);CHECK(game_time_get_speed()==0.25f); + mcc_game_speed_frame();CHECK(messages==4); + active=FALSE;CHECK(game_time_get_speed()==1 && !mcc_game_speed_global(0)); + mcc_game_speed_set(3);CHECK(native_speed==1); + CHECK(mcc_game_speed_clock(12345)==12345); + mcc_game_speed_reset();active=TRUE;CHECK(game_time_get_speed()==1); + connection=_game_connection_local;value=2;mcc_game_speed_receive(&value,1);CHECK(native_speed==1); + return 0; +} diff --git a/tools/harness/tests/mcc_mods.c b/tools/harness/tests/mcc_mods.c new file mode 100644 index 0000000000..141cf42e5c --- /dev/null +++ b/tools/harness/tests/mcc_mods.c @@ -0,0 +1,57 @@ +#define _CRT_SECURE_NO_WARNINGS +#include "harness.h" + +static long updates; +static long releases; +static unsigned long scans; +#define csstrncpy strncpy +#define console_printf(...) ((void)0) +#define console_warning(...) ((void)0) +static long port_mods_scan(void) { return ++scans; } +static unsigned long port_mods_scans(void) { return scans; } +static boolean port_mods_played(void) { return TRUE; } +static long update(boolean remove_all, boolean at_load) +{ + if (!remove_all) ++updates; + return 1; +} +#define mod_strings_update update +#define mod_bitmaps_update update +#define mod_sounds_update update +#define mod_models_update update +static void mod_sounds_tags_unloaded(void) { ++releases; } +static void mod_bitmaps_tags_unloaded(void) {} +static void mod_models_tags_unloaded(boolean give_back) {} +static void mod_strings_tags_unloaded(void) {} +#include "under_test.inc" + +int main(int argc, char **argv) +{ + long before; + mods_tags_loaded("bloodgulch"); + CHECK(mods_map_loaded() && updates == 4, "Xbox mods apply"); + /* A load that never reached normal unload must still drop old overrides. */ + mods_tags_loaded("mcc_maps\\package\\bloodgulch"); + CHECK(!mods_map_loaded() && releases == 1, "MCC clears previous mods"); + before = updates; + mods_enable(TRUE); + mods_reload(); + mods_apply(); + CHECK(updates == before, "console and menu cannot enable MCC mods"); + mods_tags_unloaded(); + mods_tags_loaded("custom_maps\\deathisland"); + CHECK(mods_map_loaded() && updates == before + 4, "CE mods resume"); + mods_enable(FALSE); + before = updates; + mods_reload(); + CHECK(updates == before, "upstream manual disable preserved"); + mods_tags_loaded("MCC_MAPS/package/a10"); + CHECK(!mods_map_loaded(), "case and slash independent MCC exclusion"); + mods_enable(TRUE); + CHECK(updates == before, "disabled CE to MCC stays inactive"); + mods_tags_loaded("a10"); + CHECK(mods_map_loaded() && updates == before + 4, "Xbox mods resume without settings reset"); + mods_tags_unloaded(); + CHECK(!mods_map_loaded(), "unload clears eligibility"); + return 0; +} diff --git a/tools/harness/tests/mcc_movement.c b/tools/harness/tests/mcc_movement.c new file mode 100644 index 0000000000..406c1da4bb --- /dev/null +++ b/tools/harness/tests/mcc_movement.c @@ -0,0 +1,59 @@ +#include "cseries.h" +#include "units/units.h" +#include "items/weapons.h" +#include "items/weapon_definitions.h" +#include "mcc_movement.h" +#include +static boolean active; +static struct unit_datum unit; +static struct weapon_datum weapon; +static struct weapon_definition definition; +boolean mcc_cache_tags_loaded(void) {return active;} +void *object_try_and_get_and_verify_type(long index,unsigned long mask) { + if(index==1 && mask==_object_mask_unit)return &unit; + if(index==2 && mask==_object_mask_weapon)return &weapon; + return NULL; +} +void *tag_get(long group,long index) {return group==WEAPON_DEFINITION_TAG && index==3 ? &definition : NULL;} +#define CHECK(x) do {if(!(x)){fprintf(stderr,"line %d: %s\n",__LINE__,#x);return 1;}}while(0) +int main(void) { + real_vector3d v; + union {unsigned long bits;real number;} invalid; + unit.object.parent_object_index=NONE; + unit.unit.player_index=0;unit.unit.current_weapon_index=0; + unit.unit.weapon_object_indices[0]=2;unit.unit.current_zoom_level=NONE; + weapon.definition_index=3; + definition.weapon.forward_movement_penalty=.333f; + definition.weapon.sideways_movement_penalty=.5f; + v.i=1;v.j=-1;v.k=5;mcc_movement_apply(1,&v);CHECK(v.i==1 && v.j==-1 && v.k==5); + active=TRUE;mcc_movement_apply(1,&v);CHECK(v.i==1-.333f && v.j==-.5f && v.k==5); + definition.weapon.movement_penalty_mode=1; + v.i=-1;v.j=1;mcc_movement_apply(1,&v);CHECK(v.i==-1 && v.j==1); + unit.unit.current_zoom_level=0;mcc_movement_apply(1,&v);CHECK(v.i==-(1-.333f) && v.j==.5f); + definition.weapon.movement_penalty_mode=2;unit.unit.current_zoom_level=NONE; + weapon.weapon.magazines[1].state=_magazine_reloading; + v.i=1;v.j=1;mcc_movement_apply(1,&v);CHECK(v.i==1 && v.j==1); + unit.unit.current_zoom_level=0;mcc_movement_apply(1,&v);CHECK(v.i==1-.333f && v.j==.5f); + unit.unit.current_zoom_level=NONE;weapon.weapon.magazines[1].state=_magazine_idle; + v.i=1;v.j=1;mcc_movement_apply(1,&v);CHECK(v.i==1-.333f && v.j==.5f); + definition.weapon.movement_penalty_mode=0; + definition.weapon.forward_movement_penalty=0;definition.weapon.sideways_movement_penalty=.5f; + v.i=1;v.j=1;mcc_movement_apply(1,&v);CHECK(v.i==1 && v.j==.5f); + definition.weapon.forward_movement_penalty=2;definition.weapon.sideways_movement_penalty=1; + v.i=1;v.j=1;mcc_movement_apply(1,&v);CHECK(v.i==-1 && v.j==0); + invalid.bits=0x7fc00000;definition.weapon.forward_movement_penalty=invalid.number; + definition.weapon.sideways_movement_penalty=-10; + v.i=1;v.j=1;mcc_movement_apply(1,&v);CHECK(v.i==1 && v.j==1); + definition.weapon.forward_movement_penalty=1;definition.weapon.sideways_movement_penalty=1; + unit.unit.current_weapon_index=MAXIMUM_WEAPONS_PER_UNIT; + mcc_movement_apply(1,&v);CHECK(v.i==1 && v.j==1); + unit.unit.current_weapon_index=0;unit.unit.weapon_object_indices[0]=NONE; + mcc_movement_apply(1,&v);CHECK(v.i==1 && v.j==1); + unit.unit.weapon_object_indices[0]=2;unit.object.parent_object_index=12; + mcc_movement_apply(1,&v);CHECK(v.i==1 && v.j==1); + unit.object.parent_object_index=NONE;unit.unit.player_index=NONE; + mcc_movement_apply(1,&v);CHECK(v.i==1 && v.j==1); + unit.unit.player_index=0;active=FALSE; + mcc_movement_apply(1,&v);CHECK(v.i==1 && v.j==1); + return 0; +} diff --git a/tools/harness/tests/mcc_network.c b/tools/harness/tests/mcc_network.c new file mode 100644 index 0000000000..640cf5224d --- /dev/null +++ b/tools/harness/tests/mcc_network.c @@ -0,0 +1,156 @@ +#include +#include +#include +typedef unsigned char byte, boolean; +typedef unsigned short word; +typedef float real; +#define TRUE 1 +#define FALSE 0 +#define NONE (-1) +#define MIN(a,b) ((a)<(b)?(a):(b)) +#define MAX(a,b) ((a)>(b)?(a):(b)) +#define CHECK(c) do {if(!(c)){fprintf(stderr,"line %d: %s\n",__LINE__,#c);return 1;}}while(0) +#define csmemset memset +#define csmemcpy memcpy +#define DATUM_INDEX_TO_ABSOLUTE_INDEX(i) ((unsigned long)(i)&65535) +#define MAXIMUM_TRACKED_OBJECTS 16 +#define MAXIMUM_TRACKED_PLAYERS 4 +#define MAXIMUM_LOCAL_PLAYERS 1 +#define MAXIMUM_GRENADE_THROWS 8 +#define TICKS_PER_SECOND 30 +#define DATAGRAM_ENTRIES(t) 64 +#define _object_mask_unit 3 +#define _game_connection_network_server 1 +#define _game_connection_network_client 2 +/* MCC_CAMPAIGN_SIZE */ +#define _distributed_to_clients 0 +typedef word message_header; +/* DISTRIBUTED_HEADER */ +struct object_iterator {long index;int done;}; +struct unit_datum {struct {long player_index;} unit;}; +struct player_datum {long unit;}; +static long now=3; +static int active=1,connection=1,types=4,sends; +static long live_unit=(long)0xe0010001UL; +static short counts[4]={1,2,3,4}; +static struct unit_datum unit={{0}}; +static struct player_datum player; +static byte sent[1024]; +static short sent_count; +static word sent_size; +static int known=1; +static boolean local=0; +static real round_trip=6; +void mcc_object_names_network_reset(void) {} +void mcc_object_names_host_tick(void) {} +static int campaign_sends,campaign_restores; +static byte campaign_state[MCC_CAMPAIGN_SNAPSHOT_BYTES]; +boolean mcc_cache_tags_loaded(void) { return active; } +void mcc_campaign_snapshot(void *out) { memcpy(out,campaign_state,sizeof(campaign_state)); } +int mcc_campaign_restore(void const *in,unsigned long bytes) { + if(bytes!=sizeof(campaign_state))return 0; + memcpy(campaign_state,in,bytes);campaign_restores++;return 1; +} +short mcc_grenades_get(long index,short type) {return index==live_unit&&type>=0&&type=0&&typedone=0;it->index=live_unit;} +void *object_iterator_next(struct object_iterator *it){if(it->done++)return NULL;return &unit;} +boolean distributed_object_index_valid(long index){return ((unsigned long)index>>16)!=0 && index!=NONE;} +boolean network_objects_client_has(long index){return known&&index==live_unit;} +void *object_try_and_get_and_verify_type(long index,long mask){(void)mask;return index==live_unit?&unit:NULL;} +boolean distributed_player_is_local(long index){return index==0&&local;} +real distributed_own_round_trip_ticks(void){return round_trip;} +long local_player_get_player_index(short index){return index==0?0:NONE;} +struct player_datum *player_try_and_get(long index){return index==0?&player:NULL;} +long distributed_living_unit(struct player_datum const *p){return p?p->unit:NONE;} +void distributed_send(void *message,byte type,short count,word size,short destination){ + if(type==_distributed_message_mcc_campaign) { if(count==1&&size==sizeof(struct distributed_message_header)+MCC_CAMPAIGN_SNAPSHOT_BYTES)campaign_sends++;return; } + (void)destination;if(type!=_distributed_message_mcc_grenades||size>sizeof(sent))return; + memcpy(sent,message,size);sent_count=count;sent_size=size;sends++; +} +/* MCC_INVENTORY_IMPLEMENTATION */ + +struct tag_block {long count;void *address;}; +struct game_globals_grenade {struct {long index;} projectile;}; +struct game_globals {struct tag_block grenades;}; +struct damage_reach {real distance,ticks,carried_ticks;}; +static struct {long throw_times[MAXIMUM_GRENADE_THROWS];short throw_types[MAXIMUM_GRENADE_THROWS];} damage_players[MAXIMUM_TRACKED_PLAYERS]; +static struct game_globals globals; +static struct game_globals_grenade grenades[4]; +static int paid; +#define TAG_BLOCK_GET_ELEMENT(block,index,type) ((type *)(block)->address+(index)) +struct game_globals *scenario_get_game_globals(void){return &globals;} +short distributed_grenade_throw(short p,short type){short i;for(i=0;i<8;i++)if(damage_players[p].throw_times[i]!=NONE&&damage_players[p].throw_types[i]==type)return i;return NONE;} +boolean distributed_explosion_this_tick(short p,short type,void *point){(void)p;(void)type;(void)point;return paid;} +real distributed_source_deals(long projectile,long damage,boolean grenade,byte *kinds,struct damage_reach *reach){ + (void)grenade;*kinds=projectile==damage?2:0;reach->distance=8;reach->ticks=3;reach->carried_ticks=1;return projectile==damage?4:0; +} +void distributed_reach_combine(struct damage_reach *reach,struct damage_reach const *other){reach->distance=MAX(reach->distance,other->distance);} +/* MCC_DAMAGE_IMPLEMENTATION */ + +int main(int argc,char **argv){ + struct mcc_network_inventory packet; + int i; + CHECK(argc==2);player.unit=live_unit;mcc_network_new_game(); + memset(&packet,0,sizeof(packet));packet.unit=live_unit;packet.counts[0]=7;packet.counts[1]=8; + if(!strcmp(argv[1],"host")){ + mcc_network_host_tick();CHECK(sends==1&&sent_count==1&&sent_size==sizeof(struct distributed_message_header)+sizeof(packet)); + CHECK(((struct mcc_network_inventory *)(sent+sizeof(struct distributed_message_header)))->counts[0]==3); + now=6;mcc_network_host_tick();CHECK(sends==1); + counts[2]=2;mcc_network_host_tick();CHECK(sends==2); + now=36;mcc_network_host_tick();CHECK(sends==3); + active=0;now=66;mcc_network_host_tick();CHECK(sends==3); + }else if(!strcmp(argv[1],"receive")){ + connection=2;mcc_network_handle_inventories(&packet,1);CHECK(counts[2]==7&&counts[3]==8&&counts[0]==1&&counts[1]==2); + packet.counts[0]=128;mcc_network_handle_inventories(&packet,1);CHECK(counts[2]==7); + packet.counts[0]=4;packet.unit^=0x10000;mcc_network_handle_inventories(&packet,1);CHECK(counts[2]==7); + packet.unit=live_unit;packet.reserved[0]=1;mcc_network_handle_inventories(&packet,1);CHECK(counts[2]==7); + packet.reserved[0]=0;known=0;mcc_network_handle_inventories(&packet,1);CHECK(counts[2]==7); + }else if(!strcmp(argv[1],"prediction")){ + connection=2;local=1;mcc_network_client_tick(); + now=4;counts[2]=2;mcc_network_client_tick(); + mcc_network_handle_inventories(&packet,1);CHECK(counts[2]==2&&counts[3]==8); + now=16;mcc_network_handle_inventories(&packet,1);CHECK(counts[2]==7); + packet.counts[0]=1;mcc_network_handle_inventories(&packet,1);CHECK(counts[2]==1); + live_unit^=0x10000;packet.unit=live_unit;packet.counts[0]=6;mcc_network_handle_inventories(&packet,1);CHECK(counts[2]==6); + }else if(!strcmp(argv[1],"rewind_host")){ + now=300;mcc_network_host_tick();CHECK(sends==1); + now=303;mcc_network_host_tick();CHECK(sends==1); + now=30;mcc_network_host_tick();CHECK(sends==2); + now=33;mcc_network_host_tick();CHECK(sends==2); + }else if(!strcmp(argv[1],"rewind_client")){ + connection=2;local=1;now=300;mcc_network_client_tick(); + now=301;counts[2]=2;mcc_network_client_tick(); + mcc_network_handle_inventories(&packet,1);CHECK(counts[2]==2); + now=30;mcc_network_handle_inventories(&packet,1);CHECK(counts[2]==7); + now=31;counts[2]=6;mcc_network_client_tick(); + mcc_network_handle_inventories(&packet,1);CHECK(counts[2]==6); + now=43;mcc_network_handle_inventories(&packet,1);CHECK(counts[2]==7); + }else if(!strcmp(argv[1],"damage")){ + byte kinds=0;struct damage_reach reach={0,0,0};short type=NONE;real rate=0; + globals.grenades.count=4;globals.grenades.address=grenades;for(i=0;i<4;i++)grenades[i].projectile.index=100+i; + for(i=0;i<8;i++)damage_players[0].throw_times[i]=NONE; + mcc_network_note_extra_grenade(live_unit,4);CHECK(distributed_grenade_throw(0,4)==NONE); + mcc_network_note_extra_grenade(live_unit,2);CHECK(distributed_grenade_throw(0,2)!=NONE); + mcc_network_extra_grenade_damage(0,102,&kinds,&reach,&type,&rate);CHECK(rate==4&&type==2&&kinds==2&&reach.distance==8); + for(i=0;i<8;i++)damage_players[0].throw_times[i]=NONE; + rate=0;type=NONE;kinds=0;mcc_network_extra_grenade_damage(0,102,&kinds,&reach,&type,&rate);CHECK(rate==0&&type==NONE); + paid=1;mcc_network_extra_grenade_damage(0,102,&kinds,&reach,&type,&rate);CHECK(rate==4&&type==2); + connection=2;mcc_network_note_extra_grenade(live_unit,3);CHECK(distributed_grenade_throw(0,3)==NONE); + }else if(!strcmp(argv[1],"campaign")){ + types=2;mcc_network_host_tick();CHECK(campaign_sends==1&&sends==0); + mcc_network_handle_campaign(campaign_state,1);CHECK(campaign_restores==0); + connection=2;mcc_network_handle_campaign(campaign_state,0);mcc_network_handle_campaign(campaign_state,2); + CHECK(campaign_restores==0);mcc_network_handle_campaign(campaign_state,1);CHECK(campaign_restores==1); + active=0;mcc_network_handle_campaign(campaign_state,1);CHECK(campaign_restores==1); + connection=1;mcc_network_host_tick();CHECK(campaign_sends==1); + }else if(!strcmp(argv[1],"legacy")){ + active=0;mcc_network_host_tick();connection=2;mcc_network_client_tick();mcc_network_handle_inventories(&packet,1); + CHECK(sends==0&&campaign_sends==0&&counts[2]==3&&counts[3]==4&&counts[0]==1&&counts[1]==2); + }else return 2; + return 0; +} diff --git a/tools/harness/tests/mcc_object_names.c b/tools/harness/tests/mcc_object_names.c new file mode 100644 index 0000000000..641ec0e95c --- /dev/null +++ b/tools/harness/tests/mcc_object_names.c @@ -0,0 +1,225 @@ +#include +#include +#include +#include +#include "mcc_object_names.h" +typedef unsigned char byte,boolean; +#define TRUE 1 +typedef unsigned short word; +#define NONE (-1) +#define FALSE 0 +#define MAXIMUM_OBJECT_NAMES_PER_SCENARIO 512 +#define NUMBER_OF_OBJECT_TYPES 12 +#define MIN(a,b) ((a)<(b)?(a):(b)) +#define VALID_INDEX(i,n) ((i)>=0 && (i)<(n)) +#define TEST_FLAG(v,b) ((v)&(1u<<(b))) +#define _object_mask_biped 1 +#define _object_mask_vehicle 2 +#define _object_mask_weapon 4 +#define _object_mask_equipment 8 +#define _error_silent 0 +#define match_assert(a,b,c) do {if(!(c))abort();} while(0) +#define CHECK(c) do {if(!(c)){fprintf(stderr,"line %d: %s\n",__LINE__,#c);return 1;}}while(0) +enum {_game_connection_network_server=1,_game_connection_network_client=2,_distributed_to_clients=0}; +struct scenario_object_name {char name[32];short runtime_object_type;}; +static struct scenario_object_name definitions[32767]; +struct scenario {struct {long count;void *address;} object_names;}; +struct object_datum {long definition_index;struct {short name_index;long first_child_object_index,next_object_index;} object;}; +typedef word message_header; +/* DISTRIBUTED_HEADER */ +static struct scenario scenario; +static struct object_datum objects[8]; +static long legacy[512],*object_name_list=legacy; +static int loaded=1,connection=1,bsp=0,sends,created,deleted; +static long now=15; +static byte packets[64][72]; +#define TAG_BLOCK_GET_ELEMENT(b,i,t) ((t *)(b)->address+(i)) +static struct scenario *global_scenario_get(void){return &scenario;} +static int mcc_cache_tags_loaded(void){return loaded;} +static long game_time_get(void){return now;} +static short game_connection(void){return (short)connection;} +static short global_structure_bsp_index_get(void){return (short)bsp;} +static struct object_datum *object_get(long i){if(i<0||i>=8)abort();return objects+i;} +static long player_index_from_unit_index(long i){(void)i;return NONE;} +static char const *tag_get_name(long id){(void)id;return "object";} +static void error(int level,char const *fmt,...){(void)level;(void)fmt;} +static void distributed_send(void *msg,short type,short count,word size,short dest){ + if(type!=_distributed_message_mcc_object_names||count!=1||size!=sizeof(struct distributed_message_header)+sizeof(packets[0])||dest||sends>=64)abort(); + memcpy(packets[sends++],(byte *)msg+sizeof(struct distributed_message_header),72); +} +long object_index_from_name_index(short name); +static void object_name_list_new(long object,short name); +static void object_name_list_delete(long object); +static long object_new_by_name(short name){long id=++created;object_name_list_new(id,name);return id;} +static void object_delete(long object){deleted++;object_name_list_delete(object);} +/* IMPLEMENTATION */ + +/* Exercise the cache's actual cleanup order; other owners have no allocations + * in this names-only fixture. Failed preparation uses the same unload entry. */ +#define mcc_loaded loaded +static struct {void *tags;unsigned long capacity;} mcc_loaded_cache; +static FILE *mcc_stream; +#define mcc_validation_cancel() ((void)0) +#define mcc_cache_validation_clear() ((void)0) +#define mcc_cache_precache_clear() ((void)0) +#define mcc_hud_glyphs_dispose() ((void)0) +#define mcc_campaign_dispose() ((void)0) +#define mcc_ui_teams_reset() ((void)0) +#define mcc_script_threads_dispose() ((void)0) +#define mcc_checkpoint_dispose() ((void)0) +#define mcc_grenades_reset() ((void)0) +#define mcc_parameters_dispose() ((void)0) +#define mcc_texture_cache_dispose() ((void)0) +#define mcc_geometry_dispose(runtime) ((void)(runtime)) +#define mcc_audio_dispose(runtime) ((void)(runtime)) +#define mcc_bitmaps_dispose(runtime) ((void)(runtime)) +#define mcc_resources_dispose(runtime) ((void)(runtime)) +#define mcc_validation_dispose(runtime) ((void)(runtime)) +#define mcc_memory_release(address,capacity) ((void)(address),(void)(capacity)) +/* CACHE_UNLOAD */ + +static int snapshot_case(long count,int invalid) +{ + static byte saved[MCC_OBJECT_NAMES_SNAPSHOT_MAXIMUM+32]; + static byte live[MCC_OBJECT_NAMES_SNAPSHOT_MAXIMUM]; + unsigned long bytes=(unsigned long)count*4,i; + unsigned long wrong[4]; + long value,expected; + short last=(short)(count-1); + scenario.object_names.count=count; + object_name_list_clear(); + object_name_list_new(1,0);object_name_list_new(2,511);object_name_list_new(3,last); + object_set_object_index_for_name_index(1,4); + memset(saved,0xA5,sizeof(saved)); + CHECK(mcc_object_names_snapshot(NULL)==bytes); + CHECK(mcc_object_names_snapshot(saved+16)==bytes); + for(i=0;i<16;i++)CHECK(saved[i]==0xA5&&saved[16+bytes+i]==0xA5); + for(i=0;i<(unsigned long)count;i++){ + memcpy(&value,saved+16+i*4,4); + expected=i==0?1:i==1?4:i==511?2:i==(unsigned long)last?3:NONE; + CHECK(value==expected&&object_index_from_name_index((short)i)==expected); + } + if(invalid){ + /* A rejected older image must not replace any currently live mapping. */ + object_set_object_index_for_name_index(0,7); + CHECK(mcc_object_names_snapshot(live)==bytes); + wrong[0]=0;wrong[1]=bytes-1;wrong[2]=bytes+1;wrong[3]=MCC_OBJECT_NAMES_SNAPSHOT_MAXIMUM+4; + for(i=0;i<4;i++){ + CHECK(!mcc_object_names_validate(saved+16,wrong[i])); + CHECK(!mcc_object_names_restore(saved+16,wrong[i])); + } + CHECK(!mcc_object_names_validate(NULL,bytes)&&!mcc_object_names_restore(NULL,bytes)); + CHECK(!mcc_object_names_validate(NULL,0)&&!mcc_object_names_restore(NULL,0)); + CHECK(mcc_object_names_snapshot(saved+16)==bytes&&!memcmp(saved+16,live,bytes)); + CHECK(object_index_from_name_index(0)==7); + }else{ + object_name_list_clear(); + for(i=0;i<(unsigned long)count;i++)CHECK(object_index_from_name_index((short)i)==NONE); + CHECK(mcc_object_names_validate(saved+16,bytes)&&mcc_object_names_restore(saved+16,bytes)); + CHECK(mcc_object_names_snapshot(live)==bytes&&!memcmp(saved+16,live,bytes)); + CHECK(object_index_from_name_index(0)==1&&object_index_from_name_index(1)==4); + CHECK(object_index_from_name_index(511)==2&&object_index_from_name_index(last)==3); + } + for(i=0;i<16;i++)CHECK(saved[i]==0xA5&&saved[16+bytes+i]==0xA5); + for(i=0;i<512;i++)CHECK(legacy[i]==NONE); + return 0; +} + +static int lifecycle_case(char const *kind) +{ + long i; + scenario.object_names.count=32767; + object_name_list_new(1,513);object_name_list_new(2,32766); + if(!strcmp(kind,"restart"))object_name_list_clear(); + else{ + if(!strcmp(kind,"failed_unload")){ + loaded=FALSE; + CHECK(!mcc_object_names_snapshot(NULL)); + CHECK(mcc_object_names_validate(NULL,0)&&mcc_object_names_restore(NULL,0)); + loaded=TRUE;CHECK(object_index_from_name_index(513)==1); + loaded=FALSE; + } + mcc_cache_tags_unload();CHECK(!loaded); + mcc_cache_tags_unload();CHECK(!loaded); + /* A legacy map still owns its original table after MCC disposal. */ + scenario.object_names.count=512; + object_name_list_new(3,511);CHECK(object_index_from_name_index(511)==3); + object_name_list_clear();loaded=TRUE;scenario.object_names.count=32767; + } + for(i=0;i<32767;i++)CHECK(object_index_from_name_index((short)i)==NONE); + object_claim_scenario_name(4,32766);CHECK(object_index_from_name_index(32766)==4); + return 0; +} + +int main(int argc,char **argv) +{ + long i; + struct mcc_name_chunk bad; + CHECK(argc==2); + scenario.object_names.count=640;scenario.object_names.address=definitions; + for(i=0;i<32767;i++)definitions[i].runtime_object_type=6; + for(i=0;i<8;i++){ + objects[i].object.first_child_object_index=NONE; + objects[i].object.name_index=NONE; + } + object_name_list_clear();mcc_object_names_network_reset(); + CHECK(mcc_object_names_entry_size()==72); + if(!strncmp(argv[1],"snapshot_",9))return snapshot_case(strtol(argv[1]+9,NULL,10),0); + if(!strncmp(argv[1],"invalid_snapshot_",17))return snapshot_case(strtol(argv[1]+17,NULL,10),1); + if(!strcmp(argv[1],"restart")||!strcmp(argv[1],"unload")||!strcmp(argv[1],"failed_unload"))return lifecycle_case(argv[1]); + if(!strcmp(argv[1],"legacy")){ + loaded=0;scenario.object_names.count=512; + object_name_list_new(1,511);CHECK(object_index_from_name_index(511)==1); + object_set_object_index_for_name_index(512,2);CHECK(object_index_from_name_index(512)==NONE); + object_name_list_delete(1);CHECK(object_name_list_lookup(511)==NONE); + loaded=1;CHECK(!mcc_object_names_active());CHECK(!mcc_object_names_snapshot(NULL)); + }else if(!strcmp(argv[1],"boundary")||!strcmp(argv[1],"maximum")){ + short last=!strcmp(argv[1],"maximum")?32766:639; + scenario.object_names.count=(long)last+1; + object_name_list_new(1,511);object_name_list_new(2,512);object_claim_scenario_name(3,last); + CHECK(object_name_list_lookup(511)==1&&object_name_list_lookup(512)==2&&object_index_from_name_index(last)==3); + object_claim_scenario_name(4,last);CHECK(object_index_from_name_index(last)==3); + CHECK(object_index_from_name_index(-1)==NONE&&object_index_from_name_index((short)(last+1))==NONE); + CHECK(legacy[511]==NONE);CHECK(objects[3].object.name_index==last); + object_name_list_clear();CHECK(object_index_from_name_index(last)==NONE); + }else if(!strcmp(argv[1],"aliases")){ + object_name_list_new(1,513);object_set_object_index_for_name_index(638,1); + object_name_list_delete(1);CHECK(object_index_from_name_index(513)==NONE&&object_index_from_name_index(638)==NONE); + object_name_list_new(2,513);CHECK(object_index_from_name_index(513)==2); + object_set_object_index_for_name_index(1,4);object_set_object_index_for_name_index(639,4); + CHECK(objects[4].object.name_index==NONE); + object_name_list_delete(4); + CHECK(object_index_from_name_index(1)==NONE&&object_index_from_name_index(639)==NONE); + CHECK(object_index_from_name_index(513)==2&&objects[4].object.name_index==NONE); + }else{ + scenario.object_names.count=32767; + object_name_list_new(1,512);object_name_list_new(2,32766); + mcc_object_names_host_tick();CHECK(sends==64); + object_name_list_clear();connection=2; + if(!strcmp(argv[1],"network")){ + for(i=63;i>=0;i--)mcc_object_names_receive(packets[i],1,15); + CHECK(created==0); + for(i=0;i<64;i++)mcc_object_names_receive(packets[i],1,15); + CHECK(created==0); + for(i=0;i<64;i++)mcc_object_names_receive(packets[i],1,30); + CHECK(created==2&&object_index_from_name_index(32766)!=NONE); + memset(packets[63]+8,0,64); + mcc_object_names_receive(packets[63],1,45);CHECK(!deleted); + mcc_object_names_receive(packets[63],1,44);CHECK(!deleted); + mcc_object_names_receive(packets[63],1,60);CHECK(deleted==1); + }else if(!strcmp(argv[1],"invalid")){ + memcpy(&bad,packets[63],72);bad.first=32767; + mcc_object_names_receive(&bad,1,15);bad.first=-512;mcc_object_names_receive(&bad,1,30); + memcpy(&bad,packets[63],72);bad.present[63]|=128;mcc_object_names_receive(&bad,1,45); + mcc_object_names_receive(packets[63],0,60);mcc_object_names_receive(packets[63],2,75); + mcc_object_names_receive(packets[63],1,90);CHECK(!created); + mcc_object_names_receive(packets[63],1,105);CHECK(created==1); + }else{ + mcc_object_names_receive(packets[63],1,15);bsp=1; + mcc_object_names_receive(packets[63],1,30);bsp=0; + mcc_object_names_receive(packets[63],1,45);CHECK(!created); + mcc_object_names_receive(packets[63],1,60);CHECK(created==1); + } + } + return 0; +} diff --git a/tools/harness/tests/mcc_objects.c b/tools/harness/tests/mcc_objects.c new file mode 100644 index 0000000000..6cca67fc9e --- /dev/null +++ b/tools/harness/tests/mcc_objects.c @@ -0,0 +1,57 @@ +#include "cseries.h" +#include "game/game_engine.h" +#include "mcc_objects.h" +#include +#include +#undef memcpy +#undef memset + +static boolean loaded, running; +static struct game_variant variant; +boolean mcc_cache_tags_loaded(void) { return loaded; } +boolean game_engine_running(void) { return running; } +struct game_variant *game_engine_get_variant(void) { return &variant; } +void *csmemcpy(void *to, void const *from, unsigned long size) { return memcpy(to, from, size); } +void *csmemset(void *to, long value, unsigned long size) { return memset(to, value, size); } + +#define CHECK(value) do { if (!(value)) { fprintf(stderr, "failed at %d\n", __LINE__); return 1; } } while (0) +int main(void) { + unsigned char bytes[0x78] = {0}; + struct scenario_object_datum *placement = (void *)bytes; + unsigned short flags; + int engine, enabled; + union { unsigned long bits; real value; } invalid; + CHECK(!mcc_item_small_scale(0.001f)); + loaded = TRUE; + CHECK(mcc_item_small_scale(0.001f) && mcc_item_small_scale(0.25f)); + CHECK(!mcc_item_small_scale(0.f) && !mcc_item_small_scale(-1.f) && + !mcc_item_small_scale(0.0001f) && !mcc_item_small_scale(0.5f) && + !mcc_item_small_scale(4.f)); + invalid.bits = 0x7FC00000; CHECK(!mcc_item_small_scale(invalid.value)); + invalid.bits = 0x7F800000; CHECK(!mcc_item_small_scale(invalid.value)); + loaded = FALSE; + running = TRUE; + variant.game_engine_index = game_engine_slayer; + CHECK(!mcc_vehicle_placement_rules()); + CHECK(mcc_vehicle_placement_allowed(placement)); + loaded = TRUE; + for (engine = game_engine_ctf; engine <= game_engine_king; ++engine) { + static unsigned short masks[] = {0, 2, 1, 8, 4}; + variant.game_engine_index = engine; + for (enabled = 0; enabled < 16; ++enabled) { + flags = (unsigned short)enabled; + memcpy(bytes + 0x5A, &flags, 2); + CHECK(mcc_vehicle_placement_rules()); + CHECK(mcc_vehicle_placement_allowed(placement) == ((enabled & masks[engine]) != 0)); + } + } + variant.game_engine_index = game_engine_race; + CHECK(!mcc_vehicle_placement_rules() && mcc_vehicle_placement_allowed(placement)); + variant.game_engine_index = game_engine_slayer; + variant.universal_variant.vehicle_set = 1; + CHECK(!mcc_vehicle_placement_rules()); + variant.universal_variant.vehicle_set = 0; + running = FALSE; + CHECK(!mcc_vehicle_placement_rules() && mcc_vehicle_placement_allowed(placement)); + return 0; +} diff --git a/tools/harness/tests/mcc_particles.c b/tools/harness/tests/mcc_particles.c new file mode 100644 index 0000000000..e4a45465ab --- /dev/null +++ b/tools/harness/tests/mcc_particles.c @@ -0,0 +1,98 @@ +#include +#include +#define TRUE 1 +#define FALSE 0 +#define NONE -1 +#define FLAG(n) (1UL << (n)) +#define TEST_FLAG(v,n) (((v) & FLAG(n)) != 0) +#define VALID_INDEX(i,n) ((i) >= 0 && (i) < (n)) +#define TAG_BLOCK_GET_ELEMENT(b,i,t) (&((t *)(b)->address)[i]) +typedef int boolean; +enum {_director_perspective_first_person, third_person}; +struct object_marker {float x, y, z;}; +struct tag_block {int count;void *address;}; +struct object_attachment_definition {char marker_name[32];}; +struct weapon_datum {long definition_index;}; +struct object_definition {struct {struct tag_block attachments;} object;}; +static struct weapon_datum weapon = {42}; +static struct object_attachment_definition attachment = {"spawn fire"}; +static struct object_definition definition = {{{1, &attachment}}}; +static int active = 1, exists = 1, local = 0, perspective, reads, queries, marker_exists = 1; +static int mcc_cache_tags_loaded(void) {return active;} +static struct weapon_datum *weapon_try_and_get(long index) { + ++reads;return exists && index == 123 ? &weapon : NULL; +} +static long first_person_weapon_get_local_index(long index) {(void)index;return local;} +static int director_get_perspective(short index) {(void)index;return perspective;} +static struct object_definition *object_definition_get(long index) {(void)index;return &definition;} +static short first_person_weapon_get_marker_by_name(long index, char const *name, + struct object_marker *markers, short maximum) { + ++queries; + if (index != 123 || strcmp(name,"spawn fire") || maximum <= 0 || !marker_exists) return 0; + markers[0].x=10;markers[0].y=20;markers[0].z=30; + return 1; +} +/* IMPLEMENTATION */ +#define CHECK(v) do {if(!(v)){fprintf(stderr,"line %d\n",__LINE__);return 1;}} while(0) +int main(int argc,char **argv) { + unsigned long fp=FLAG(_particle_system_type_nodraw_third_person_bit); + unsigned long world=FLAG(_particle_system_type_nodraw_first_person_bit); + struct object_marker markers[2]={{1,2,3},{4,5,6}}; + int viewer, flags; + if(argc!=2)return 2; + if(!strcmp(argv[1],"markers")) { + CHECK(mcc_particle_system_markers(123,0,fp,markers,1,0)==1); + CHECK(markers[0].z==30 && markers[1].z==6 && queries==1); + markers[0].z=3; + CHECK(mcc_particle_system_markers(123,0,world,markers,1,1)==1); + CHECK(mcc_particle_system_markers(123,0,0,markers,1,2)==2); + CHECK(markers[0].z==3 && queries==1); + marker_exists=0;CHECK(mcc_particle_system_markers(123,0,fp,markers,1,1)==0); + CHECK(markers[0].z==3); + CHECK(mcc_particle_system_markers(123,0,fp|world,markers,1,1)==0); + } else if(!strcmp(argv[1],"views")) { + local=2; + for(viewer=-1;viewer<4;viewer++)for(flags=0;flags<4;flags++) { + unsigned long mask=(flags&1 ? world:0)|(flags&2 ? fp:0); + CHECK(mcc_particle_system_visible(123,mask,(short)viewer)== + !(flags & (viewer==2 ? 1:2))); + } + perspective=third_person; + CHECK(!mcc_particle_system_visible(123,fp,2)); + CHECK(mcc_particle_system_visible(123,world,2)); + CHECK(!mcc_particle_system_visible(NONE,fp,2)); + CHECK(mcc_particle_system_visible(NONE,world,2)); + } else if(!strcmp(argv[1],"invalid")) { + CHECK(mcc_particle_system_markers(NONE,0,fp,markers,1,1)==0); + CHECK(mcc_particle_system_markers(456,0,fp,markers,1,1)==0); + CHECK(mcc_particle_system_markers(123,-1,fp,markers,1,1)==0); + CHECK(mcc_particle_system_markers(123,1,fp,markers,1,1)==0); + CHECK(mcc_particle_system_markers(123,0,fp,markers,0,1)==0); + CHECK(queries==0 && markers[0].z==3); + } else if(!strcmp(argv[1],"lifecycle")) { + CHECK(mcc_particle_system_markers(123,0,fp,markers,1,0)==1); + local=NONE; /* Holstered, zoomed, remote, or not yet visible. */ + CHECK(mcc_particle_system_markers(123,0,fp,markers,1,1)==0); + CHECK(!mcc_particle_system_visible(123,fp,0)); + local=0;perspective=third_person; + CHECK(mcc_particle_system_markers(123,0,fp,markers,1,1)==0); + perspective=0;exists=0; /* Deleted weapon must not expose a stale FP cache. */ + CHECK(mcc_particle_system_markers(123,0,fp,markers,1,1)==0); + CHECK(!mcc_particle_system_visible(123,fp,0)); + exists=1;active=0; + CHECK(mcc_particle_system_markers(123,0,fp,markers,1,0)==0); + CHECK(mcc_particle_system_visible(123,fp,3)); + active=1; + CHECK(mcc_particle_system_markers(123,0,fp,markers,1,0)==1); + CHECK(mcc_particle_system_visible(123,fp,0)); + } else if(!strcmp(argv[1],"legacy")) { + active=0; /* Xbox and CE retain all native results without reading objects. */ + for(flags=0;flags<4;flags++) { + unsigned long mask=(flags&1 ? world:0)|(flags&2 ? fp:0); + CHECK(mcc_particle_system_markers(456,-1,mask,markers,1,2)==2); + CHECK(mcc_particle_system_visible(456,mask,0)); + } + CHECK(reads==0 && queries==0 && markers[0].z==3); + } else return 3; + return 0; +} diff --git a/tools/harness/tests/mcc_player.c b/tools/harness/tests/mcc_player.c new file mode 100644 index 0000000000..d1c88982f0 --- /dev/null +++ b/tools/harness/tests/mcc_player.c @@ -0,0 +1,160 @@ +#include "cseries.h" +#include "math/real_math.h" +#include "game/players.h" +#include "game/game.h" +#include "units/units.h" +#include "scenario/scenario_definitions.h" +#include "mcc_player.h" +#include +#include +#undef memset +static boolean active; +static short types = 4, counts[4]; +static struct unit_datum equipment_unit; +static struct scenario equipment_scenario; +static short connection = _game_connection_local; +static unsigned equipment_calls, deleted_weapons; +static long deleted_weapon, given_unit; +static short given_profile; +static boolean given_reset, held_at_assignment; +short game_connection(void) { return connection; } +struct scenario *global_scenario_get(void) { return &equipment_scenario; } +void *object_try_and_get_and_verify_type(long index, unsigned long mask) { + return index == 123 && (mask & _object_mask_biped) ? &equipment_unit : NULL; +} +void object_delete(long weapon) { + short slot=equipment_unit.unit.current_weapon_index; + ++deleted_weapons;deleted_weapon=weapon; + /* The engine's deleted-object notification clears matching inventory. */ + if (slot>=0 && equipment_unit.unit.weapon_object_indices[slot]==weapon) { + equipment_unit.unit.weapon_object_indices[slot]=NONE; + equipment_unit.unit.current_weapon_index=NONE; + } +} +void player_add_equipment(long unit, short profile, boolean reset) { + ++equipment_calls;given_unit=unit;given_profile=profile;given_reset=reset; + held_at_assignment=equipment_unit.unit.current_weapon_index!=NONE; +} +static struct { long weapon_index; } cached_weapons[4]; +static unsigned forgotten; +boolean mcc_cache_tags_loaded(void) { return active; } +static void first_person_weapon_forget_weapon(short local) +{ + forgotten |= 1U << local; + cached_weapons[local].weapon_index = NONE; +} +#define first_person_weapon_get(local) (&cached_weapons[local]) +#include "mcc_first_person.inl" +boolean mcc_grenades_active(void) { return active; } +short mcc_grenades_type_count(void) { return types; } +void mcc_grenades_clear(long unit) { (void)unit; counts[2] = counts[3] = 0; } +short mcc_grenades_get(long unit, short type) { (void)unit; return counts[type]; } +void mcc_grenades_set(long unit, short type, short count) { (void)unit; counts[type] = count; } +#define CHECK(value) do { if (!(value)) { fprintf(stderr,"failed at %d\n",__LINE__); return 1; } } while (0) +int main(void) { + struct player_action action = {0}; + struct scenario_starting_profile profile = {0}; + union { unsigned long bits; float value; } invalid; + short choice; + equipment_scenario.starting_profiles.count=2; + equipment_unit.unit.player_index=7; + equipment_unit.unit.current_weapon_index=1; + equipment_unit.unit.weapon_object_indices[0]=44; + equipment_unit.unit.weapon_object_indices[1]=55; + mcc_player_add_equipment(123,1,TRUE); + CHECK(!equipment_calls && !deleted_weapons); /* Xbox/CE */ + active=TRUE; + connection=_game_connection_network_client; + mcc_player_add_equipment(123,1,TRUE); + CHECK(!equipment_calls && !deleted_weapons); + connection=_game_connection_local; + mcc_player_add_equipment(NONE,1,TRUE); + mcc_player_add_equipment(999,1,TRUE); + mcc_player_add_equipment(123,NONE,TRUE); + mcc_player_add_equipment(123,2,TRUE); + equipment_unit.unit.player_index=NONE; + mcc_player_add_equipment(123,1,TRUE); + CHECK(!equipment_calls && !deleted_weapons); + equipment_unit.unit.player_index=7; + mcc_player_add_equipment(123,1,FALSE); + CHECK(equipment_calls==1 && !deleted_weapons && held_at_assignment && !given_reset); + mcc_player_add_equipment(123,1,TRUE); + CHECK(equipment_calls==2 && deleted_weapons==1 && deleted_weapon==55 && !held_at_assignment); + CHECK(given_unit==123 && given_profile==1 && given_reset); + CHECK(equipment_unit.unit.weapon_object_indices[0]==44); /* native service clears the rest */ + mcc_player_add_equipment(123,1,TRUE); + CHECK(equipment_calls==3 && deleted_weapons==1); /* unarmed/repeated reset */ + equipment_unit.unit.current_weapon_index=MAXIMUM_WEAPONS_PER_UNIT; + mcc_player_add_equipment(123,1,TRUE); + CHECK(equipment_calls==4 && deleted_weapons==1); + equipment_unit.unit.current_weapon_index=1; + equipment_unit.unit.weapon_object_indices[1]=NONE; + mcc_player_add_equipment(123,1,TRUE); + CHECK(equipment_calls==5 && deleted_weapons==1); + connection=_game_connection_network_server; + equipment_unit.unit.weapon_object_indices[1]=66; + mcc_player_add_equipment(123,1,TRUE); + CHECK(equipment_calls==6 && deleted_weapons==2 && deleted_weapon==66 && !held_at_assignment); + active=FALSE; + mcc_player_add_equipment(123,1,TRUE); + CHECK(equipment_calls==6 && deleted_weapons==2); /* unload/legacy transition */ + cached_weapons[0].weapon_index = cached_weapons[2].weapon_index = 123; + cached_weapons[1].weapon_index = 456; + cached_weapons[3].weapon_index = NONE; + mcc_first_person_weapon_deleted(123); + CHECK(!forgotten && cached_weapons[0].weapon_index == 123); + active = TRUE; + mcc_first_person_weapon_deleted(NONE); + mcc_first_person_weapon_deleted(789); + CHECK(!forgotten); + mcc_first_person_weapon_deleted(123); + CHECK(forgotten == 5 && cached_weapons[0].weapon_index == NONE && + cached_weapons[2].weapon_index == NONE && cached_weapons[1].weapon_index == 456); + mcc_first_person_weapon_deleted(123); + CHECK(forgotten == 5); + active = FALSE; + CHECK(!mcc_player_choice_supported(0)); + mcc_player_profile_grenades(1, &profile, TRUE); + active = TRUE; + for (choice = NONE; choice < 4; ++choice) { + action.desired_grenade_index = choice; + CHECK(mcc_player_action_valid(&action)); + } + action.desired_grenade_index = 4; + CHECK(!mcc_player_action_valid(&action)); + action.desired_grenade_index = -2; + CHECK(!mcc_player_action_valid(&action)); + action.desired_grenade_index = 3; + types = 2; + CHECK(!mcc_player_action_valid(&action)); + types = 4; + invalid.bits = 0x7FC00000; + action.throttle.i = invalid.value; + CHECK(!mcc_player_action_valid(&action)); + action.throttle.i = 0; + action.desired_weapon_index = 100; + CHECK(!mcc_player_action_valid(&action)); + action.desired_weapon_index = NONE; + action.desired_zoom_level = -2; + CHECK(!mcc_player_action_valid(&action)); + profile.pad[0] = 2; profile.pad[1] = 3; + counts[0] = 1; counts[1] = 4; counts[2] = 10; + mcc_player_profile_grenades(1, &profile, TRUE); + CHECK(counts[0] == 1 && counts[1] == 4 && counts[2] == 2 && counts[3] == 3); + mcc_player_profile_grenades(1, &profile, FALSE); + CHECK(counts[2] == 4 && counts[3] == 6); + counts[2] = 126; + mcc_player_profile_grenades(1, &profile, FALSE); + CHECK(counts[2] == 127 && counts[3] == 9); + active = FALSE; + mcc_player_profile_grenades(1, &profile, TRUE); + CHECK(counts[2] == 127 && counts[3] == 9); + mcc_player_postspawn_grenades(1, TRUE); + CHECK(counts[2] == 127 && counts[3] == 9); + active = TRUE; + mcc_player_postspawn_grenades(1, FALSE); + CHECK(counts[2] == 127 && counts[3] == 9); + mcc_player_postspawn_grenades(1, TRUE); + CHECK(counts[0] == 1 && counts[1] == 4 && !counts[2] && !counts[3]); + return 0; +} diff --git a/tools/harness/tests/mcc_player_indicator.c b/tools/harness/tests/mcc_player_indicator.c index 7b46498c86..58e3a9d13c 100644 --- a/tools/harness/tests/mcc_player_indicator.c +++ b/tools/harness/tests/mcc_player_indicator.c @@ -20,10 +20,11 @@ static struct { struct { int world_to_view; real z_near, z_far; } frustum; struct { real_point3d position; rectangle2d viewport_bounds; } camera; } render; -static int mcc; +static int mcc, ce; static real drawn_width, drawn_height, drawn_origin_y; static short name_bottom; #define mcc_cache_tags_loaded() mcc +#define custom_edition_cache_tags_loaded() ce #define bitmap_group_get(index) (&test_group) #define player_get(index) (&test_player) #define unit_get(index) (&unit) @@ -82,7 +83,11 @@ int main(int argc, char **argv) else { check_family(TRUE, 0x10, 0.25f); check_family(FALSE, 0, 1.0f); /* Xbox */ - check_family(FALSE, 0x10, 1.0f); /* CE */ + ce=1; + check_family(FALSE, 0x10, 0.5f); /* CE */ + check_family(FALSE, 0x80, 0.5f); + check_family(FALSE, 0x90, 0.25f); + ce=0; check_family(TRUE, 0x80, 0.25f); check_family(FALSE, 0x80, 1.0f); } diff --git a/tools/harness/tests/mcc_recording_control.c b/tools/harness/tests/mcc_recording_control.c new file mode 100644 index 0000000000..9310b6f035 --- /dev/null +++ b/tools/harness/tests/mcc_recording_control.c @@ -0,0 +1,53 @@ +/* Exercise the real MCC playback hook, including inactive/foreign data. */ +#include "cseries.h" +#include "cutscene/recorded_animation_definitions.h" +#include "units/unit_control_data.h" +#include "units/units.h" +#include "mcc_recordings.h" +#include +#include +#undef memset +#undef memcmp + +#define CHECK(x) do {if (!(x)) {fprintf(stderr, "line %d: %s\n", __LINE__, #x);return 1;}} while (0) +static boolean loaded = TRUE, owned = TRUE; +static unsigned char stream[78]; +static struct unit_datum unit; +boolean mcc_cache_tags_loaded(void) {return loaded;} +boolean mcc_cache_contains(void const *p, long bytes) {return owned && p==stream && bytes==sizeof(stream);} +void *object_try_and_get_and_verify_type(long index, unsigned long mask) { + return index==7 && (mask & (1u< +#include +#include +#undef malloc +#undef free +#undef memset +#undef memcpy +#undef strcmp +#undef strncmp +#undef strcpy + +#define CHECK(value) do {if(!(value)){fprintf(stderr,"check failed at %d: %s\n",__LINE__,#value);return 1;}}while(0) +struct hs_stack_frame {struct hs_stack_frame *previous;long expression_index;void *result;short size;byte data[2];}; +struct hs_thread_datum {short identifier;byte type,flags;long script_index,sleep_until,previous_sleep_until; + struct hs_stack_frame *stack;long result;byte stack_data[512];}; +static struct hs_thread_datum thread,other_thread; +static struct scenario *scenario; +struct data_array *hs_syntax_data; +struct hs_global_datum {short identifier;short unused;long value;}; +static struct data_array *hs_global_data; +static int loaded=1,errors,refs,returned,disabled; +short const hs_external_global_count=443; +static long last_result; +static struct hs_thread_datum *hs_thread_get(long index) {return (index&65535)==1 ? &other_thread : &thread;} +static struct data_array thread_array; +static struct data_array *hs_thread_data=&thread_array; +#define _hs_thread_type_script 0 +#define _hs_thread_type_console_command 2 +static int deleted; +static void hs_thread_delete(long index) {(void)index;deleted++;} +void *datum_try_and_get(struct data_array *data,long index) { + struct hs_thread_datum *t; + if(data!=hs_thread_data || (unsigned short)index>1)return NULL; + t=hs_thread_get(index); + return t->identifier && t->identifier==(short)((unsigned long)index>>16) ? t : NULL; +} +#define _hs_thread_sleeping_bit 1 +static long hs_find_thread_by_script(short script) { return script==0 ? 0 : script==1 ? 1 : NONE; } +short hs_find_script_by_name(char const *name) {return !strcmp(name,"target") ? 1 : NONE;} +static long finished_argument; +long *hs_macro_function_evaluate(short f,long t,boolean i) {(void)f;(void)t;return i ? &finished_argument : NULL;} +boolean mcc_cache_tags_loaded(void) {return loaded;} +void error(short priority,char const *message,...) {(void)priority;(void)message;} +void *csmemset(void *p,long value,unsigned long size) {return memset(p,(int)value,size);} +void *csmemcpy(void *p,void const *from,unsigned long size) {return memcpy(p,from,size);} +boolean hs_can_cast(short a,short b) {return a==b || + (loaded && a==_hs_type_ai && (HS_TYPE_IS_OBJECT(b)||b==_hs_type_object_list));} +long hs_cast(long index,short from,short to,long value) {(void)index;(void)from;(void)to;return value;} +void object_list_add_reference(long index) {if(index!=NONE)refs++;} +void object_list_remove_reference(long index) {if(index!=NONE){if(!refs)exit(20);refs--;}} +static void hs_syntax_error(long index) {(void)index;errors++;} +static long hs_type_default_value(short type) {(void)type;return NONE;} +boolean hs_scenario_script_disabled(short index) {(void)index;return disabled;} +struct scenario *global_scenario_get(void) {return scenario;} +struct hs_syntax_node *hs_syntax_get(long handle) { + unsigned index=(unsigned)handle&65535; + struct hs_syntax_node *nodes=hs_syntax_data->data; + return handle!=NONE&&index<(unsigned)hs_syntax_data->count&& + (unsigned short)nodes[index].datum_header==(unsigned short)((unsigned)handle>>16)?nodes+index:NULL; +} +static void *hs_stack_allocate(long index,long size) { + void *out;(void)index; + if(size<0||size>thread.stack_data+512-(thread.stack->data+thread.stack->size)){errors++;return NULL;} + out=thread.stack->data+thread.stack->size;thread.stack->size+=(short)size;return out; +} +void hs_return(long index,long value) {(void)index;returned++;last_result=value;} +static void hs_evaluate(long index,long expression,long *out); +#include "mcc_script_runtime.inl" +static void hs_evaluate(long index,long expression,long *out) { + struct hs_syntax_node *node=hs_syntax_get(expression); + if(!node){errors++;return;} + if(!mcc_hs_parameter_evaluate(index,node,out))*out=node->data; +} +void *mcc_runtime_pointer(struct mcc_runtime *runtime,uint32_t address,uint32_t bytes) { + uint32_t offset=address-runtime->report.tag_base; + return address>=runtime->report.tag_base&&offset<=runtime->used&&bytes<=runtime->used-offset? + runtime->tags+offset:NULL; +} +void *tag_block_get_element_with_size(struct tag_block const *block,long index,long size) { + return (unsigned char *)block->address+index*size; +} + +int main(int argc,char **argv) { + struct mcc_runtime runtime={0}; + struct hs_script *scripts; + struct hs_syntax_node *nodes; + struct hs_global *globals; + unsigned char *parameter; + uint32_t *block; + short type=_hs_type_long_integer,owner; + int valid=1,i; + struct hs_stack_frame *frame; + struct mcc_hs_arguments *state; + CHECK(argc==2); + runtime.used=1048576;runtime.tags=malloc(runtime.used);CHECK(runtime.tags); + memset(runtime.tags,0,runtime.used);runtime.report.tag_base=(uint32_t)(uintptr_t)runtime.tags; + scenario=(void *)(runtime.tags+256);scripts=(void *)(runtime.tags+4096); + hs_syntax_data=(void *)(runtime.tags+8192);nodes=(void *)(hs_syntax_data+1); + parameter=runtime.tags+0xE0000;globals=(void *)(runtime.tags+0xF0000); + scenario->hs_scripts.count=2;scenario->hs_scripts.address=scripts; + scenario->hs_globals.address=globals; + scripts[0].script_type=_hs_script_static;scripts[0].return_type=type;scripts[0].root_expression_index=0x10000; + scripts[1].script_type=_hs_script_static;scripts[1].return_type=type;scripts[1].root_expression_index=NONE; + block=(void *)((unsigned char *)scripts+0x50);block[0]=1;block[1]=(uint32_t)(uintptr_t)parameter; + strcpy((char *)parameter,"argument");memcpy(parameter+32,&type,2); + hs_syntax_data->data=nodes;hs_syntax_data->count=5; + for(i=0;i<5;i++){nodes[i].datum_header=1;nodes[i].next_node_index=NONE;nodes[i].type=type;nodes[i].flags=9;} + nodes[0].flags=0x1D;nodes[0].data=0; + nodes[1].datum_header=0; + nodes[2].flags=10;nodes[2].script_index=0;nodes[2].data=0x10003; + nodes[3].type=_hs_function_name;nodes[3].next_node_index=0x10004; + nodes[4].data=42; + if(!strncmp(argv[1],"kill_",5) || !strcmp(argv[1],"executing_thread")) { + struct hs_stack_frame *base=(void *)thread.stack_data; + struct hs_stack_frame *other_base=(void *)other_thread.stack_data; + thread_array.valid=1;thread.identifier=other_thread.identifier=3; + thread.type=other_thread.type=_hs_thread_type_script; + thread.stack=(void *)(thread.stack_data+64);thread.stack->previous=base; + other_thread.stack=(void *)(other_thread.stack_data+64);other_thread.stack->previous=other_base; + thread.sleep_until=other_thread.sleep_until=99; + if(!strcmp(argv[1],"executing_thread")) { + mcc_executing_thread_evaluate(0,0x30000,TRUE);CHECK(last_result==0x30000);return 0; + } + finished_argument=(!strcmp(argv[1],"kill_self") || !strcmp(argv[1],"kill_self_lists")) ? 0x30000 : 0x30001; + if(!strcmp(argv[1],"kill_self_lists") || !strcmp(argv[1],"kill_other_lists")) { + struct hs_thread_datum *target=hs_thread_get(finished_argument); + struct mcc_hs_arguments *args=(void *)target->stack->data; + CHECK(mcc_parameters_prepare(&runtime,scenario,hs_syntax_data)); + target->stack->expression_index=0x10002;target->stack->size=(short)mcc_hs_arguments_size(1); + args->magic=MCC_HS_ARGUMENT_MAGIC;args->script=0;args->count=1; + args->references=1;args->values[0]=42;refs=1; + } + if(!strcmp(argv[1],"kill_stale"))finished_argument=0x20001; + if(!strcmp(argv[1],"kill_slot"))finished_argument=1; + if(!strcmp(argv[1],"kill_none"))finished_argument=NONE; + if(!strcmp(argv[1],"kill_outside"))finished_argument=0x3ffff; + if(!strcmp(argv[1],"kill_deleted"))other_thread.identifier=0; + if(!strcmp(argv[1],"kill_legacy"))loaded=0; + if(!strcmp(argv[1],"kill_console"))other_thread.type=_hs_thread_type_console_command; + mcc_kill_thread_evaluate(0,0x30000,FALSE);CHECK(!returned && !deleted); + mcc_kill_thread_evaluate(0,0x30000,TRUE); + if(!strcmp(argv[1],"kill_self") || !strcmp(argv[1],"kill_self_lists")) { + CHECK(thread.stack==base && thread.sleep_until==NONE && !returned && !deleted); + CHECK(other_thread.sleep_until==99); + } else if(!strcmp(argv[1],"kill_other") || !strcmp(argv[1],"kill_other_lists") || !strcmp(argv[1],"kill_console")) { + CHECK(other_thread.stack==other_base && !other_thread.flags && !other_thread.previous_sleep_until); + CHECK(other_thread.sleep_until==(other_thread.type==_hs_thread_type_console_command ? 0 : NONE)); + CHECK(returned==1 && deleted==(other_thread.type==_hs_thread_type_console_command)); + } else { + CHECK(other_thread.stack!=other_base && other_thread.sleep_until==99 && !deleted); + CHECK(returned==loaded); + } + CHECK(!refs); + free(runtime.tags); + return 0; + } + if(!strncmp(argv[1],"tail_",5)) { + struct hs_stack_frame *parent=(void *)thread.stack_data; + struct hs_stack_frame *child=(void *)(thread.stack_data+64); + long output=99; + long *state=(long *)child->data; + nodes[0].flags=8;nodes[0].type=_hs_type_long_integer;nodes[0].data=0x10001; + nodes[1].datum_header=1;nodes[1].next_node_index=0x10002; + nodes[2].next_node_index=0x10003; + nodes[3].flags=9;nodes[3].type=_hs_type_long_integer;nodes[3].data=12;nodes[3].next_node_index=0x10004; + nodes[4].flags=9;nodes[4].type=_hs_type_long_integer;nodes[4].data=34; + parent->result=&output;child->previous=parent;child->expression_index=0x10000;thread.stack=child; + state[0]=!strcmp(argv[1],"tail_true");state[1]=NONE; + if(!strcmp(argv[1],"tail_legacy"))loaded=0; + if(!strcmp(argv[1],"tail_cast"))nodes[4].type=_hs_type_short_integer; + if(!strcmp(argv[1],"tail_absent"))nodes[3].next_node_index=NONE; + if(!strcmp(argv[1],"tail_complete"))state[1]=0x10004; + CHECK(!mcc_hs_if_tail(_hs_function_if,0,TRUE)); + CHECK(!mcc_hs_if_tail(_hs_function_begin,0,FALSE)); + if(!strcmp(argv[1],"tail_true") || !strcmp(argv[1],"tail_false")) { + CHECK(mcc_hs_if_tail(_hs_function_if,0,FALSE)); + CHECK(thread.stack==parent && output==(!strcmp(argv[1],"tail_true") ? 12 : 34)); + } else { + CHECK(!mcc_hs_if_tail(_hs_function_if,0,FALSE)); + CHECK(thread.stack==child && output==99); + } + CHECK(!errors);free(runtime.tags);return 0; + } + if(!strcmp(argv[1],"finished")) { + finished_argument=(long)"target"; + other_thread.sleep_until=NONE; + mcc_script_finished_evaluate(0,0,TRUE);CHECK(last_result==TRUE); + other_thread.sleep_until=NONE-1; + mcc_script_finished_evaluate(0,0,TRUE);CHECK(last_result==FALSE); + other_thread.sleep_until=123; + mcc_script_finished_evaluate(0,0,TRUE);CHECK(last_result==FALSE); + finished_argument=(long)"missing"; + mcc_script_finished_evaluate(0,0,TRUE);CHECK(last_result==FALSE); + finished_argument=0;mcc_script_finished_evaluate(0,0,TRUE);CHECK(last_result==FALSE); + last_result=123;mcc_script_finished_evaluate(0,0,FALSE);CHECK(last_result==123); + free(runtime.tags);return 0; + } + if(!strncmp(argv[1],"sleep_",6)) { + int named=strcmp(argv[1],"sleep_self")!=0; + struct hs_thread_datum saved; + memset(&thread,0,sizeof(thread));memset(&other_thread,0,sizeof(other_thread)); + frame=(void *)(thread.stack_data+32);thread.stack=frame;frame->expression_index=0x10002; + other_thread.sleep_until=123;nodes[4].data=1; + if(!strcmp(argv[1],"sleep_lists")) { + struct hs_stack_frame *pending=(void *)(other_thread.stack_data+32); + struct mcc_hs_arguments *arguments=(void *)pending->data; + CHECK(mcc_parameters_prepare(&runtime,scenario,hs_syntax_data)); + pending->previous=(void *)other_thread.stack_data; + pending->expression_index=0x10002;pending->size=(short)mcc_hs_arguments_size(1); + other_thread.stack=pending;arguments->magic=MCC_HS_ARGUMENT_MAGIC; + arguments->script=0;arguments->count=1;arguments->references=1;arguments->values[0]=42;refs=1; + } + if(!strcmp(argv[1],"sleep_disabled"))disabled=1; + if(!named)nodes[3].next_node_index=NONE; + if(!strcmp(argv[1],"sleep_missing"))nodes[4].data=9; + if(!strcmp(argv[1],"sleep_finished"))other_thread.sleep_until=NONE; + mcc_sleep_forever_evaluate(0,0,TRUE); + if(named) { + CHECK(!returned && other_thread.sleep_until!=NONE-1); + saved=thread;memset(&thread,0,sizeof(thread));thread=saved; + frame->size=0;mcc_sleep_forever_evaluate(0,0,FALSE); + if(!strcmp(argv[1],"sleep_missing"))CHECK(other_thread.sleep_until==123); + else if(disabled)CHECK(other_thread.sleep_until==123); + else { + CHECK(other_thread.sleep_until==NONE-1 && other_thread.previous_sleep_until==0); + CHECK(!other_thread.flags && other_thread.stack==(void *)other_thread.stack_data); + CHECK(!other_thread.stack->previous && !other_thread.stack->size && other_thread.stack->expression_index==NONE); + frame->size=0;mcc_sleep_forever_evaluate(0,0,TRUE); + frame->size=0;mcc_sleep_forever_evaluate(0,0,FALSE); + CHECK(other_thread.previous_sleep_until==0 && other_thread.sleep_until==NONE-1); + CHECK(!refs); + } + CHECK(thread.sleep_until==0); + } else CHECK(thread.sleep_until==NONE-1 && !thread.flags); + CHECK(returned && !errors);free(runtime.tags);return 0; + } + if(!strcmp(argv[1],"count")){block[0]=17;valid=0;} + else if(!strcmp(argv[1],"type")){type=_hs_type_void;memcpy(parameter+32,&type,2);valid=0;} + else if(!strcmp(argv[1],"pointer")){block[1]=1;valid=0;} + else if(!strcmp(argv[1],"slot")){nodes[0].data=1;valid=0;} + else if(!strcmp(argv[1],"orphan")){scripts[0].root_expression_index=NONE;valid=0;} + else if(!strcmp(argv[1],"flags")){nodes[0].flags=0x19;valid=0;} + else if(!strcmp(argv[1],"call_arity")){nodes[3].next_node_index=NONE;valid=0;} + else if(!strcmp(argv[1],"call_type")){nodes[4].type=_hs_type_boolean;valid=0;} + else if(!strcmp(argv[1],"predicate")){nodes[3].type=_hs_type_long_integer;valid=0;} + else if(!strcmp(argv[1],"script_kind")){scripts[0].script_type=_hs_script_startup;valid=0;} + else if(!strcmp(argv[1],"global_scope")){scenario->hs_globals.count=1;globals[0].initialization_expression_index=0x10000;valid=0;} + else if(!strcmp(argv[1],"lists")){type=_hs_type_object_list;memcpy(parameter+32,&type,2);nodes[0].type=nodes[4].type=type;} + else if(!strcmp(argv[1],"ai_cast")){type=_hs_type_ai;memcpy(parameter+32,&type,2);nodes[4].type=type;nodes[0].type=_hs_type_unit;} + else if(!strcmp(argv[1],"widen")){type=_hs_type_short_integer;memcpy(parameter+32,&type,2);nodes[4].type=type;} + else if(!strcmp(argv[1],"global_capacity")||!strcmp(argv[1],"global_overflow")) { + scenario->hs_globals.count=581+(!strcmp(argv[1],"global_overflow")); + for(i=0;ihs_globals.count;i++)globals[i].initialization_expression_index=NONE; + valid=scenario->hs_globals.count==581; + } else if(!strcmp(argv[1],"maximum")) { + block[0]=16;hs_syntax_data->count=20; + for(i=0;i<16;i++) { + strcpy((char *)parameter+i*36,"argument");memcpy(parameter+i*36+32,&type,2); + nodes[i+4].datum_header=1;nodes[i+4].flags=9;nodes[i+4].type=type; + nodes[i+4].next_node_index=i==15?NONE:0x10005+i; + } + } else if(!strcmp(argv[1],"high_node")) { + hs_syntax_data->count=32767; + nodes[32766]=nodes[0];nodes[0].datum_header=0; + scripts[0].root_expression_index=0x17FFE; + } else if(!strcmp(argv[1],"negative_count")) { + hs_syntax_data->count=(short)32768;valid=0; + } else if(!strcmp(argv[1],"disabled"))disabled=1; + loaded=0;CHECK(mcc_parameters_prepare(&runtime,scenario,hs_syntax_data)==valid);loaded=1; + if(!valid){CHECK(!mcc_parameters_signature(0));free(runtime.tags);return 0;} + if(!strcmp(argv[1],"high_node")) { + struct hs_thread_datum saved; + CHECK(mcc_parameter_type(nodes+32766,&owner)==type&&owner==0); + CHECK(mcc_parameter_compile(nodes+32766)==1); + memset(&thread,0,sizeof(thread));frame=(void *)(thread.stack_data+32); + frame->previous=(void *)thread.stack_data;frame->expression_index=0x10002;thread.stack=frame; + CHECK(mcc_hs_script_evaluate(0,0,TRUE)); + saved=thread;memset(&thread,0,sizeof(thread));thread=saved; + frame->size=0;CHECK(mcc_hs_script_evaluate(0,0,FALSE)); + CHECK(((struct mcc_hs_arguments *)frame->data)->result==42); + frame->size=0;CHECK(mcc_hs_script_evaluate(0,0,FALSE)); + CHECK(returned==1&&last_result==42&&!errors); + goto done; + } + CHECK(mcc_parameter_type(nodes,&owner)==type&&owner==0); + CHECK(mcc_parameter_compile(nodes)==1); + if(!strcmp(argv[1],"maximum")){CHECK(mcc_parameters_signature(0)->count==16);goto done;} + if(!strcmp(argv[1],"global_capacity"))goto done; + if(!strcmp(argv[1],"metadata")||!strcmp(argv[1],"ai_cast")){CHECK(mcc_parameters_signature(0)->count==1);goto done;} + if(!strcmp(argv[1],"legacy")){loaded=0;CHECK(mcc_parameter_type(nodes,NULL)==-1);CHECK(!mcc_parameters_signature(0));goto done;} + memset(&thread,0,sizeof(thread));frame=(void *)(thread.stack_data+32); + frame->previous=(void *)thread.stack_data;frame->expression_index=0x10002;thread.stack=frame; + CHECK(mcc_hs_script_evaluate(0,0,TRUE)); + state=(void *)frame->data;CHECK(state->values[0]==42&&state->phase==0); + if(!strcmp(argv[1],"widen")) { + long value; + state->phase=1; + state->values[0]=0x1234ffff;CHECK(mcc_hs_parameter_evaluate(0,nodes,&value)&&value==-1); + state->values[0]=0x8000;CHECK(mcc_hs_parameter_evaluate(0,nodes,&value)&&value==-32768); + state->values[0]=32767;CHECK(mcc_hs_parameter_evaluate(0,nodes,&value)&&value==32767); + goto done; + } + if(!strcmp(argv[1],"snapshot")) { + unsigned char snapshot[sizeof(thread)];memcpy(snapshot,&thread,sizeof(thread)); + memset(&thread,0,sizeof(thread));memcpy(&thread,snapshot,sizeof(thread)); + } + frame->size=0;CHECK(mcc_hs_script_evaluate(0,0,FALSE)); + if(disabled){CHECK(returned==1&&last_result==NONE&&!refs);goto done;} + CHECK(state->phase==1&&state->result==42); + if(!strcmp(argv[1],"lists")){CHECK(refs==1);mcc_hs_release_thread(0);CHECK(!refs);state->references=0;} + if(!strcmp(argv[1],"nested_scope")||!strcmp(argv[1],"recursive_arguments")) { + struct hs_stack_frame *nested=(void *)(frame->data+frame->size+16); + struct mcc_hs_arguments *other; + long *value;short actual; + nested->previous=frame;nested->expression_index=0x10002;thread.stack=nested; + nested->size=0;CHECK(mcc_hs_script_evaluate(0,0,TRUE));other=(void *)nested->data; + other->values[0]=84; + if(!strcmp(argv[1],"nested_scope"))other->phase=1; + value=mcc_hs_parameter_address(0,nodes,&actual); + CHECK(value&&*value==(!strcmp(argv[1],"nested_scope")?84:42));thread.stack=frame; + } + if(!strcmp(argv[1],"set")) { + struct hs_stack_frame *setter=(void *)(frame->data+frame->size+16); + setter->previous=frame;setter->expression_index=0x10003;setter->size=0;thread.stack=setter; + nodes[0].next_node_index=0x10004;nodes[4].data=77; + CHECK(mcc_parameter_set_valid(nodes,nodes+4)==1); + CHECK(mcc_hs_parameter_set(0,nodes,TRUE));setter->size=0; + CHECK(mcc_hs_parameter_set(0,nodes,FALSE));CHECK(state->values[0]==77);thread.stack=frame; + returned=0; + } + if(!strcmp(argv[1],"overflow")) { + struct hs_stack_frame *overflow=(void *)(thread.stack_data+480); + overflow->size=0;overflow->previous=frame;overflow->expression_index=0x10002;thread.stack=overflow; + CHECK(mcc_hs_script_evaluate(0,0,TRUE));CHECK(errors==1);mcc_hs_release_thread(0);errors=0;thread.stack=frame; + } + frame->size=0;CHECK(mcc_hs_script_evaluate(0,0,FALSE));CHECK(returned==1&&last_result==42&&!errors&&!refs); +done: + mcc_parameters_dispose();CHECK(!mcc_parameters_signature(0));free(runtime.tags);return 0; +} diff --git a/tools/harness/tests/mcc_script_threads.c b/tools/harness/tests/mcc_script_threads.c new file mode 100644 index 0000000000..2ee5458855 --- /dev/null +++ b/tools/harness/tests/mcc_script_threads.c @@ -0,0 +1,154 @@ +#include +#include +#include +#include +#include +#include "zlib_prefixed.h" +#define CHECK(x) do { if (!(x)) {fprintf(stderr,"line %d: %s\n",__LINE__,#x);return 1;} } while (0) +#define TAG_STRING_LENGTH 31 +#define NONE (-1) +#define TRUE 1 +#define FALSE 0 +#define TEST_FLAG(v,b) (((v) & (1u << (b))) != 0) +#define match_hs_assert(a,b,c,d,e) ((void)0) +typedef unsigned char byte,boolean; +#include "types.inc" +static byte image[2*1024*1024], saved[sizeof(image)]; +static unsigned long used=160000, capacity=sizeof(image); +static int loaded, lighting_resets; +static void mcc_campaign_reset_model_lighting(void) {++lighting_resets;} +static struct data_array *hs_thread_data; +static struct hs_thread_datum *hs_thread_get(long index) {(void)index;return hs_thread_data->data;} +static void hs_stack_overflow(long index) {hs_thread_get(index)->flags|=1u<<_hs_thread_stack_overflow_bit;} +static int mcc_cache_tags_loaded(void) {return loaded;} +static void *game_state_port_cpu_region(unsigned long *u,unsigned long *c) {*u=used;*c=capacity;return image;} +static void data_initialize(struct data_array *a,char const *name,short count,short stride) +{ + memset(a,0,sizeof(*a));memcpy(a->name,name,strlen(name)+1);a->maximum_count=count; + a->size=stride;a->signature='d@t@';a->data=a+1; +} +static void data_make_invalid(struct data_array *a) {a->valid=0;} +#include "under_test.inc" + +/* A real stack shape: root result, a large parent and an odd-aligned leaf. + * Frame offsets follow the native push operation, including its padding. */ +static struct hs_thread_datum *populate(struct data_array *a,unsigned size) +{ + struct hs_thread_datum *t=(void *)(a+1); + struct hs_stack_frame *root=(void *)t->stack_data; + struct hs_stack_frame *parent=(void *)(t->stack_data+20); + struct hs_stack_frame *leaf=(void *)(t->stack_data+36+size); + a->valid=1;a->next_identifier=2;a->count=a->actual_count=1; + t->identifier=1;t->sleep_until=123;t->script_index=0; + root->size=4;root->previous=NULL;root->result=root->data; + parent->previous=root;parent->size=(short)size;parent->result=parent->data; + leaf->previous=parent;leaf->size=4;t->stack=leaf; + memcpy(leaf->data,"test",4); + return t; +} + +int main(int argc,char **argv) +{ + struct data_array *native=(void *)(image+1024),*incoming; + struct hs_thread_datum *t,*copy; + struct hs_stack_frame *root; + byte *storage,*saved_storage; + unsigned long offset; + CHECK((argc==2 || argc==3) && sizeof(long)==4 && sizeof(void *)==4); + if (!strcmp(argv[1],"crc")) { + unsigned long i,bytes; + unsigned char *data; + CHECK(argc==3); + if (!strcmp(argv[2],"null")) {printf("%08lx\n",mcc_threads_checksum(NULL,0));return 0;} + if (!strcmp(argv[2],"known")) {printf("%08lx\n",mcc_threads_checksum((byte const *)"123456789",9));return 0;} + bytes=strtoul(argv[2],NULL,10);CHECK(bytes<=MCC_SCRIPT_THREAD_STORAGE); + data=malloc(bytes?bytes:1);CHECK(data); + for(i=0;i>8)+19); + printf("%08lx\n",mcc_threads_checksum(data,bytes));free(data);return 0; + } + memset(image,0xA5,sizeof(image));memset(native,0,140000); + data_initialize(native,"hs thread",256,sizeof(struct hs_thread_datum)); + hs_thread_data=native; + t=populate(native,65); + CHECK(mcc_hs_stack_end(t)==t->stack_data+512); + if (!strcmp(argv[1],"bounds")) { + CHECK(!hs_stack_allocate(0,1024));CHECK(TEST_FLAG(t->flags,_hs_thread_stack_overflow_bit)); + t->flags=0; + } + if (!strcmp(argv[1],"capacity")) { + used=capacity;CHECK(!mcc_script_threads_prepare()); + CHECK(!mcc_threads.original && hs_thread_data==native); + CHECK(!mcc_checkpoint_script_storage(image,0,8,1)); + CHECK(!mcc_checkpoint_script_storage(image,0,capacity,0xFFFFFFFFu));return 0; + } + CHECK(mcc_script_threads_prepare());CHECK(!mcc_script_threads_prepare()); + storage=mcc_threads.storage;offset=(unsigned long)(storage-image); + CHECK(storage>=image+used && storage+MCC_SCRIPT_THREAD_STORAGE<=image+capacity); + if (!strcmp(argv[1],"unactivated")) { + mcc_script_threads_dispose();CHECK(native->valid && hs_thread_data==native); + CHECK(storage[0]==0xA5 && storage[MCC_SCRIPT_THREAD_STORAGE-1]==0xA5);return 0; + } + mcc_hs_threads_activate();CHECK(hs_thread_data==native && !lighting_resets); + if (!strcmp(argv[1],"migration")) memcpy(saved,image,sizeof(image)); + loaded=1;mcc_hs_threads_activate();CHECK(hs_thread_data==mcc_threads.array && lighting_resets==1); + if (!strcmp(argv[1],"bounds")) { + t=populate(hs_thread_data,1025); + CHECK(hs_stack_allocate(0,1024));CHECK(hs_stack_push(0)); + CHECK(!hs_stack_allocate(0,4096));CHECK(TEST_FLAG(t->flags,_hs_thread_stack_overflow_bit)); + CHECK(!hs_stack_push(0));mcc_script_threads_dispose();return 0; + } + if (!strcmp(argv[1],"migration")) { + CHECK(mcc_script_threads_validate(saved,image,used,capacity)); + memcpy(image,saved,sizeof(image)); + CHECK(mcc_script_threads_restore(image,used,capacity)); + t=(void *)(hs_thread_data+1); + CHECK(t->stack==(void *)(t->stack_data+101) && !memcmp(t->stack->data,"test",4)); + CHECK(t->stack->previous==(void *)(t->stack_data+20)); + CHECK(t->stack->previous->result==t->stack->previous->data); + CHECK(mcc_script_threads_capture()); + } else { + t=populate(hs_thread_data,1025); + CHECK(mcc_hs_stack_end(t)==t->stack_data+4096); + CHECK(mcc_script_threads_capture()); + memcpy(saved,image,sizeof(image));saved_storage=saved+offset; + if (!strcmp(argv[1],"snapshot")) { + FILE *output; + CHECK(argc==3); + output=fopen(argv[2],"wb");CHECK(output); + CHECK(fwrite(saved,1,sizeof(saved),output)==sizeof(saved));CHECK(!fclose(output)); + mcc_script_threads_dispose();return 0; + } + incoming=(void *)(saved_storage+16);copy=(void *)(incoming+1); + root=(void *)copy->stack_data; + CHECK(mcc_script_threads_validate(saved,image,used,capacity)); + if (!strcmp(argv[1],"checksum")) saved_storage[16]^=1; + else if (!strcmp(argv[1],"missing")) saved_storage[0]=0; + else if (!strcmp(argv[1],"flags")) copy->flags=0x80; + else if (!strcmp(argv[1],"type")) copy->type=255; + else if (!strcmp(argv[1],"sleep")) copy->sleep_until=-3; + else if (!strcmp(argv[1],"unused_slot")) ((struct hs_thread_datum *)((byte *)copy+MCC_SCRIPT_THREAD_BYTES))->identifier=4; + else if (!strcmp(argv[1],"stride")) incoming->size=512; + else if (!strcmp(argv[1],"count")) incoming->actual_count=2; + else if (!strcmp(argv[1],"pointer")) incoming->data=incoming+1; + else if (!strcmp(argv[1],"stack")) copy->stack=(void *)(t->stack_data+4090); + else if (!strcmp(argv[1],"cycle")) ((struct hs_stack_frame *)(copy->stack_data+1061))->previous=t->stack; + else if (!strcmp(argv[1],"overlap")) root->size=5; + else if (!strcmp(argv[1],"result")) root->result=&t->stack; + else if (!strcmp(argv[1],"size")) ((struct hs_stack_frame *)(copy->stack_data+1061))->size=4096; + else if (!strcmp(argv[1],"root")) root->previous=(void *)t->stack_data; + else if (!strcmp(argv[1],"other_thread")) copy->stack=(void *)((byte *)t->stack+MCC_SCRIPT_THREAD_BYTES); + else if (strcmp(argv[1],"lifecycle") && strcmp(argv[1],"roundtrip")) return 2; + if (strcmp(argv[1],"lifecycle") && strcmp(argv[1],"roundtrip")) { + if (strcmp(argv[1],"checksum") && strcmp(argv[1],"missing")) mcc_threads_stamp(saved_storage); + CHECK(!mcc_script_threads_validate(saved,image,used,capacity)); + } else { + memset(t->stack->data,0,4);memcpy(image,saved,sizeof(image)); + CHECK(mcc_script_threads_restore(image,used,capacity)); + CHECK(!memcmp(t->stack->data,"test",4)); + } + } + mcc_script_threads_dispose();CHECK(hs_thread_data==native && !mcc_threads.array); + CHECK(!native->valid && mcc_hs_stack_end((void *)(native+1))==(byte *)(native+1)+sizeof(struct hs_thread_datum)); + CHECK(storage[0]==0xA5 && storage[MCC_SCRIPT_THREAD_STORAGE-1]==0xA5); + mcc_script_threads_dispose();return 0; +} diff --git a/tools/harness/tests/mcc_scripts.c b/tools/harness/tests/mcc_scripts.c new file mode 100644 index 0000000000..813e8c57c2 --- /dev/null +++ b/tools/harness/tests/mcc_scripts.c @@ -0,0 +1,572 @@ +/* Native MCC linker tests with generated syntax, no game assets. */ +#include "cseries.h" +#include "math/real_math.h" +#include "errors.h" +#include "hs/hs.h" +#include "hs/hs_scenario_definitions.h" +#include "memory/data.h" +#include "objects/objects.h" +#include "scenario/scenario_definitions.h" +#include "mcc_runtime.h" +#include "mcc_scripts.h" +#include "mcc_campaign.h" +#include +#include +#include +#include +#include +#undef malloc +#undef free +#undef memset +#undef memcpy +#undef memcmp +#undef strcmp +#undef strcpy +#undef strlen +#undef strstr +#undef strncmp + +void mcc_executing_thread_evaluate(short f,long t,boolean i) {(void)f;(void)t;(void)i;} +void mcc_kill_thread_evaluate(short f,long t,boolean i) {(void)f;(void)t;(void)i;} +short const hs_external_global_count=443; +static boolean loaded; +static boolean resolver_case, alias_target_missing; +static unsigned native_lookups, campaign_lookups, parameter_prepares; +static struct data_array list_data; +struct data_array *object_list_header_data = &list_data; +static long arguments[3], returned; +static long equipment_unit; +static short equipment_profile; +static boolean equipment_reset; +static unsigned equipment_calls; +static unsigned deselect_calls; +void ai_scripting_deselect(void) { ++deselect_calls; } +void mcc_player_add_equipment(long unit, short profile, boolean reset) { + equipment_unit=unit;equipment_profile=profile;equipment_reset=reset;++equipment_calls; +} +static int segment_events; +static char last_event[256]; +static struct object_datum mock_object; +static int deleted_lists; +word const hs_object_type_masks[6] = {0xFFFF, 3, 2, 4, 0x380, 0x40}; +struct hs_function_definition *mcc_campaign_function(short index) { (void)index;return NULL; } +short mcc_campaign_find(char const *name) { + if (resolver_case) { + ++campaign_lookups; + if (!_stricmp(name,"physics_set_gravity")) return MCC_HS_CAMPAIGN_FIRST; + } + return NONE; +} +struct scenario *global_scenario_get(void) { return NULL; } +boolean ai_index_from_string(struct scenario *scenario, char const *name, long *result) { + (void)scenario; + if (strcmp(name, "falcon/pilot")) return FALSE; + *result = (long)0x80000018; return TRUE; +} +long object_list_from_ai_reference(long reference) { return reference == NONE ? NONE : 0; } +void object_list_delete(long list) { (void)list; ++deleted_lists; } + +void *csmemcpy(void *to, void const *from, unsigned long bytes) { return memcpy(to, from, bytes); } +void *csmemset(void *to, long value, unsigned long bytes) { return memset(to, value, bytes); } +char *csstrcpy(char *to, char const *from) {return strcpy(to,from);} +long csstrcasecmp(char const *a, char const *b) { return _stricmp(a, b); } +void error(short priority, char const *format, ...) { + va_list args; + if (priority != _error_log) return; + ++segment_events; + va_start(args, format); + _vsnprintf(last_event, sizeof(last_event) - 1, format, args); + va_end(args); + last_event[sizeof(last_event) - 1] = 0; +} +boolean mcc_cache_tags_loaded(void) { return loaded; } +boolean mcc_cache_contains(void const *data, unsigned long bytes) { (void)data; (void)bytes; return loaded; } +int mcc_parameters_prepare(struct mcc_runtime *runtime, struct scenario *scenario, struct data_array *syntax) { + (void)runtime; (void)scenario; (void)syntax; ++parameter_prepares; return 1; +} +boolean hs_macro_function_parse(short index, long expression) { (void)index; (void)expression; return TRUE; } +long *hs_macro_function_evaluate(short function, long thread, boolean initialize) { + (void)function; (void)thread; return initialize ? arguments : NULL; +} +void hs_return(long thread, long value) { (void)thread; returned = value; } +short hs_find_function_by_name(char const *name) { + if (resolver_case) { + /* The real native lookup consults the guarded MCC hook first. */ + short index=mcc_script_find(name); + if (index!=NONE) return index; + ++native_lookups; + if (!_stricmp(name,"sleep")) return 321; + if (!_stricmp(name,"player_effect_set_max_rumble")) return alias_target_missing ? NONE : 322; + /* Deliberate legacy collisions check MCC precedence and alias misses. */ + if (!_stricmp(name,"core_save_name")) return 323; + if (!_stricmp(name,"player_effect_set_max_vibrate")) return 324; + if (!_stricmp(name,"ai_select")) return 200; + if (!_stricmp(name,"ai_deselect")) return 201; + return NONE; + } + if (!strcmp(name, "sleep") || !strcmp(name,"set")) return 321; + if (!strcmp(name, "player_effect_set_max_rumble")) return 322; + return NONE; +} +short hs_find_global_by_name(char const *name) { return !strcmp(name, "known_global") ? (short)0x8009 : NONE; } +void *object_try_and_get_and_verify_type(long index, unsigned long mask) { + (void)mask; return index >= 0 && index <= 2 ? &mock_object : NULL; +} +real_point3d *object_get_origin(long index, real_point3d *point) { + point->x = index == 0 ? 1.f : index == 1 ? 8.f : 10.f; + point->y = point->z = 0; return point; +} +long object_list_get_first(long list, long *reference) { (void)list; *reference = 0; return 0; } +long object_list_get_next(long list, long *reference) { (void)list; return ++*reference == 1 ? 1 : NONE; } +void *datum_try_and_get(struct data_array *data, long handle) { + unsigned index = (unsigned)handle & 0xFFFFu; + struct hs_syntax_node *node; + if (data == &list_data) return handle == 0 ? arguments : NULL; + if (handle == NONE || index >= (unsigned)data->count) return NULL; + node = (struct hs_syntax_node *)data->data + index; + return node->datum_header == (short)((unsigned)handle >> 16) ? node : NULL; +} +void *mcc_runtime_pointer(struct mcc_runtime *runtime, uint32_t address, uint32_t bytes) { + uint32_t offset = address - runtime->report.tag_base; + return address >= runtime->report.tag_base && offset <= runtime->used && bytes <= runtime->used - offset ? + runtime->tags + offset : NULL; +} + +void *mcc_runtime_allocate(struct mcc_runtime *runtime,uint32_t bytes) { + if(runtime->used+bytes>runtime->capacity)return NULL; + {void *p=runtime->tags+runtime->used;runtime->used+=bytes;return p;} +} +#define CHECK(value) do { if (!(value)) { fprintf(stderr, "check failed at line %d\n", __LINE__); return 1; } } while (0) + +static int check_resolver(struct mcc_runtime *runtime, struct data_array *syntax, + struct hs_syntax_node *nodes, char *strings, char const *name, short expected, boolean missing) +{ + short prepared_index=!_stricmp(name,"sleep") ? 321 : expected; + short resolved; + unsigned preparation_native,preparation_campaign; + boolean prepared; + resolver_case=TRUE;alias_target_missing=missing; + strcpy(strings,name); + nodes[1].function_index=778; + CHECK(!loaded && mcc_script_find(name)==NONE && mcc_script_find(NULL)==NONE); + CHECK(!native_lookups && !campaign_lookups && !parameter_prepares); + prepared=mcc_scripts_prepare(runtime); + CHECK(prepared==(prepared_index!=NONE)); + CHECK(parameter_prepares==(unsigned)prepared); + CHECK(nodes[0].function_index==(prepared ? prepared_index : 777)); + CHECK(nodes[1].function_index==(prepared ? prepared_index : 778)); + CHECK(syntax->count==4 && syntax->actual_count==4 && syntax->maximum_count==32767); + CHECK(prepared ? !runtime->failure[0] : strstr(runtime->failure,"Unsupported script name:")!=NULL); + preparation_native=native_lookups;preparation_campaign=campaign_lookups; + native_lookups=campaign_lookups=0;loaded=TRUE; + CHECK(mcc_script_find(NULL)==NONE && !native_lookups && !campaign_lookups); + resolved=mcc_script_find(name); + CHECK(resolved==expected); + if (!_stricmp(name,"player_effect_set_max_vibrate")) CHECK(native_lookups==1); + else CHECK(!native_lookups); + printf("%s prepare=%d call=%d predicate=%d runtime=%d native=%u/%u campaign=%u/%u\n", + name,prepared,nodes[0].function_index,nodes[1].function_index,resolved, + preparation_native,native_lookups,preparation_campaign,campaign_lookups); + native_lookups=campaign_lookups=0;loaded=FALSE; + CHECK(mcc_script_find(name)==NONE && mcc_script_find(NULL)==NONE); + CHECK(!native_lookups && !campaign_lookups); + /* A later legacy lookup retains the native implementation. */ + CHECK(hs_find_function_by_name("core_save_name")==323); + CHECK(hs_find_function_by_name("player_effect_set_max_vibrate")==324); + CHECK(hs_find_function_by_name("ai_deselect")==201); + free(runtime->tags); + return 0; +} + +int main(int argc, char **argv) { + struct mcc_runtime runtime = {0}; + struct scenario *scenario; + struct data_array *syntax; + struct hs_syntax_node *nodes; + struct hs_function_definition *extension; + char *strings; + uint32_t pointer; + int expected = 1; + short segment_index; + CHECK(argc >= 2 && argc <= 4); + segment_index = !strcmp(argv[1], "core_segment") ? MCC_HS_CORE_SEGMENT : MCC_HS_MISSION_SEGMENT; + if (!strcmp(argv[1], "issue89_registry")) { + char const *names[3]={"abs_integer","get_executing_running_thread","kill_thread"}; + long values[5]={0,1,-1,2147483647L,(-2147483647L-1)}; + int j; + for(j=0;j<3;j++) { + loaded=0;CHECK(mcc_script_find(names[j])==NONE); + CHECK(!mcc_script_function((short)(0x7004+j))); + loaded=1;CHECK(mcc_script_find(names[j])==0x7004+j); + extension=mcc_script_function((short)(0x7004+j));CHECK(extension); + CHECK(extension->parameter_count==(j==1 ? 0 : 1)); + CHECK(extension->return_type==(j==2 ? _hs_type_void : _hs_type_long_integer)); + if(j!=1) CHECK(extension->parameter_types[0]==_hs_type_long_integer); + } + extension=mcc_script_function(0x7004); + for(j=0;j<5;j++) { + arguments[0]=values[j];returned=123; + extension->evaluate(0x7004,0,FALSE);CHECK(returned==123); + extension->evaluate(0x7004,0,TRUE); + CHECK((unsigned long)returned==(values[j]<0 ? 0UL-(unsigned long)values[j] : (unsigned long)values[j])); + } + return 0; + } + runtime.used = 0x100000; + runtime.capacity=runtime.used+65536; + runtime.tags = malloc(runtime.capacity); + CHECK(runtime.tags); + memset(runtime.tags, 0, runtime.used); + runtime.tag_index = runtime.tags + 40; + runtime.report.tag_base = (uint32_t)(uintptr_t)runtime.tags; + scenario = (struct scenario *)(runtime.tags + 0x100); + syntax = (struct data_array *)(runtime.tags + 0x1000); + nodes = (struct hs_syntax_node *)(syntax + 1); + strings = (char *)(runtime.tags + 0xF0000); + pointer = (uint32_t)(uintptr_t)scenario; + memcpy(runtime.tags + 60, &pointer, 4); + scenario->hs_syntax_data.address = syntax; + scenario->hs_syntax_data.size = sizeof(*syntax) + 32767 * sizeof(*nodes); + scenario->hs_string_constants.address = strings; + scenario->hs_string_constants.size = 128; + syntax->size = sizeof(*nodes); + syntax->maximum_count = 32767; + syntax->count = 4; + syntax->actual_count = 4; + syntax->first_free_absolute_index = 4; + syntax->valid = TRUE; + syntax->signature = 'd@t@'; + syntax->data = nodes; + nodes[0].datum_header = nodes[1].datum_header = nodes[2].datum_header = nodes[3].datum_header = 1; + nodes[0].flags = 8; + nodes[0].next_node_index = NONE; + nodes[0].data = 0x10001; + nodes[0].function_index = 777; + nodes[1].type = _hs_function_name; + nodes[1].flags = 1; + nodes[1].next_node_index = 0x10002; + nodes[2].type = _hs_type_object_list; + nodes[2].flags = 1; + nodes[2].next_node_index = 0x10003; + nodes[3].type = _hs_type_object; + nodes[3].flags = 1; + nodes[3].next_node_index = NONE; + strcpy(strings, "sleep"); + if (!strcmp(argv[1],"resolver") || !strcmp(argv[1],"resolver_missing_alias")) { + CHECK(argc==4); + return check_resolver(&runtime,syntax,nodes,strings,argv[2],(short)strtol(argv[3],NULL,10), + !strcmp(argv[1],"resolver_missing_alias")); + } + if (!strcmp(argv[1],"ai_deselect")) { + strcpy(strings,"ai_deselect");resolver_case=TRUE; + nodes[0].type=_hs_type_void;nodes[1].next_node_index=NONE; + CHECK(!loaded && !mcc_script_function(0x7007)); + CHECK(mcc_scripts_prepare(&runtime)); + CHECK(nodes[0].function_index==0x7007 && nodes[1].function_index==0x7007); + loaded=TRUE;extension=mcc_script_function(0x7007);CHECK(extension); + CHECK(extension->return_type==_hs_type_void && extension->parameter_count==0); + CHECK(mcc_script_find("ai_select")==NONE && hs_find_function_by_name("ai_select")==200); + CHECK(mcc_script_call_valid(nodes,syntax)); + returned=123;extension->evaluate(0x7007,0,TRUE); + CHECK(deselect_calls==1 && returned==0); + /* Like native zero-argument evaluators, completion does not depend on + * an argument frame or the initialize flag. */ + returned=123;extension->evaluate(0x7007,0,FALSE); + CHECK(deselect_calls==2 && returned==0); + nodes[1].next_node_index=0x10002;CHECK(!mcc_script_call_valid(nodes,syntax)); + nodes[1].next_node_index=NONE; + nodes[0].data=0x20001;CHECK(!mcc_script_call_valid(nodes,syntax)); + nodes[0].data=0x10001; + nodes[0].flags=0;CHECK(!mcc_script_call_valid(nodes,syntax)); + nodes[0].flags=9;CHECK(!mcc_script_call_valid(nodes,syntax)); + nodes[0].flags=10;CHECK(!mcc_script_call_valid(nodes,syntax)); + nodes[0].flags=8;loaded=FALSE; + CHECK(!mcc_script_call_valid(nodes,syntax) && !mcc_script_function(0x7007)); + CHECK(mcc_script_find("ai_deselect")==NONE && hs_find_function_by_name("ai_deselect")==201); + free(runtime.tags);return 0; + } + if (!strncmp(argv[1], "issue89_link_", 13)) { + strcpy(strings,argv[1]+13); + nodes[0].type=!strcmp(strings,"kill_thread") ? _hs_type_void : _hs_type_long_integer; + nodes[2].type=_hs_type_long_integer;nodes[2].next_node_index=NONE; + if (!strcmp(strings,"get_executing_running_thread")) nodes[1].next_node_index=NONE; + } + if (!strcmp(argv[1], "unknown")) { strcpy(strings, "not_implemented"); expected = 0; } + if (!strcmp(argv[1], "bad_child")) { nodes[0].data = 0x10008; expected = 0; } + if (!strcmp(argv[1], "child_salt")) { nodes[0].data = 0x20001; expected = 0; } + if (!strcmp(argv[1], "short_data")) { scenario->hs_syntax_data.size = sizeof(*syntax) + 4 * sizeof(*nodes); expected = 0; } + if (!strcmp(argv[1], "capacity")) syntax->count = 19002; + if (!strcmp(argv[1], "negative_count")) { syntax->count = -1; expected = 0; } + if (!strcmp(argv[1], "full_capacity")) { + syntax->count = 32767; + syntax->actual_count = 6; + nodes[32765] = nodes[0]; nodes[32765].data = 0x17FFE; + nodes[32766] = nodes[1]; nodes[32766].next_node_index = NONE; + } + if (!strcmp(argv[1], "unterminated")) { memset(strings, 'x', 128); expected = 0; } + if (!strcmp(argv[1], "equipment")) { + strcpy(strings, "player_add_equipment"); + nodes[0].type=_hs_type_void;nodes[2].type=_hs_type_unit; + nodes[3].type=_hs_type_starting_profile;nodes[3].next_node_index=0x10004; + nodes[4].datum_header=1;nodes[4].flags=1;nodes[4].type=_hs_type_boolean; + nodes[4].next_node_index=NONE;syntax->count=syntax->actual_count=5; + } + if (!strcmp(argv[1], "alias")) strcpy(strings, "player_effect_set_max_vibrate"); + if (!strcmp(argv[1], "extension")) strcpy(strings, "objects_distance_to_object"); + if (!strcmp(argv[1], "segment") || !strcmp(argv[1], "core_segment")) { + strcpy(strings, segment_index == MCC_HS_CORE_SEGMENT ? "core_save_name" : "mcc_mission_segment"); + nodes[0].type = _hs_type_boolean; + nodes[2].type = _hs_type_string; + nodes[2].next_node_index = NONE; + } + if (!strcmp(argv[1], "global")) { + nodes[0].flags = 5; nodes[0].data = 0x8001; strcpy(strings, "known_global"); + } + if (!strcmp(argv[1], "skull_read") || !strcmp(argv[1], "skull_wrong_type")) { + nodes[0].flags=5;nodes[0].data=0x8001;nodes[0].type=_hs_type_boolean; + strcpy(strings,"debug_ice_cream_flavor_status_grunt_birthday_party"); + if (!strcmp(argv[1], "skull_wrong_type")) {nodes[0].type=_hs_type_real;expected=0;} + } + if (!strcmp(argv[1], "skull_write")) { + strcpy(strings,"set");strcpy(strings+4,"debug_ice_cream_flavor_status_i_would_have_been_your_daddy"); + nodes[2].flags=5;nodes[2].data=0x8001;nodes[2].string_offset=4;nodes[2].type=_hs_type_boolean;expected=0; + } + if (!strcmp(argv[1], "developer_read") || !strcmp(argv[1], "developer_cast")) { + nodes[0].flags=13;nodes[0].data=0x8001; + nodes[0].type=!strcmp(argv[1],"developer_cast") ? _hs_type_real : _hs_type_short_integer; + strcpy(strings,"developer_mode"); + } + if (!strcmp(argv[1], "developer_write")) { + strcpy(strings,"set");strcpy(strings+4,"developer_mode"); + nodes[2].flags=5;nodes[2].data=0x8001;nodes[2].string_offset=4; + nodes[2].type=_hs_type_short_integer; + } + if (!strcmp(argv[1],"skull_disable") || !strcmp(argv[1],"skull_enable") || !strcmp(argv[1],"skull_computed")) { + strcpy(strings,"set");strcpy(strings+4,"debug_ice_cream_flavor_status_bandanna"); + nodes[0].type=_hs_type_void; + nodes[2].flags=5;nodes[2].data=0x8001;nodes[2].string_offset=4;nodes[2].type=_hs_type_boolean; + nodes[3].flags=9;nodes[3].type=nodes[3].constant_type=_hs_type_boolean;nodes[3].data=(long)0xffffff00; + if (!strcmp(argv[1],"skull_enable")) {nodes[3].data=1;expected=0;} + if (!strcmp(argv[1],"skull_computed")) {nodes[3].flags=13;expected=0;} + } + if (!strcmp(argv[1],"developer_capacity") || !strcmp(argv[1],"developer_allocation")) { + nodes[0].flags=13;nodes[0].data=0x8001;nodes[0].type=_hs_type_short_integer; + strcpy(strings,"developer_mode");expected=0; + if (!strcmp(argv[1],"developer_capacity")) scenario->hs_globals.count=1024-hs_external_global_count; + else runtime.capacity=runtime.used; + } + if (!strncmp(argv[1],"score_",6)) { + strcpy(strings,"set");strcpy(strings+4,"debug_score"); + nodes[2].flags=13;nodes[2].data=0x8001;nodes[2].string_offset=4; + nodes[2].type=_hs_type_long_integer; + if (!strcmp(argv[1],"score_capacity")) {scenario->hs_globals.count=1024-hs_external_global_count;expected=0;} + if (!strcmp(argv[1],"score_allocation")) {runtime.capacity=runtime.used;expected=0;} + } + if (argc>=3) strcpy(strings+(!strcmp(argv[1],"skull_read") || !strcmp(argv[1],"skull_wrong_type") ? 0 : 4),argv[2]); + if (argc==4) nodes[0].type=!strcmp(argv[3],"real") ? _hs_type_real : + !strcmp(argv[3],"long") ? _hs_type_long_integer : _hs_type_boolean; + if (strstr(argv[1],"prediction")==argv[1]) { + strcpy(strings,"set");strcpy(strings+4,"object_prediction");nodes[0].type=_hs_type_void; + nodes[2].flags=5;nodes[2].data=0x8001;nodes[2].string_offset=4;nodes[2].type=_hs_type_boolean; + nodes[3].flags=9;nodes[3].type=nodes[3].constant_type=_hs_type_boolean;nodes[3].data=(long)0xffffff01; + if (!strcmp(argv[1],"prediction_disable")) {nodes[3].data=0;expected=0;} + if (!strcmp(argv[1],"prediction_computed")) {nodes[3].flags=13;expected=0;} + } + if (!strcmp(argv[1],"scratch")) { + char counter[3]={'f',argc>=3 ? argv[2][0] : '0',0}; + scenario->hs_string_constants.size=1152; + strcpy(strings,"set");strcpy(strings+4,counter); + nodes[2].flags=nodes[3].flags=13;nodes[2].data=nodes[3].data=0x8001; + nodes[2].string_offset=nodes[3].string_offset=4; + nodes[2].type=nodes[3].type=_hs_type_real; + } + if (!strcmp(argv[1],"speed") || !strcmp(argv[1],"score")) { + strcpy(strings,!strcmp(argv[1],"score") ? "debug_score" : "game_speed_value"); + nodes[0].flags=nodes[2].flags=13;nodes[0].data=nodes[2].data=0x8001; + nodes[0].string_offset=nodes[2].string_offset=0; + nodes[0].type=nodes[2].type=!strcmp(argv[1],"score") ? _hs_type_long_integer : _hs_type_real; + } + CHECK(mcc_scripts_prepare(&runtime) == expected); + if (!strcmp(argv[1],"score_write")) { + struct hs_global *global=scenario->hs_globals.address; + CHECK(scenario->hs_globals.count==1 && nodes[2].data==0 && (nodes[2].flags&4)); + CHECK(global->type==_hs_type_long_integer && !strcmp(global->name,"debug_score")); + free(runtime.tags);return 0; + } + if (!strcmp(argv[1],"speed") || !strcmp(argv[1],"score")) { + struct hs_global *global=scenario->hs_globals.address; + struct hs_syntax_node *initial=datum_try_and_get(syntax,global->initialization_expression_index); + CHECK(scenario->hs_globals.count==1 && nodes[0].data==0 && nodes[2].data==0); + CHECK(global->type==nodes[0].type && initial); + CHECK(initial->data==(!strcmp(argv[1],"score") ? 0 : 0x3f800000)); + CHECK(!strcmp(global->name,!strcmp(argv[1],"score") ? "debug_score" : "game_speed_value")); + free(runtime.tags);return 0; + } + if (!strcmp(argv[1],"scratch")) { + struct hs_global *global=scenario->hs_globals.address; + struct hs_syntax_node *initial=datum_try_and_get(syntax,global->initialization_expression_index); + char const *relocated=(char const *)scenario->hs_string_constants.address+nodes[2].string_offset; + CHECK(scenario->hs_globals.count==1 && nodes[2].data==0 && nodes[3].data==0); + CHECK(global->type==_hs_type_real && initial && initial->data==0 && initial->type==_hs_type_real); + CHECK(!strcmp(global->name,relocated) && !strncmp(relocated,"__mcc_scratch_f",14)); + CHECK(nodes[2].string_offset==nodes[3].string_offset && syntax->actual_count==5); + CHECK(nodes[2].string_offseths_string_constants.size-1024); + CHECK(!memcmp((char const *)scenario->hs_string_constants.address+scenario->hs_string_constants.size-1024, + runtime.tags+0xE0000,1024)); + free(runtime.tags);return 0; + } + if (strstr(argv[1],"prediction")==argv[1]) { + if (expected) CHECK(nodes[0].flags==9 && nodes[0].data==0 && nodes[0].type==_hs_type_void && nodes[0].constant_type==nodes[0].type); + free(runtime.tags);return 0; + } + if (!strcmp(argv[1],"skull_disable")) { + CHECK(nodes[0].flags==9 && nodes[0].data==FALSE && nodes[0].constant_type==nodes[0].type); + CHECK((argc==4 || nodes[0].type==_hs_type_void) && nodes[0].next_node_index==NONE); + free(runtime.tags);return 0; + } + if (!strcmp(argv[1],"developer_write")) { + struct hs_global *global=scenario->hs_globals.address; + struct hs_syntax_node *initial; + CHECK(scenario->hs_globals.count==1 && nodes[2].data==0 && (nodes[2].flags&4)); + CHECK(!strcmp(global->name,"developer_mode") && global->type==_hs_type_short_integer); + initial=datum_try_and_get(syntax,global->initialization_expression_index); + CHECK(initial && initial->flags==9 && initial->short_value==0 && initial->type==_hs_type_short_integer); + CHECK(initial->next_node_index==NONE && initial->source_offset==NONE); + } + if (!strcmp(argv[1], "developer_read") || !strcmp(argv[1], "developer_cast")) { + CHECK((nodes[0].flags&4) && nodes[0].data==0 && scenario->hs_globals.count==1); + CHECK(((struct hs_global *)scenario->hs_globals.address)->type==_hs_type_short_integer); + CHECK(syntax->actual_count==5); + CHECK(nodes[0].type==(!strcmp(argv[1],"developer_cast") ? _hs_type_real : _hs_type_short_integer)); + free(runtime.tags);return 0; + } + if (!expected) { free(runtime.tags); return 0; } + if (!strcmp(argv[1], "skull_read")) { + CHECK(!(nodes[0].flags&4) && nodes[0].data==FALSE && nodes[0].constant_type==_hs_type_boolean); + free(runtime.tags);return 0; + } + CHECK(syntax->maximum_count == 32767); + CHECK(syntax->data == nodes); + if (!strcmp(argv[1], "full_capacity")) { + CHECK(nodes[32765].function_index == 321 && nodes[32766].function_index == 321); + } + CHECK(mcc_script_find("player_add_equipment") == NONE); + CHECK(!mcc_script_function(MCC_HS_DISTANCE_TO_OBJECT)); + CHECK(!mcc_script_function(MCC_HS_MISSION_SEGMENT)); + CHECK(!mcc_script_function(MCC_HS_CORE_SEGMENT)); + CHECK(mcc_script_find("core_save_name") == NONE); + CHECK(mcc_script_find("objects_distance_to_object") == NONE); + CHECK(mcc_script_find("mcc_mission_segment") == NONE); + loaded = TRUE; + { + struct hs_syntax_node ai = {0}; + CHECK(mcc_script_ai_cast(_hs_type_ai, _hs_type_unit)); + CHECK(mcc_script_can_cast(_hs_type_short_integer, _hs_type_long_integer)); + CHECK(mcc_script_cast(_hs_type_short_integer, _hs_type_long_integer, 0xFFFF) == -1); + CHECK(mcc_script_cast(_hs_type_short_integer, _hs_type_long_integer, 32767) == 32767); + CHECK(mcc_script_cast(_hs_type_short_integer, _hs_type_long_integer, 0x8000) == -32768); + CHECK(!mcc_script_can_cast(_hs_type_long_integer, _hs_type_short_integer)); + ai.flags = 9; ai.constant_type = _hs_type_ai; ai.type = _hs_type_unit; + CHECK(mcc_script_parse_ai(&ai, "falcon/pilot") == 1 && ai.data == (long)0x80000018); + CHECK(mcc_script_parse_ai(&ai, "missing/pilot") == 0); + ai.flags |= 4; + CHECK(mcc_script_parse_ai(&ai, "falcon/pilot") == -1); + CHECK(mcc_script_cast_ai(_hs_type_unit, 24) == 0 && deleted_lists == 1); + CHECK(mcc_script_cast_ai(_hs_type_vehicle, 24) == NONE && deleted_lists == 2); + CHECK(mcc_script_cast_ai(_hs_type_object_list, 24) == 0 && deleted_lists == 2); + CHECK(mcc_script_cast_ai(_hs_type_unit, NONE) == NONE); + loaded = FALSE; + CHECK(!mcc_script_ai_cast(_hs_type_ai, _hs_type_unit)); + CHECK(!mcc_script_can_cast(_hs_type_short_integer, _hs_type_long_integer)); + loaded = TRUE; + } + if (!strncmp(argv[1], "issue89_link_", 13)) { + short index=mcc_script_find(strings); + CHECK(index!=NONE && nodes[0].function_index==index && nodes[1].function_index==index); + CHECK(mcc_script_call_valid(nodes,syntax)); + if (!strcmp(strings,"get_executing_running_thread")) nodes[1].next_node_index=0x10002; + else nodes[2].type=_hs_type_string; + CHECK(!mcc_script_call_valid(nodes,syntax)); + free(runtime.tags);return 0; + } + CHECK(mcc_script_find("player_effect_set_max_vibrate") == 322); + CHECK(mcc_script_find("MCC_MISSION_SEGMENT") == MCC_HS_MISSION_SEGMENT); + CHECK(mcc_script_find("CORE_SAVE_NAME") == MCC_HS_CORE_SEGMENT); + if (!strcmp(argv[1], "equipment")) { + short index=mcc_script_find("PLAYER_ADD_EQUIPMENT"); + CHECK(index!=NONE && nodes[0].function_index==index && nodes[1].function_index==index); + extension=mcc_script_function(index); + CHECK(extension && extension->parameter_count==3 && extension->return_type==_hs_type_void); + CHECK(mcc_script_call_valid(nodes,syntax)); + nodes[4].type=_hs_type_real;CHECK(!mcc_script_call_valid(nodes,syntax)); + nodes[4].type=_hs_type_boolean;nodes[4].next_node_index=0x10002; + CHECK(!mcc_script_call_valid(nodes,syntax)); + arguments[0]=123;arguments[1]=0xFFFF0007;arguments[2]=(long)0xFFFFFF01; + extension->evaluate(index,0,FALSE);CHECK(!equipment_calls); + extension->evaluate(index,0,TRUE); + CHECK(equipment_calls==1 && equipment_unit==123 && equipment_profile==7 && equipment_reset==TRUE); + arguments[2]=(long)0xFFFFFF00;extension->evaluate(index,0,TRUE); + CHECK(equipment_calls==2 && equipment_reset==FALSE); + loaded=FALSE;CHECK(!mcc_script_function(index)); + } else if (!strcmp(argv[1], "global")) CHECK((unsigned short)nodes[0].short_value == 0x8009); + else if (!strcmp(argv[1], "alias")) CHECK(nodes[0].function_index == 322); + else if (!strcmp(argv[1], "extension")) { + union { long bits; float value; } result; + CHECK(nodes[0].function_index == MCC_HS_DISTANCE_TO_OBJECT); + CHECK(mcc_script_call_valid(&nodes[0], syntax)); + nodes[3].type = _hs_type_real; + CHECK(!mcc_script_call_valid(&nodes[0], syntax)); + extension = mcc_script_function(MCC_HS_DISTANCE_TO_OBJECT); + CHECK(extension && extension->parameter_types[1] == _hs_type_object); + arguments[0] = 0; arguments[1] = 2; + extension->evaluate(MCC_HS_DISTANCE_TO_OBJECT, 0, TRUE); + result.bits = returned; + CHECK(result.value == 2.f); + arguments[0] = NONE; + extension->evaluate(MCC_HS_DISTANCE_TO_OBJECT, 0, TRUE); + result.bits = returned; + CHECK(result.value == -1.f); + } else if (!strcmp(argv[1], "segment") || !strcmp(argv[1], "core_segment")) { + char long_segment[200]; + CHECK(nodes[0].function_index == segment_index); + CHECK(nodes[1].function_index == segment_index); + CHECK(mcc_script_call_valid(&nodes[0], syntax)); + extension = mcc_script_function(segment_index); + CHECK(extension && extension->return_type == _hs_type_boolean); + CHECK(extension->parameter_count == 1 && extension->parameter_types[0] == _hs_type_string); + nodes[2].type = _hs_type_real; + CHECK(!mcc_script_call_valid(&nodes[0], syntax)); + nodes[2].type = _hs_type_string; + nodes[1].next_node_index = NONE; + CHECK(!mcc_script_call_valid(&nodes[0], syntax)); + nodes[1].next_node_index = 0x20002; + CHECK(!mcc_script_call_valid(&nodes[0], syntax)); + nodes[1].next_node_index = 0x10002; + nodes[2].next_node_index = 0x10003; + CHECK(!mcc_script_call_valid(&nodes[0], syntax)); + nodes[2].next_node_index = NONE; + arguments[0] = (long)(uintptr_t)"cine1_intro"; + returned = -123; + extension->evaluate(segment_index, 0, FALSE); + CHECK(returned == -123 && !segment_events); /* argument expression still yielding */ + extension->evaluate(segment_index, 0, TRUE); + CHECK(returned == TRUE && segment_events == 1); + CHECK(!strcmp(last_event, "mcc: mission segment 'cine1_intro'")); + arguments[0] = (long)(uintptr_t)"03_escape"; /* use the evaluated argument each time */ + extension->evaluate(segment_index, 0, TRUE); + CHECK(returned == TRUE && segment_events == 2); + CHECK(!strcmp(last_event, "mcc: mission segment '03_escape'")); + memset(long_segment, 'x', sizeof(long_segment)); long_segment[199] = 0; + arguments[0] = (long)(uintptr_t)long_segment; + extension->evaluate(segment_index, 0, TRUE); + CHECK(returned == TRUE && segment_events == 3 && strlen(last_event) == 151); + arguments[0] = 0; + extension->evaluate(segment_index, 0, TRUE); + CHECK(returned == FALSE && segment_events == 3); + loaded = FALSE; + CHECK(!mcc_script_function(segment_index)); + CHECK(mcc_script_find("mcc_mission_segment") == NONE); + } else CHECK(nodes[0].function_index == 321 && nodes[1].function_index == 321); + free(runtime.tags); + return 0; +} diff --git a/tools/harness/tests/mcc_sprites.c b/tools/harness/tests/mcc_sprites.c new file mode 100644 index 0000000000..f2fe35e3fb --- /dev/null +++ b/tools/harness/tests/mcc_sprites.c @@ -0,0 +1,100 @@ +#include +#include +#include +#include +typedef float real; +typedef unsigned char boolean; +typedef unsigned short word; +typedef struct {real x,y,z;} real_point3d; +typedef struct {real i,j,k;} real_vector3d; +typedef struct {real a,r,g,b;} real_argb_color; +struct shader_effect_definition {int sentinel;}; +struct shader {int sentinel;}; +struct bitmap_data {int id;}; +/* HEADER */ +#define TRUE 1 +#define FALSE 0 +#define NONE (-1) +#define FLAG(b) (1u<<(b)) +#define TEST_FLAG(v,b) ((v)&FLAG(b)) +#define SET_FLAG(v,b,t) ((v)=(t)?((v)|FLAG(b)):((v)&~FLAG(b))) +#define NUMBER_OF_VERTICES_PER_QUADRILATERAL 4 +#define MAXIMUM_BUILD_SPRITE_GROUPS 8 +#define _build_sprites_valid_bit NUMBER_OF_BUILD_SPRITES_FLAGS +#define _rasterizer_geometry_viewspace_bit 5 +#define _rasterizer_geometry_first_person_bit 7 +#define _rasterizer_lock_sprite 1 +#define _rasterizer_lock_none 0 +#define _error_silent 0 +#define CHECK(x) do {if(!(x)){fprintf(stderr,"line %d: %s\n",__LINE__,#x);exit(1);}}while(0) +static int assertions; +#define match_assert(f,l,x) do {if(!(x))assertions++;}while(0) +#define match_vassert(f,l,x,msg) match_assert(f,l,x) +static int loaded,ce,depth,draws,unlocks,deletes,allocations,fail_alloc; +static int expected_first_person; +static unsigned drawn[80]; +static char vertices[80]; +static struct {int current_lock_operation;} rasterizer_globals; +static struct {struct {int view_to_world;} frustum;} render; +static real_point3d origin; +static real_point3d const *global_origin3d=&origin; +static int mcc_cache_tags_loaded(void){return loaded;} +static int custom_edition_cache_tags_loaded(void){return ce;} +static void viewmodel_projection_begin(void){depth++;} +static void viewmodel_projection_end(void){CHECK(depth>0);depth--;} +static void matrix4x3_transform_point(int const *m,real_point3d const *in,real_point3d *out){(void)m;*out=*in;} +static int _texture_cache_bitmap_get_hardware_format(struct bitmap_data *b,int a,int c){(void)b;(void)a;(void)c;return 1;} +static long rasterizer_dynamic_vertices_new(int type,int count){CHECK(type==6);CHECK(count>0);return fail_alloc?NONE:allocations++;} +static void *rasterizer_dynamic_vertices_lock(long i){CHECK(i>=0&&i<80);return vertices+i;} +static void rasterizer_dynamic_vertices_unlock(long i){CHECK(i>=0&&i=0&&isentinel==123&&a==NULL&&q==-4&&v>=0&&n>0); + CHECK(c->x==2&&c->y==3&&c->z==4); + CHECK(!!TEST_FLAG(flags,_rasterizer_geometry_first_person_bit)==expected_first_person); + CHECK(b->id>=0&&b->id<80);drawn[b->id]+=(unsigned)n/2;draws++; +} +static char const *tag_get_name(long i){(void)i;return "test";} +static void error(int level,char const *fmt,...){(void)level;(void)fmt;} +/* IMPLEMENTATION */ +int main(void){ + struct build_sprite_data data; + struct shader_effect_definition shader={123}; + struct bitmap_data bitmaps[80]; + int i,pass; + short g; + for(i=0;i<80;i++)bitmaps[i].id=i; + for(pass=0;pass<2;pass++){ + memset(&data,0,sizeof(data));memset(drawn,0,sizeof(drawn)); + loaded=1;expected_first_person=pass;allocations=draws=unlocks=deletes=0; + build_sprites_begin(&data,65,77,&shader,pass?FLAG(_build_sprites_first_person_bit):0); + for(i=0;i<65;i++){ + CHECK(data.sprite_count=0&&g<8); + CHECK(data.bitmap_group_index==77&&data.shader==&shader); + CHECK(depth==pass&&data.group_count<=8); + if(i==7)CHECK(build_sprite_get_group(&data,bitmaps)==0&&draws==0); + data.groups[g].sprite_count++;data.sprite_count++; + data.centroid.x+=2;data.centroid.y+=3;data.centroid.z+=4; + } + CHECK(data.sprite_count==data.maximum_sprite_count); + build_sprites_end(&data); + CHECK(draws==65&&unlocks==65&&deletes==65&&depth==0&&assertions==0); + for(i=0;i<65;i++)CHECK(drawn[i]==1); + } + /* Original Xbox assertion and CE refusal still apply without MCC. */ + loaded=0;expected_first_person=0;allocations=0; + for(pass=0;pass<2;pass++){ + ce=pass;build_sprites_begin(&data,10,77,&shader,0); + for(i=0;i<8;i++)CHECK(build_sprite_get_group(&data,bitmaps+i)==i); + CHECK(build_sprite_get_group(&data,bitmaps+8)==NONE); + CHECK(assertions==1&&data.group_count==8&&data.maximum_sprite_count==10); + } + /* A failed allocation is not drawn and cannot leak a locked buffer. */ + loaded=1;ce=0;fail_alloc=1;draws=unlocks=deletes=0; + build_sprites_begin(&data,10,77,&shader,0); + for(i=0;i<17;i++)CHECK(build_sprite_get_group(&data,bitmaps+i)==NONE); + CHECK(assertions==1&&draws==0&&unlocks==0&&deletes==0); + return 0; +} diff --git a/tools/harness/tests/mcc_syntax.c b/tools/harness/tests/mcc_syntax.c new file mode 100644 index 0000000000..d82eb02f7d --- /dev/null +++ b/tools/harness/tests/mcc_syntax.c @@ -0,0 +1,203 @@ +/* Generated MCC syntax blobs: no shipped game data or external resources. */ +#include "cseries.h" +#include "math/real_math.h" +#include "errors.h" +#include "hs/hs.h" +#include "hs/hs_scenario_definitions.h" +#include "memory/data.h" +#include "scenario/scenario_definitions.h" +#include "mcc_syntax.h" +#include +#include +#include +#include +#undef memset +#undef memcpy +#undef memcmp +#undef malloc +#undef free +#undef strcmp +#undef strcpy + +#define CHECK(x) do { if (!(x)) { fprintf(stderr, "check failed at line %d\n", __LINE__); return 1; } } while (0) + +static boolean loaded; +static unsigned char *allocation; +static long allocation_bytes; +static char strings[1024]; +static unsigned errors, visited; + +void *csmemset(void *buffer, long value, unsigned long bytes) { return memset(buffer, (int)value, bytes); } +boolean mcc_cache_tags_loaded(void) { return loaded; } +boolean mcc_cache_contains(void const *pointer, long bytes) +{ + uintptr_t address = (uintptr_t)pointer, base = (uintptr_t)allocation; + if (bytes < 0) return FALSE; + if (address >= base && address - base <= (unsigned long)allocation_bytes && + (unsigned long)bytes <= (unsigned long)allocation_bytes - (address - base)) return TRUE; + return pointer == strings && bytes <= sizeof(strings); +} +void error(short severity, char const *format, ...) { (void)severity; (void)format; ++errors; } + +static long handle(unsigned index) { return (long)(0x81230000u | index); } +static short refusal(struct hs_syntax_node const *node, char const **name) +{ + ++visited; + *name = node->source_offset == 99 ? "blocked_function" : NULL; + return node->source_offset == 99 ? 1 : 0; +} +static void live_node(struct hs_syntax_node *node) +{ + node->datum_header = (short)0x8123; + node->flags = 9; + node->type = node->constant_type = _hs_type_boolean; + node->next_node_index = NONE; +} + +int main(int argc, char **argv) +{ + struct data_array *syntax; + struct hs_syntax_node *nodes; + struct scenario scenario = {0}; + struct hs_script scripts[2] = {0}; + struct hs_global globals[1] = {0}; + unsigned long disabled_scripts[16] = {0}, disabled_globals[32] = {0}; + unsigned char *before; + long bytes; + unsigned i; + int expected = 1; + char const *test; + CHECK(argc == 2); + test = argv[1]; + allocation_bytes = sizeof(*syntax) + MCC_SYNTAX_CAPACITY * sizeof(*nodes); + allocation = malloc(allocation_bytes); + before = malloc(allocation_bytes); + CHECK(allocation && before); + memset(allocation, 0, allocation_bytes); + syntax = (struct data_array *)allocation; + nodes = (struct hs_syntax_node *)(syntax + 1); + syntax->signature = 'd@t@'; + syntax->size = sizeof(*nodes); + syntax->maximum_count = MCC_SYNTAX_CAPACITY; + syntax->valid = TRUE; + syntax->identifier_zero_invalid = TRUE; + syntax->count = syntax->actual_count = 2; + syntax->data = (void *)1; /* File pointer is stale; validation must ignore it. */ + for (i = 0; i < 2; ++i) live_node(nodes + i); + bytes = allocation_bytes; + + if (!strcmp(test, "empty")) { + syntax->count = syntax->actual_count = 0; + memset(nodes, 0, 2 * sizeof(*nodes)); + } else if (!strcmp(test, "high_slot") || !strcmp(test, "callbacks")) { + syntax->count = MCC_SYNTAX_CAPACITY; + memset(nodes + 1, 0, sizeof(*nodes)); + live_node(nodes + MCC_SYNTAX_CAPACITY - 1); + nodes[0].flags = 8; + nodes[0].data = handle(MCC_SYNTAX_CAPACITY - 1); + } else if (!strcmp(test, "sparse")) { + syntax->count = 19723; + syntax->actual_count = 18480; + memset(nodes, 0, 2 * sizeof(*nodes)); + for (i = 1243; i < 19723; ++i) live_node(nodes + i); + } else if (!strcmp(test, "deep") || !strcmp(test, "wide") || !strcmp(test, "deep_cycle")) { + syntax->count = syntax->actual_count = MCC_SYNTAX_CAPACITY; + for (i = 0; i < MCC_SYNTAX_CAPACITY; ++i) { + live_node(nodes + i); + if (i + 1 < MCC_SYNTAX_CAPACITY) { + if (!strcmp(test, "wide") && i) nodes[i].next_node_index = handle(i + 1); + else { nodes[i].flags = 8; nodes[i].data = handle(i + 1); } + } + } + if (!strcmp(test, "deep_cycle")) { + nodes[MCC_SYNTAX_CAPACITY - 1].next_node_index = handle(0); + expected = 0; + } + } else if (!strcmp(test, "salt")) { nodes[0].next_node_index = handle(1) ^ 0x10000; expected = 0; + } else if (!strcmp(test, "zero_salt")) { nodes[0].next_node_index = 1; expected = 0; + } else if (!strcmp(test, "out_of_range")) { nodes[0].next_node_index = handle(32767); expected = 0; + } else if (!strcmp(test, "unused")) { nodes[1].datum_header = 0; syntax->actual_count = 1; nodes[0].next_node_index = handle(1); expected = 0; + } else if (!strcmp(test, "sibling_cycle")) { nodes[0].next_node_index = handle(1); nodes[1].next_node_index = handle(0); expected = 0; + } else if (!strcmp(test, "call_cycle")) { nodes[0].flags = 8; nodes[0].data = handle(0); expected = 0; + } else if (!strcmp(test, "short_blob")) { --bytes; expected = 0; + } else if (!strcmp(test, "long_blob")) { ++bytes; expected = 0; + } else if (!strcmp(test, "negative_count")) { syntax->count = -1; expected = 0; + } else if (!strcmp(test, "negative_capacity")) { syntax->maximum_count = (short)0x8000; expected = 0; + } else if (!strcmp(test, "count_over_capacity")) { syntax->maximum_count = 1; expected = 0; + } else if (!strcmp(test, "actual_count")) { syntax->actual_count = 1; expected = 0; + } else if (!strcmp(test, "negative_actual")) { syntax->actual_count = -1; expected = 0; + } else if (!strcmp(test, "free_hint")) { syntax->first_free_absolute_index = -1; expected = 0; + } else if (!strcmp(test, "signature")) { syntax->signature = 0; expected = 0; + } else if (!strcmp(test, "node_size")) { ++syntax->size; expected = 0; + } else if (!strcmp(test, "invalid_array")) { syntax->valid = FALSE; expected = 0; + } + memcpy(before, allocation, allocation_bytes); + CHECK(mcc_syntax_graph_valid(syntax, bytes) == expected); + CHECK(!memcmp(before, allocation, allocation_bytes)); + CHECK(!mcc_syntax_graph_valid(NULL, bytes)); + CHECK(!mcc_syntax_graph_valid(syntax, 1)); + CHECK(!mcc_syntax_graph_valid((struct data_array *)(allocation + 1), bytes)); + if (!expected) { free(before); free(allocation); return 0; } + + scenario.hs_syntax_data.address = syntax; + scenario.hs_syntax_data.size = bytes; + scenario.hs_string_constants.address = strings; + scenario.hs_string_constants.size = sizeof(strings); + CHECK(mcc_syntax_scenario_valid((struct scenario *)1) == -1); + CHECK(!mcc_syntax_functions_check((struct scenario *)1, (struct data_array *)1, NULL, NULL, NULL)); + loaded = TRUE; + CHECK(mcc_syntax_scenario_valid(&scenario) == 1); + scenario.hs_string_constants.size = 1023; + CHECK(mcc_syntax_scenario_valid(&scenario) == 0); + scenario.hs_string_constants.size = 1024; + scenario.hs_syntax_data.size = bytes + 1; + CHECK(mcc_syntax_scenario_valid(&scenario) == 0); + scenario.hs_syntax_data.size = bytes; + scenario.hs_syntax_data.address = (void *)1; + CHECK(mcc_syntax_scenario_valid(&scenario) == 0); + scenario.hs_syntax_data.address = syntax; + CHECK(mcc_syntax_scenario_valid(NULL) == 0); + + if (!strcmp(test, "callbacks") || !strcmp(test, "wide") || !strcmp(test, "deep") || + !strcmp(test, "root_type") || !strcmp(test, "damaged_root") || !strcmp(test, "shared_child")) { + scenario.hs_scripts.count = 1; + scenario.hs_scripts.address = scripts; + scenario.hs_globals.count = 1; + scenario.hs_globals.address = globals; + strcpy(scripts[0].name, "script"); + scripts[0].root_expression_index = handle(0); + scripts[0].return_type = _hs_type_boolean; + globals[0].initialization_expression_index = NONE; + globals[0].type = _hs_type_boolean; + if (!strcmp(test, "root_type")) scripts[0].return_type = _hs_type_void; + if (!strcmp(test, "damaged_root")) scripts[0].root_expression_index = handle(32767); + if (!strcmp(test, "shared_child")) { + syntax->count = syntax->actual_count = 3; + live_node(nodes + 2); + nodes[0].flags = nodes[1].flags = 8; + nodes[0].data = handle(1); + nodes[1].data = handle(2); + nodes[1].next_node_index = handle(2); /* Acyclic, but two references within one expression. */ + CHECK(mcc_syntax_graph_valid(syntax, bytes)); + } + CHECK(mcc_syntax_functions_check(&scenario, syntax, refusal, disabled_scripts, disabled_globals)); + if (!strcmp(test, "root_type") || !strcmp(test, "damaged_root") || !strcmp(test, "shared_child")) { + CHECK(disabled_scripts[0] == 1 && !disabled_globals[0] && errors == 2); + } else { + CHECK(!disabled_scripts[0] && !disabled_globals[0] && !errors); + CHECK(visited == (unsigned)syntax->actual_count); + } + if (!strcmp(test, "callbacks")) { + nodes[MCC_SYNTAX_CAPACITY - 1].source_offset = 99; + globals[0].initialization_expression_index = handle(MCC_SYNTAX_CAPACITY - 1); + CHECK(mcc_syntax_functions_check(&scenario, syntax, refusal, disabled_scripts, disabled_globals)); + CHECK(disabled_scripts[0] == 1 && disabled_globals[0] == 1 && errors == 2); + loaded = FALSE; + CHECK(!mcc_syntax_functions_check(&scenario, syntax, refusal, disabled_scripts, disabled_globals)); + CHECK(disabled_scripts[0] == 1 && disabled_globals[0] == 1 && errors == 2); + } + } + free(before); + free(allocation); + return 0; +} diff --git a/tools/harness/tests/muzzle_lighting.c b/tools/harness/tests/muzzle_lighting.c new file mode 100644 index 0000000000..afe7804975 --- /dev/null +++ b/tools/harness/tests/muzzle_lighting.c @@ -0,0 +1,159 @@ +#include "harness.h" +#define PIN(x,a,b) ((x)<(a)?(a):(x)>(b)?(b):(x)) +#define MAX(a,b) ((a)>(b)?(a):(b)) +#define NUMBEROF(a) (sizeof(a)/sizeof((a)[0])) +typedef struct { real red,green,blue; } real_rgb_color; +typedef struct { real_point3d position; real_vector3d forward; } real_matrix4x3; +enum { _object_invisible_bit, _point_light_port_glow_bit, _point_light_connected_to_map_bit, MAXIMUM_WEAPONS_PER_UNIT=4 }; +struct weapon_datum { long definition_index; struct { long parent_object_index; int flags; struct { int size; } node_matrices; } object; }; +struct unit_datum { struct { short current_weapon_index; } unit; }; +struct object_marker { real_matrix4x3 matrix; }; +struct observer_result { real_point3d position; }; +static struct weapon_datum weapons[21]; +static struct unit_datum unit; +static struct observer_result camera; +static const char *tag="weapons\\assault rifle\\assault rifle"; +static int on=1,present=1,held=1,marker=1,world_marker,allocs,deletes,disconnects,submits,fail,missing; +static long tick=30; +static real render_time=1.0f, marker_x=0.5f; +static real_vector3d forward={1,0,0}; +static const real_vector3d *global_forward3d=&forward; +struct light_datum { long object_index,definition_index; int flags; real_point3d position; real_rgb_color color; real radius; int active; }; +static struct light_datum lights[64]; +static struct { int valid; } data={1},*light_data=&data; +static long light_port_glow_definition=99; +int lighting_config_boolean(const char *n) { return on; } +static long game_time_get(void) { return tick; } +real render_interpolation_game_time_sec(long t) { return render_time; } +static struct weapon_datum *weapon_try_and_get(long w) { return present && w>=0 && w<12 ? &weapons[w] : NULL; } +static struct weapon_datum *object_get(long w) { return &weapons[w]; } +static struct unit_datum *unit_try_and_get(long u) { return present && u==20 ? &unit : NULL; } +static const char *tag_get_name(long d) { return tag; } +static long unit_inventory_get_weapon(long u,short s) { return held; } +static int first_person_weapon_adjust_light(long w,const char *n,real_point3d *p,real_vector3d *f,real_vector3d *u) { p->x=marker_x;p->y=p->z=0;*f=forward;return marker; } +static int object_get_marker_by_name(long w,const char *n,struct object_marker *m,short c) { m->matrix.forward=forward;m->matrix.position.x=!strcmp(n,"cannon flash")?4:marker_x;m->matrix.position.y=m->matrix.position.z=0;return world_marker; } +static short local_player_get_next(short p) { return p==NONE?0:NONE; } +static const struct observer_result *observer_get_camera(short p) { return &camera; } +static real distance3d(const real_point3d *a,const real_point3d *b) { return a->x-b->x; } +long light_port_glow_definition_get(void) { return missing?NONE:99; } +static struct light_datum *datum_try_and_get(void *a,long i) { return i>=0 && iobject_index!=o || l->definition_index!=99)return FALSE; + l->color=*c;l->radius=r;l->flags|=FLAG(_point_light_port_glow_bit);return TRUE; +} +static void light_delete(long i) { lights[i].active=0;deletes++; } +static void light_disconnect_from_map(long i) { CHECK(TEST_FLAG(lights[i].flags,_point_light_connected_to_map_bit),"disconnect once");lights[i].flags&=~FLAG(_point_light_connected_to_map_bit);disconnects++; } +static void light_reconnect_to_map(long i) { CHECK(!TEST_FLAG(lights[i].flags,_point_light_connected_to_map_bit),"reconnect once");lights[i].flags|=FLAG(_point_light_connected_to_map_bit); } +void plasma_occlusion_submit(long l,long r) { submits++; } +#include "under_test.inc" +int main(int argc,char **argv) +{ + int i; real old; long light; const char *name=argv[1]; + for(i=0;i<12;i++) { weapons[i].object.parent_object_index=20;weapons[i].object.node_matrices.size=sizeof(real_matrix4x3); } + if(!strcmp(name,"pulse")) + { + muzzle_lighting_shot(1,0);CHECK(!allocs,"shot is cosmetic bookkeeping only");muzzle_lighting_update(); + CHECK(allocs==1 && lights[0].color.red==1,"initial full pulse"); + muzzle_lighting_submitted(0,3);CHECK(muzzle_lighting_selected(3) && submits==1,"selected and occluded"); + muzzle_lighting_frame_end();CHECK(!lights[0].color.red && !TEST_FLAG(lights[0].flags,_point_light_connected_to_map_bit),"dark and disconnected during simulation"); + render_time=1.025f;marker_x=0.75f;muzzle_lighting_update();old=lights[0].color.red; + CHECK(old>0 && old<1 && lights[0].position.x==0.75f,"subtick fade and rendered marker motion"); + muzzle_lighting_shot(1,0);muzzle_lighting_update();CHECK(lights[0].color.red==old && allocs==1,"same tick does not duplicate or restart"); + render_time=1.05f;muzzle_lighting_update();CHECK(lights[0].color.red2.079f&&lights[1].position.x<2.081f,"distinct rendered sources beyond barrels"); + CHECK(muzzle_lighting_vehicle_occlusion(0)&&muzzle_lighting_vehicle_occlusion(1),"both guns include chassis blockers"); + muzzle_lighting_frame_end();render_time=1.05f;tick++;muzzle_lighting_update();old=lights[0].color.red; + muzzle_lighting_shot(1,1);muzzle_lighting_update(); + CHECK(lights[0].color.red==old&&lights[1].color.red==1&&allocs==2,"machinegun does not restart or replace cannon pulse"); + muzzle_lighting_shot(1,1);render_time=1.08f;muzzle_lighting_update(); + CHECK(lights[1].color.red<1,"duplicate shot does not postpone machinegun decay"); + render_time=1.18f;tick+=4;muzzle_lighting_update(); + CHECK(lights[0].active&&!lights[1].active,"each trigger expires on its own envelope"); + on=0;muzzle_lighting_update();CHECK(deletes==2,"disable releases both tank lights"); + } + else if(!strcmp(name,"move")) + { + real_point3d p={3,2,1};muzzle_lighting_shot(1,0);muzzle_lighting_update();muzzle_lighting_frame_end(); + CHECK(light_port_glow_move(0,&p) && lights[0].position.x==3,"move disconnected glow"); + CHECK(muzzle_lighting_radius(0,0.2f)==1.8f,"maximum bounds cover own radius"); + CHECK(muzzle_lighting_radius(25,0.2f)==0.2f,"unowned bounds untouched"); + lights[0].object_index=1;CHECK(!light_port_glow_move(0,&p),"attached light cannot be moved"); + lights[0].object_index=NONE;light_data->valid=0;CHECK(!light_port_glow_move(0,&p),"invalid array cannot be moved"); + } + return 0; +} diff --git a/tools/harness/tests/plasma_collision.c b/tools/harness/tests/plasma_collision.c new file mode 100644 index 0000000000..8178c823df --- /dev/null +++ b/tools/harness/tests/plasma_collision.c @@ -0,0 +1,188 @@ +#include "harness.h" +#include +#include +#define MAX(a,b) ((a)>(b)?(a):(b)) +#define MIN(a,b) ((a)<(b)?(a):(b)) +#define MAXIMUM_OBJECTS_PER_MAP 1024 +#define MAXIMUM_CLUSTERS_PER_STRUCTURE 4 +#define MAXIMUM_BREAKABLE_SURFACES_PER_MAP 256 +#define REAL_MAX 3.402823466e38F +enum { PLASMA_COLLISION_RAYS=1536, PLASMA_COLLISION_WORDS=48 }; +#define MAXIMUM_BSP3D_TRAVERSAL_DEPTH 128 +#define TAG_BLOCK_GET_ELEMENT(b,i,t) (&((t *)(b)->address)[i]) +#define _object_invisible_bit 0 +enum { _collision_test_structure_bit, _collision_test_objects_bit, + _collision_test_front_facing_surfaces_bit, _collision_test_back_facing_surfaces_bit, + _collision_test_objects_first_type_bit, _collision_test_objects_scenery_bit=_collision_test_objects_first_type_bit, + _collision_test_objects_machines_bit, _collision_test_objects_vehicles_bit }; +struct collision_model_instance { long object_index; }; +struct collision_bsp_test_vector_result { real t; int leaf_count; long leaf_indices[256]; }; +struct collision_model_test_vector_result { struct collision_bsp_test_vector_result bsp_result; }; +struct collision_result { real t; }; +struct structure_leaf { short cluster_index; }; +struct structure_bsp { struct { long count; void *address; } leaves; }; +typedef struct { real_vector3d n; real d; } real_plane3d; +struct bsp3d_node { long plane_designator, children[2]; }; +struct collision_bsp { struct { struct { long count; void *address; } nodes, planes; } bsp3d; }; +struct collision_bsp_vector_cache; +static struct collision_bsp bsp; +static struct bsp3d_node nodes[4]; +static real_plane3d planes[4]; +static long queried_node; +static short queried_depth; +static real plane3d_distance_to_point(const real_plane3d *p,const real_point3d *v) +{ return p->n.i*v->x+p->n.j*v->y+p->n.k*v->z-p->d; } +struct object_datum { struct { long next_object_index, first_child_object_index; real_point3d bounding_sphere_center; + real bounding_sphere_radius; unsigned long flags; int type; } object; }; +static struct object_datum objects[1024]; +static struct structure_leaf leaves[2]; +static struct structure_bsp structure; +static int roots[1024], root_count, stock_calls, reads, model_builds, cluster_reads; +static float object_depth[1024], structure_depth; +static int bad_leaf, debug_collision_skip_objects, debug_collision_skip_vectors; +static struct object_datum *object_get(long index) { reads++; return &objects[index]; } +static struct structure_bsp *global_structure_bsp_get(void) { return &structure; } +static struct collision_bsp *global_collision_bsp_get(void) { return &bsp; } +static void *breakable_surface_flags_get(void) { return NULL; } +static int collision_bsp_test_vector_from_node(unsigned long flags,const struct collision_bsp *bsp,int breaks,void *bits, + const real_point3d *p,const real_vector3d *v,float limit,struct collision_bsp_test_vector_result *r,long start,short depth,struct collision_bsp_vector_cache *cache) +{ queried_node=start;queried_depth=depth;r->t=structure_depth;r->leaf_count=2;r->leaf_indices[0]=bad_leaf?9:0;r->leaf_indices[1]=1;return structure_depth<1; } +static long cluster_get_first_collideable_object(long *reference,short cluster) +{ cluster_reads++;*reference=0;return root_count?roots[0]:NONE; } +static long cluster_get_next_collideable_object(long *reference) +{ return ++*referenceobject_index=index;return object_depth[index]>=0; } +static int collision_model_test_vector(const struct collision_model_instance *m,unsigned long flags, + const real_point3d *p,const real_vector3d *v,struct collision_model_test_vector_result *r) +{ r->bsp_result.t=object_depth[m->object_index];return r->bsp_result.t<1; } +static int collision_test_vector(unsigned long flags,const real_point3d *p,const real_vector3d *v,long ignore,struct collision_result *r) +{ stock_calls++;r->t=.123f;return 1; } +static void plasma_collision_model_depths(const struct collision_model_instance *m,const real_point3d *p, + const real_vector3d *v,int count,const unsigned int *mask,float *depths) +{ int i;for(i=0;iobject_index];if(d>=0&&d<1&&dcenter,cached->radius),"cached sphere matches engine predicate"); + plasma_collision_end(); + } + { + real_vector3d vectors[PLASMA_COLLISION_RAYS+1]; + real expected[PLASMA_COLLISION_RAYS+1],actual[PLASMA_COLLISION_RAYS+1]; + setup();p.x=p.y=p.z=0;root_count=2;object_depth[0]=-1; + objects[0].object.first_child_object_index=1;objects[1].object.next_object_index=2; + object_depth[1]=.4f;object_depth[2]=.2f;objects[2].object.bounding_sphere_center.y=.8f; + objects[2].object.bounding_sphere_radius=.3f; + plasma_collision_begin(flags,&p,NONE); + for(i=0;i +#define REAL_MAX FLT_MAX +#define MAXIMUM_REGIONS_PER_OBJECT 4 +#define MIN(a,b) ((a)<(b)?(a):(b)) +#define MAX(a,b) ((a)>(b)?(a):(b)) +#define PIN(a,b,c) MIN(MAX(a,b),c) +#define TAG_BLOCK_GET_ELEMENT(b,i,t) (&((t *)(b)->address)[i]) +enum { PLASMA_COLLISION_RAYS=1536, PLASMA_COLLISION_WORDS=48, + _collision_test_front_facing_surfaces_bit=0, _collision_test_back_facing_surfaces_bit=1, _error_silent=0 }; +typedef struct { long long QuadPart; } LARGE_INTEGER; +struct block { long count; void *address; }; +struct collision_bsp { struct { struct block nodes; } bsp3d; int axis; float boundary; }; +struct collision_node { short region_index; struct block bsps; }; +struct collision_model { struct block nodes; }; +struct collision_bsp_vector_cache { int unused; }; +struct collision_bsp_test_vector_result { real t; }; +struct collision_model_test_vector_result { struct collision_bsp_test_vector_result bsp_result; short node_index,region_index,bsp_index; }; +static int inversions, diagnostics, warned_about_collision_model_regions; +static void error(int level,const char *format,...) { diagnostics++; } +static void collision_log_usage(int n) {} +static void collision_log_start_time(LARGE_INTEGER *t) { t->QuadPart=0; } +static void collision_log_end_time(int n,long long t) {} +static int collision_bsp_test_vector_from_node(unsigned long flags,const struct collision_bsp *b,int breaks,const byte *bits, + const real_point3d *p,const real_vector3d *v,real limit,struct collision_bsp_test_vector_result *r,long node,short depth,struct collision_bsp_vector_cache *cache) +{ + real a=b->axis==0?p->x:b->axis==1?p->y:p->z; + real d=b->axis==0?v->i:b->axis==1?v->j:v->k; + real t; + CHECK(flags==3 && !breaks && !bits && !node && !depth,"model BSP call retains original flags/root contract"); + r->t=limit;if(d==0)return 0;t=(b->boundary-a)/d; + if(t>=0&&t<=1&&tt=t;return 1;}return 0; +} +static int collision_bsp_test_vector(unsigned long flags,const struct collision_bsp *b,int breaks,const byte *bits, + const real_point3d *p,const real_vector3d *v,real limit,struct collision_bsp_test_vector_result *r) +{ return collision_bsp_test_vector_from_node(flags,b,breaks,bits,p,v,limit,r,0,0,NULL); } +#include "under_test.inc" +int main(int argc,char **argv) +{ + struct collision_model model;struct collision_node nodes[4];struct collision_bsp bsps[4][2]; + real_matrix4x3 matrices[4];struct collision_model_instance instance; + real_point3d point={.1f,-.2f,.3f};real_vector3d vectors[PLASMA_COLLISION_RAYS]; + real actual[PLASMA_COLLISION_RAYS+2],expected[PLASMA_COLLISION_RAYS+2]; + unsigned int pending[PLASMA_COLLISION_WORDS];byte permutations[4]={0,255,1,0}; + int trial,i,n,count,old_inversions; + memset(matrices,0,sizeof(matrices));memset(bsps,0,sizeof(bsps)); + model.nodes.count=4;model.nodes.address=nodes; + instance.model=&model;instance.node_count=4;instance.region_permutation_indices=permutations;instance.matrices=matrices; + for(n=0;n<4;n++) + { + nodes[n].region_index=n;nodes[n].bsps.count=2;nodes[n].bsps.address=bsps[n]; + matrices[n].scale=1;matrices[n].forward.i=matrices[n].left.j=matrices[n].up.k=1; + matrices[n].position.x=n*.13f;matrices[n].position.y=-n*.17f; + for(i=0;i<2;i++){bsps[n][i].bsp3d.nodes.count=1;bsps[n][i].axis=(n+i)%3;bsps[n][i].boundary=.35f+n*.09f+i*.2f;} + } + for(trial=0;trial<64;trial++) + { + count=trial&1?96:PLASMA_COLLISION_RAYS; + matrices[1].forward.i=trial%2?.6f:1;matrices[1].forward.j=trial%2?.8f:0; + matrices[1].left.i=-matrices[1].forward.j;matrices[1].left.j=matrices[1].forward.i; + memset(pending,0,sizeof(pending)); + nodes[2].region_index=trial%5==0?NONE:2; + nodes[3].bsps.count=trial%7==0?0:2; + matrices[0].scale=trial%4==0?0:trial%4==1?.5f:trial%4==2?-2.f:1.f; + for(i=0;iinversions*10,"node transforms are shared across the entire ray batch"); + } + nodes[0].region_index=5;diagnostics=0;warned_about_collision_model_regions=0; + for(i=0;i +#define MAX(a,b) ((a)>(b)?(a):(b)) +#define _object_mask_scenery 1 +#define _object_mask_machine 2 +#define _object_mask_vehicle 4 +#define _object_invisible_bit 0 +#define _object_has_collision_model_bit 1 +#define MAXIMUM_BREAKABLE_SURFACES_PER_MAP 256 +static boolean debug_collision_skip_vectors, debug_collision_skip_objects; +static long global_scenario_index, global_structure_bsp_index; +static unsigned char broken[32]; +static float matrices[3][8192]; +struct object_datum { long definition_index; struct { + unsigned long flags; short type; long first_cluster_reference_index, next_object_index, + first_child_object_index, parent_object_index; real_point3d bounding_sphere_center; + real bounding_sphere_radius; unsigned char region_permutations[8]; + struct { short size; } node_matrices; +} object; } objects[3]; +struct object_iterator { long index; unsigned long mask; }; +struct object_cluster_iterator { int visited; }; +static short membership[3]; +static short object_get_first_cluster(struct object_cluster_iterator *it,long i) {it->visited=1;return membership[i];} +static short object_get_next_cluster(struct object_cluster_iterator *it,long i) {return NONE;} +static int count=3, reads; +static void object_iterator_new(struct object_iterator *i,unsigned long mask,int unused) { i->index=-1;i->mask=mask; } +static struct object_datum *object_iterator_next(struct object_iterator *i) +{ + while(++i->indexmask & (1<index)) {reads++;return &objects[i->index];} + return NULL; +} +static void *object_get_node_matrices(long i) { return matrices[i]; } +typedef struct {float values[12];} real_matrix4x3; +struct collision_model_instance {short node_count; const real_matrix4x3 *matrices;}; +static int collision_model_instance_new(struct collision_model_instance *m,long i) +{m->node_count=objects[i].object.node_matrices.size<0?-1:objects[i].object.node_matrices.size/48;m->matrices=(const real_matrix4x3 *)matrices[i];return 1;} +static void *breakable_surface_flags_get(void) { return broken; } +#include "under_test.inc" +static struct plasma_collision_scene scenes[2]; +static real_point3d point; +static unsigned long next(int vehicles) { return plasma_collision_scene_revision(&scenes[vehicles],&point,1,vehicles); } +int main(int argc,char **argv) +{ + unsigned long a,b;int i,offset; + for(i=0;i<3;i++) objects[i].object.node_matrices.size=48; + a=next(0);CHECK(a && reads==2,"ordinary field snapshots scenery and machines only"); + CHECK(next(0)==a,"equal inputs reuse revision"); + matrices[2][0]=2;CHECK(next(0)==a,"ordinary fields ignore vehicle motion"); + b=next(1);matrices[2][0]=3;CHECK(next(1)!=b,"vehicle blockers track their rendered pose"); +#define CHANGE(value) value++; b=next(0);CHECK(b!=a,"changed collision input invalidates");a=b + CHANGE(matrices[0][0]); CHANGE(matrices[1][0]); + CHANGE(objects[0].object.region_permutations[0]); + CHANGE(objects[0].object.bounding_sphere_center.x); + CHANGE(objects[0].object.bounding_sphere_radius); + CHANGE(objects[0].object.next_object_index); + CHANGE(objects[0].object.first_child_object_index); + CHANGE(objects[0].object.parent_object_index); + CHANGE(objects[0].definition_index); + CHANGE(objects[0].object.flags); + CHANGE(membership[0]); + CHANGE(global_structure_bsp_index); CHANGE(global_scenario_index); + CHANGE(broken[0]); CHANGE(debug_collision_skip_vectors); CHANGE(debug_collision_skip_objects); +#undef CHANGE + count=1;b=next(0);CHECK(b!=a,"removed blocker invalidates");a=b; + count=3;b=next(0);CHECK(b!=a,"new blocker invalidates");a=b; + objects[0].object.node_matrices.size=-1;b=next(0);CHECK(b!=a && next(0)!=b,"invalid input never certifies reuse"); + objects[0].object.node_matrices.size=48; + memset(scenes,0,sizeof(scenes));a=next(0);CHECK(a && next(0)==a,"field reset starts new snapshots"); + objects[0].object.first_cluster_reference_index++;CHECK(next(0)==a,"partition allocation handles do not describe geometry"); + objects[1].object.bounding_sphere_center.x=100;a=next(0);matrices[1][0]++;CHECK(next(0)==a,"distant door motion does not invalidate local fields"); + objects[1].object.bounding_sphere_center.x=0;CHECK(next(0)!=a,"blocker entering the light volume invalidates"); + offset=PLASMA_COLLISION_SCENE_BYTES;CHECK(scene_append(&scenes[0],&offset,broken,1) && offset==-1,"overflow refuses partial comparison"); + return 0; +} diff --git a/tools/harness/tests/plasma_falloff.c b/tools/harness/tests/plasma_falloff.c new file mode 100644 index 0000000000..db80233c66 --- /dev/null +++ b/tools/harness/tests/plasma_falloff.c @@ -0,0 +1,98 @@ +#include "harness.h" +#include +#include +#define MAX(a,b) ((a) > (b) ? (a) : (b)) +typedef struct { int unused; } IDirect3DVolumeTexture8; +typedef IDirect3DVolumeTexture8 D3DBaseTexture; +typedef IDirect3DVolumeTexture8 D3DResource; +typedef struct { void *pBits; } D3DLOCKED_BOX; +enum { D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, D3DTSS_MINFILTER, D3DTEXF_LINEAR, D3DTEXF_POINT }; +static struct { struct { int index; } distance_attenuation; } globals, *global_rasterizer_data = &globals; +static IDirect3DVolumeTexture8 texture; +static unsigned long texels[64*64*64]; +static int selected, fail_create, creates, releases, binds, restores, filter, bound_stage, restored_stage; +typedef struct { real red, green, blue; } real_rgb_color; +static struct { long light_count; struct { real_rgb_color color; } lights[2]; } rasterizer_lights; +static unsigned long real_rgb_color_to_pixel32(real_rgb_color const *c) +{ return ((unsigned long)(c->red*255) << 16) | ((unsigned long)(c->green*255) << 8) | (unsigned long)(c->blue*255); } +static int plasma_lighting_selected(long index) { return selected; } +static int D3DDevice_CreateVolumeTexture(int w,int h,int d,int levels,int usage,int format,int pool,IDirect3DVolumeTexture8 **out) +{ creates++; if (fail_create) return -1; *out = &texture; return 0; } +static int IDirect3DVolumeTexture8_LockBox(IDirect3DVolumeTexture8 *t,int l,D3DLOCKED_BOX *box,void *b,int f) +{ box->pBits = texels; return 0; } +static int IDirect3DVolumeTexture8_UnlockBox(IDirect3DVolumeTexture8 *t,int l) { return 0; } +static void rasterizer_xbox_bitmap_swizzle3d_long(void *d,void *s,int w,int h,int depth) { memcpy(d,s,w*h*depth*sizeof(long)); } +static void D3DDevice_SetTexture(int stage,D3DBaseTexture *t) { CHECK(stage == 2 || stage == 1, "only attenuation stages"); bound_stage=stage; binds++; } +static void D3DDevice_SetTextureState_Deferred(int stage,int state,int value) { filter = value; } +static void rasterizer_set_texture_direct(int stage,int bitmap,int mip) { restored_stage=stage; restores++; } +static void D3DResource_Release(D3DResource *t) { releases++; } +void *plasma_occlusion_texture(long index,int specular) { return NULL; } +void plasma_occlusion_reset(void) {} +void plasma_falloff_dispose(void); +#include "under_test.inc" +int main(int argc, char **argv) +{ + int i; + real previous = 1.0f; + if (!strcmp(argv[1], "curve")) + { + CHECK(plasma_falloff_value(0) == 1 && plasma_falloff_value(1) == 0 && plasma_falloff_value(2) == 0, "bounded endpoints"); + for (i=0; i<=100; i++) + { + real value = plasma_falloff_value(i/100.0f); + CHECK(value >= 0 && value <= previous, "monotonic nonnegative falloff"); + previous = value; + } + CHECK(plasma_falloff_value(0.999f)/0.001f < 0.01f, "slope approaches zero at boundary"); + } + else if (!strcmp(argv[1], "scope")) + { + plasma_falloff_begin(0); plasma_falloff_end(); + CHECK(!creates && !binds && !restores, "stock pass untouched"); + selected=1; plasma_falloff_begin(0); + CHECK(creates == 1 && binds == 1 && filter == D3DTEXF_LINEAR, "selected pass uses smooth texture"); + CHECK(texels[0] == 0 && texels[64*64*64-1] == 0 && texels[(32*64+32)*64+32] > 0xF0000000UL, "dark corners and luminous center"); + selected=0; plasma_falloff_end(); + CHECK(restores == 1 && filter == D3DTEXF_POINT, "restore even after disabling"); + plasma_falloff_end(); plasma_falloff_dispose(); plasma_falloff_dispose(); + CHECK(restores == 1 && releases == 1, "idempotent end and cleanup"); + } + else if (!strcmp(argv[1], "specular")) + { + plasma_falloff_specular_begin(0); CHECK(!binds,"unselected specular stays stock"); + selected=1; plasma_falloff_specular_begin(0); + CHECK(bound_stage==1 && filter==D3DTEXF_LINEAR,"specular uses attenuation stage one"); + plasma_falloff_end(); + CHECK(restored_stage==1 && filter==D3DTEXF_LINEAR,"specular filter restored"); + plasma_falloff_begin(0); + CHECK(bound_stage==2,"diffuse follows specular independently"); + plasma_falloff_dispose(); + CHECK(restored_stage==2 && filter==D3DTEXF_POINT && releases==1,"cleanup restores latest stage"); + } + else if (!strcmp(argv[1], "tint")) + { + rasterizer_lights.light_count=1; + rasterizer_lights.lights[0].color.green=0.5f; + plasma_specular_begin(0); + CHECK(plasma_specular_color(0xAABBCCDDUL)==0xAABBCCDDUL,"stock reflection is bit exact"); + selected=1; plasma_specular_begin(0); + CHECK(plasma_specular_color(0xAABBCCDDUL)==0xAA00CC00UL,"selected green light retains material green and alpha"); + plasma_falloff_end(); + CHECK(plasma_specular_color(0xAABBCCDDUL)==0xAABBCCDDUL,"end restores colour even with no texture bound"); + plasma_specular_begin(0); plasma_specular_begin(-1); + CHECK(plasma_specular_color(0x00FFFFFFUL)==0x00FFFFFFUL,"invalid index resets hue"); + rasterizer_lights.lights[0].color.red=0.5f; + rasterizer_lights.lights[0].color.blue=0.5f; + plasma_specular_begin(0); + CHECK(plasma_specular_color(0xAABBCCDDUL)==0xAABBCCDDUL,"neutral light preserves material"); + rasterizer_lights.lights[0].color.red=0; + plasma_specular_begin(0); selected=0; plasma_specular_begin(0); + CHECK(plasma_specular_color(0xAABBCCDDUL)==0xAABBCCDDUL,"next stock light cannot inherit tint"); + } + else + { + selected=1; fail_create=1; plasma_falloff_begin(0); plasma_falloff_end(); + CHECK(!binds && !restores, "allocation failure retains stock rendering"); + } + return 0; +} diff --git a/tools/harness/tests/plasma_lighting.c b/tools/harness/tests/plasma_lighting.c new file mode 100644 index 0000000000..ab054410a1 --- /dev/null +++ b/tools/harness/tests/plasma_lighting.c @@ -0,0 +1,330 @@ +#include "harness.h" +#define NUMBEROF(a) (sizeof(a)/sizeof((a)[0])) +#include + +enum { _object_type_projectile = 5 }; +enum { _point_light_dynamic_bit = 0, _point_light_connects_to_map_bit = 1, + _point_light_connected_to_map_bit = 2 }; +#define SET_FLAG(value, bit, enabled) ((value) = (enabled) ? ((value) | (1 << (bit))) : ((value) & ~(1 << (bit)))) +struct object_datum { long definition_index; struct { short type; } object; }; +static struct object_datum projectile = { 1, { _object_type_projectile } }; +static const char *tag_name = "weapons\\plasma rifle\\bolt"; +static int muzzle_on, emitter_on, shield_on; +static int enabled = 1, refreshes, present = 1, interpolation_rendering = 1; +static int rendered_pose; +static float connected_radius; +int lighting_config_boolean(const char *name) { return strcmp(name, "display.muzzle_lighting") ? enabled : muzzle_on; } +static struct object_datum *object_try_and_get(long index) { return present ? &projectile : NULL; } +static const char *tag_get_name(long index) { return tag_name; } +struct light_datum { long object_index, parent_light_index; int flags; float radius; long definition_index; real_point3d position; real_vector3d forward; }; +struct rasterizer_light_submit_parameters { real_point3d position; real_vector3d forward; real radius; }; +static struct { long light_count; struct rasterizer_light_submit_parameters lights[32]; } rasterizer_lights; +static struct { int valid; } storage = { 1 }, *light_data = &storage; +static int stale; +static struct light_datum *datum_try_and_get(void *data, long index) +{ + static struct light_datum light; + light.object_index = index + stale; + light.parent_light_index = NONE; + return &light; +} +enum { _light_definition_no_specular_bit = 1 }; +#define _pi 3.14159265f +struct point_light_definition { real radius_modifier_upper_bound, radius, specular_radius_multiplier, lens_flare_radius, cutoff_angle, runtime_cosine_cutoff_angle, runtime_sine_cutoff_angle; int flags; }; +static struct point_light_definition light_definition = {1,1,2,0,2,1,1,0}; +static struct point_light_definition *light_definition_get(long i) { return &light_definition; } +static struct light_datum *light_get(long i) { return datum_try_and_get(light_data,i); } +float rocket_lighting_radius(long l,long o,float r) { return r; } +static void light_compute_bounding_sphere(long i,boolean m,boolean s,boolean f,real_point3d *p,real *r); +static void light_disconnect_from_map(long index) +{ + struct light_datum *light = light_get(index); + if (TEST_FLAG(light->flags, _point_light_connects_to_map_bit)) + { + CHECK(TEST_FLAG(light->flags, _point_light_connected_to_map_bit), "disconnect requires map membership"); + SET_FLAG(light->flags, _point_light_connected_to_map_bit, FALSE); + } +} +static void light_reconnect_to_map(long index) +{ + refreshes++; + if (TEST_FLAG(light_get(index)->flags, _point_light_connects_to_map_bit)) + SET_FLAG(light_get(index)->flags, _point_light_connected_to_map_bit, TRUE); + rendered_pose = interpolation_rendering; + { real_point3d p; light_compute_bounding_sphere(index, TRUE, FALSE, TRUE, &p, &connected_radius); } +} +void plasma_occlusion_model_slot(long i, short s) {} +static int visibility_resets; +void plasma_occlusion_reset(void) { visibility_resets++; } +void muzzle_lighting_frame_end(void) {} +void muzzle_lighting_window_begin(void) {} +void muzzle_lighting_submitted(long l,long r) {} +int muzzle_lighting_selected(long i) { return muzzle_on && i == 20; } +float muzzle_lighting_radius(long l,float r) { return r; } +void rocket_lighting_frame_end(void) {} +void rocket_lighting_window_begin(void) {} +void rocket_lighting_submitted(long i,long r) {} +int rocket_lighting_selected(long i) { return 0; } +void plasma_occlusion_window(void) {} +void plasma_occlusion_submit(long i,long r) {} +void plasma_lighting_reset(void); +int plasma_lighting_selected(long index); +void plasma_falloff_dispose(void) {} +void plasma_falloff_end(void) {} +int covenant_emitter_lighting_enabled(void) { return emitter_on; } +void covenant_emitter_lighting_frame_end(void) {} +void covenant_emitter_lighting_window_begin(void) {} +void covenant_emitter_lighting_submitted(long i,long r) {} +int covenant_emitter_lighting_selected(long i) { return emitter_on && i == 22; } +float covenant_emitter_lighting_radius(long l,float r) { return r; } +void covenant_lighting_frame_end(void) {} +void covenant_lighting_window_begin(void) {} +void covenant_lighting_submitted(long i,long r) {} +int covenant_lighting_selected(long i) { return 0; } +int covenant_lighting_owns(long l,long o) { return l == 21; } +float covenant_lighting_radius(long l,long o,float r) { return r; } +int shield_glow_enabled(void) { return shield_on; } +int shield_glow_selected(long i) { return shield_on && i == 23; } +void shield_glow_frame_end(void) {} +void shield_glow_window_begin(void) {} +void shield_glow_submitted(long l,long r) {} +float shield_glow_radius(long l,float r) { return r; } +int authored_emitter_lighting_enabled(void) { return 0; } +int authored_emitter_lighting_profile(long o,long d,float *s) { return 0; } +int authored_emitter_lighting_category_enabled(int c) { return enabled; } +#include "under_test.inc" + +int main(int argc, char **argv) +{ + int i; + const char *test = argv[1]; + + if (!strcmp(test, "shield")) + { + enabled = muzzle_on = emitter_on = 0; shield_on = 1; + CHECK(plasma_lighting_selected(23), "shield-only selection"); + plasma_model_lighting_slot(23, 0); + CHECK(plasma_model_lighting_mask() == 1, "shield-only model lighting"); + plasma_lighting_frame_end(); + CHECK(visibility_resets == 0, "shield-only cache retained"); + shield_on = 0; + CHECK(!plasma_lighting_selected(23), "disabled shield not selected"); + } + else if (!strcmp(test, "counter_cache")) + { + enabled = muzzle_on = 0; + emitter_on = 1; + plasma_lighting_frame_end(); + CHECK(visibility_resets == 0, "emitter-only frame retains directional textures"); + emitter_on = 0; + plasma_lighting_frame_end(); + CHECK(visibility_resets == 1, "disabled lighting releases visibility cache"); + } + else if (!strcmp(test, "covenant")) + { + const char *names[] = {"vehicles\\ghost\\ghost bolt", "vehicles\\banshee\\banshee bolt", "vehicles\\banshee\\banshee fuel rod", "vehicles\\c gun turret\\c gun turret", "weapons\\fuel rod gun\\fuel rod", "weapons\\needler\\needle", "vehicles\\wraith\\wraith mortar", "weapons\\plasma_cannon\\plasma_cannon"}; + float scales[] = {1.75f,1.75f,2.75f,2.5f,2.75f,1.5f,1.75f,2.75f}; + for(i=0;i<8;i++) { + tag_name=names[i];plasma_lighting_prepare(1,1, NONE); + CHECK(plasma_lighting_radius(1,1,1)==scales[i],"Covenant authored radius"); + plasma_lighting_frame_end(); + CHECK(plasma_lighting_radius(1,1,1)==1,"Covenant restore"); + } + plasma_lighting_prepare(21,21, NONE);CHECK(plasma_lighting_count==0,"owned glow bypasses authored restore"); + } + else if (!strcmp(test, "radius")) + { + const char *names[] = {"weapons\\plasma rifle\\bolt", "weapons\\plasma pistol\\bolt", + "weapons\\plasma rifle\\charged bolt", "weapons\\rocket launcher\\rocket"}; + float scales[] = {1.75f, 2.25f, 2.75f, 1.75f}; + real_point3d position; + real radius; + for (i = 0; i < 4; i++) + { + tag_name = names[i]; enabled = 1; + datum_try_and_get(light_data, 1)->radius = 0.5f; + plasma_lighting_prepare(1, 1, NONE); + CHECK(plasma_lighting_radius(1, 1, 1.0f) == scales[i], "per-projectile reach"); + CHECK(connected_radius == 2.0f * scales[i], "partition sees tuned radius before submission"); + datum_try_and_get(light_data, 1)->radius = scales[i]; + light_compute_bounding_sphere(1, FALSE, FALSE, FALSE, &position, &radius); + CHECK(radius == scales[i], "actual bounds do not scale twice"); + light_compute_bounding_sphere(1, FALSE, TRUE, FALSE, &position, &radius); + CHECK(radius == 2.0f * scales[i], "specular keeps authored multiplier"); + plasma_lighting_prepare(1, 1, NONE); + CHECK(plasma_lighting_radius(1, 1, 1.0f) == scales[i], "split views do not compound radius"); + CHECK(plasma_lighting_radius(1, 2, 1.0f) == 1.0f, "wrong owner untouched"); + datum_try_and_get(light_data, 1)->radius = 9.0f; + enabled = 0; + CHECK(plasma_lighting_radius(1, 1, 1.0f) == 1.0f, "disabled policy is stock"); + plasma_lighting_frame_end(); + CHECK(datum_try_and_get(light_data, 1)->radius == 0.5f, "radius restored even when disabled"); + CHECK(connected_radius == 2.0f, "partition restored to stock"); + } + } + else if (!strcmp(test, "rocket")) + { + tag_name = "weapons\\rocket launcher\\rocket"; + plasma_lighting_prepare(1, 1, NONE); + plasma_lighting_submitted(1, 3); + CHECK(plasma_lighting_selected(3), "rocket flight attachment selected"); + render_interpolation_frame_end(); + CHECK(!plasma_lighting_selected(3), "rocket selection expires with frame"); + CHECK(!datum_try_and_get(light_data, 1)->flags, "rocket dynamic state restored"); + tag_name = "weapons\\rocket launcher\\explosion"; + plasma_lighting_prepare(1, 1, NONE); + tag_name = "weapons\\rocket launcher\\effects\\rocket explosion"; + plasma_lighting_prepare(1, 1, NONE); + CHECK(refreshes == 2, "explosion attachments stay stock"); + } + else if (!strcmp(test, "pistol")) + { + const char *names[] = { "weapons\\plasma pistol\\bolt", "weapons\\plasma rifle\\charged bolt" }; + for (i = 0; i < 2; i++) + { + tag_name = names[i]; + interpolation_rendering = 1; + datum_try_and_get(light_data, 1)->flags = i ? 7 : 0; + plasma_lighting_prepare(1, 1, NONE); + plasma_lighting_submitted(1, 3); + CHECK(plasma_lighting_selected(3), "pistol projectile attachment selected"); + render_interpolation_frame_end(); + CHECK(!plasma_lighting_selected(3), "pistol light expires with render frame"); + CHECK(datum_try_and_get(light_data, 1)->flags == (i ? 7 : 0), "pistol authored flags restored"); + } + tag_name = "weapons\\plasma pistol\\muzzle flash"; + plasma_lighting_prepare(1, 1, NONE); + CHECK(refreshes == 4, "muzzle effects excluded"); + } + else if (!strcmp(test, "model")) + { + plasma_lighting_prepare(1,1, NONE); plasma_lighting_submitted(1,3); + plasma_model_lighting_slot(3,0); plasma_model_lighting_slot(7,1); + CHECK(plasma_model_lighting_mask()==1,"only selected slot is softened"); + plasma_model_lighting_slot(3,1); + CHECK(plasma_model_lighting_mask()==3,"both selected slots supported"); + plasma_model_lighting_slot(NONE,0); + CHECK(plasma_model_lighting_mask()==2,"empty slot clears previous model"); + enabled=0; CHECK(!plasma_model_lighting_mask(),"disable immediately gates model state"); + enabled=1; plasma_lighting_window_begin(); + CHECK(!plasma_model_lighting_mask(),"next view clears slots"); + plasma_lighting_submitted(1,3); plasma_model_lighting_slot(3,1); + plasma_lighting_frame_end(); + CHECK(!plasma_model_lighting_mask(),"frame cleanup clears slots"); + } + else if (!strcmp(test, "muzzle")) + { + enabled=0; muzzle_on=1; + CHECK(plasma_lighting_selected(20), "muzzle uses shared soft falloff independently"); + CHECK(!plasma_lighting_selected(3), "unrelated light stays stock"); + plasma_model_lighting_slot(20,0); + CHECK(plasma_model_lighting_mask()==1,"muzzle model slot works without projectile lighting"); + muzzle_on=0; CHECK(!plasma_model_lighting_mask(),"both off restores stock model"); + } + else if (!strcmp(test, "off")) + { + enabled = 0; + plasma_lighting_prepare(1, 1, NONE); + CHECK(!refreshes, "disabled changes no attachments"); + } + else if (!strcmp(test, "filter")) + { + tag_name = "weapons\\rocket launcher\\explosion"; + plasma_lighting_prepare(1, 1, NONE); + tag_name = "weapons\\plasma rifle\\bolt"; + projectile.object.type = 0; + plasma_lighting_prepare(1, 1, NONE); + CHECK(!refreshes, "other projectile tags and object types stay stock"); + } + else if (!strcmp(test, "restore")) + { + plasma_lighting_prepare(1, 1, NONE); + CHECK(rendered_pose && refreshes == 1, "draw uses render pose"); + CHECK(datum_try_and_get(light_data, 1)->flags == 1, "lens-flare attachment promoted only for rendering"); + enabled = 0; + render_interpolation_frame_end(); + CHECK(!rendered_pose && refreshes == 2, "disable still restores simulation pose"); + CHECK(datum_try_and_get(light_data, 1)->flags == 0, "original dynamic flag restored"); + plasma_lighting_frame_end(); + CHECK(refreshes == 2, "restoration happens once"); + } + else if (!strcmp(test, "split")) + { + plasma_lighting_prepare(1, 1, NONE); + plasma_lighting_prepare(1, 1, NONE); + CHECK(refreshes == 1, "two views share one attachment refresh"); + } + else if (!strcmp(test, "capacity")) + { + for (i = 0; i < 130; i++) plasma_lighting_prepare(i, i, NONE); + CHECK(refreshes == 128, "overflow leaves excess lights untouched"); + render_interpolation_frame_end(); + CHECK(refreshes == 256 && !rendered_pose, "every accepted light restored"); + } + else if (!strcmp(test, "unload")) + { + plasma_lighting_prepare(1, 1, NONE); + plasma_lighting_reset(); + render_interpolation_frame_end(); + CHECK(refreshes == 1, "old map handles never revisited"); + } + else if (!strcmp(test, "missing")) + { + present = 0; + plasma_lighting_prepare(1, 1, NONE); + plasma_lighting_frame_end(); + CHECK(!refreshes, "deleted projectile cannot acquire a render light"); + } + else if (!strcmp(test, "stale")) + { + plasma_lighting_prepare(1, 1, NONE); + stale = 1; + render_interpolation_frame_end(); + CHECK(refreshes == 1, "changed light owner is not restored"); + storage.valid = 0; + plasma_lighting_prepare(2, 2, NONE); + CHECK(refreshes == 1, "invalid light storage is untouched"); + } + else if (!strcmp(test, "selection")) + { + plasma_lighting_prepare(1, 1, NONE); + plasma_lighting_submitted(1, 3); + CHECK(plasma_lighting_selected(3) && !plasma_lighting_selected(2), "only submitted plasma lights selected"); + CHECK(!plasma_lighting_selected(NONE), "failed submission excluded"); + plasma_lighting_window_begin(); + CHECK(!plasma_lighting_selected(3), "view indices cannot leak across split screen"); + plasma_lighting_submitted(1, 0); + enabled = 0; + CHECK(!plasma_lighting_selected(0), "disable immediately restores stock selection"); + emitter_on = 1; + CHECK(plasma_lighting_selected(22) && !plasma_lighting_selected(0), "emitter-only option selects only emitter lights"); + plasma_model_lighting_reset(); + plasma_model_lighting_slot(22, 0); + CHECK(plasma_model_lighting_mask() == 1, "emitter-only option reaches model lighting"); + } + else if (!strcmp(test, "disconnected")) + { + struct light_datum *light = light_get(1); + int flags = 1 << _point_light_connects_to_map_bit; + light->flags = flags; + plasma_lighting_prepare(1, 1, NONE); + CHECK(!refreshes && light->flags == flags, "disconnected attachment stays outside the map"); + CHECK(!plasma_lighting_count, "failed refresh does not admit a render attachment"); + plasma_lighting_frame_end(); + CHECK(!refreshes && light->flags == flags, "frame cleanup preserves disconnected state"); + SET_FLAG(light->flags, _point_light_connected_to_map_bit, TRUE); + flags = light->flags; + plasma_lighting_prepare(1, 1, NONE); + CHECK(refreshes == 1 && plasma_lighting_count == 1, "engine reconnect permits later admission"); + plasma_lighting_frame_end(); + CHECK(refreshes == 2 && light->flags == flags, "connected attachment restores authored flags"); + } + else if (!strcmp(test, "existing")) + { + datum_try_and_get(light_data, 1)->flags = 1; + plasma_lighting_prepare(1, 1, NONE); + render_interpolation_frame_end(); + CHECK(datum_try_and_get(light_data, 1)->flags == 1, "authored dynamic lighting stays dynamic"); + } + return 0; +} diff --git a/tools/harness/tests/plasma_model_shader.c b/tools/harness/tests/plasma_model_shader.c new file mode 100644 index 0000000000..ca394401b5 --- /dev/null +++ b/tools/harness/tests/plasma_model_shader.c @@ -0,0 +1,113 @@ +#include "harness.h" +#include +typedef unsigned long DWORD; +typedef int BOOL; +static BOOL xgpu_reversed_depth; +#define XGPU_VERTEX_ATTRIBUTE_COUNT 16 +#define XGPU_VERTEX_CONSTANT_COUNT 192 +#define XGPU_VERTEX_CONSTANT_BIAS 96 +struct xgpu_text; +void xgpu_text_append(struct xgpu_text *text, const char *format, ...); +#include "under_test.inc" +void xgpu_text_append(struct xgpu_text *text, const char *format, ...) +{ + char buffer[8192]; + va_list args; + int length; + va_start(args, format); length = vsnprintf(buffer, sizeof(buffer), format, args); va_end(args); + CHECK(length >= 0 && length < sizeof(buffer), "bounded shader append"); + text->buffer = realloc(text->buffer, text->length + length + 1); + memcpy(text->buffer + text->length, buffer, length + 1); + text->length += length; +} +int main(int argc, char **argv) +{ + unsigned int i, recognized = 0; + int enabled, per_pixel, packed, reversed; + struct xgpu_text pixel = {0}; + if (argc == 6 && strcmp(argv[1], "translated") == 0) + { + struct nv2a_vertex_lighting lighting; + char *shader; + int model; + i = atoi(argv[3]); + CHECK(i < sizeof(lengths)/sizeof(lengths[0]), "valid program"); +#ifndef HALO_GLES + xgpu_reversed_depth = atoi(argv[2]); +#endif + model = nv2a_vertex_shader_lighting(programs[i], lengths[i], &lighting); + shader = nv2a_vertex_shader_to_glsl(programs[i], lengths[i], atoi(argv[5]) ? 2 : 0, + model ? &lighting : NULL, atoi(argv[4])); + fputs(shader, stdout); + free(shader); + return 0; + } + if (argc == 3 && strcmp(argv[1], "fixed") == 0) + { + char *shader; +#ifndef HALO_GLES + xgpu_reversed_depth = atoi(argv[2]); +#endif + shader = nv2a_fixed_function_glsl(); + fputs(shader, stdout); + free(shader); + return 0; + } + for (reversed = 0; reversed < 2; reversed++) + for (enabled = 0; enabled < 2; enabled++) + for (per_pixel = 0; per_pixel < 2; per_pixel++) + for (packed = 0; packed < 2; packed++) + for (i = 0; i < sizeof(lengths)/sizeof(lengths[0]); i++) + { + struct nv2a_vertex_lighting lighting; + int model = nv2a_vertex_shader_lighting(programs[i], lengths[i], &lighting); + int point = model && lighting.lights == 2; + char *shader; +#ifndef HALO_GLES + xgpu_reversed_depth = reversed; +#endif + shader = nv2a_vertex_shader_to_glsl(programs[i], lengths[i], packed ? 2 : 0, + per_pixel && model ? &lighting : NULL, enabled); + CHECK((strstr(shader, "position.z += depth_bias * position.w") != NULL) == xgpu_reversed_depth, + "depth bias follows the desktop depth mode in program %u", i); + if (point && enabled) + { + recognized++; +#ifndef HALO_ANDROID + CHECK(strstr(shader, "if (plasma_model_slots[0] > 0.5)"), "first point light color reached in program %u", i); + CHECK(strstr(shader, "if (plasma_model_slots[1] > 0.5)"), "second point light color reached in program %u", i); + CHECK(strstr(shader, "vec3 plasma_model_position") < strstr(shader, "B.xyz *="), "position captured before color use"); +#endif + } + else CHECK(!strstr(shader, "plasma_") && !strstr(shader, "sampler3D"), "disabled and non-point programs are stock"); +#ifdef HALO_ANDROID + CHECK(!strstr(shader, "plasma_") && !strstr(shader, "sampler3D"), "Android vertex program has no optional lighting"); +#endif + free(shader); + } + CHECK(recognized >= 2, "real two-point-light programs tested"); + for (enabled = 0; enabled < 2; enabled++) + { + model_lighting(&pixel, 1, enabled); +#ifdef HALO_ANDROID + CHECK(!strstr(pixel.buffer, "plasma_") && !strstr(pixel.buffer, "sampler3D"), "Android per-pixel lighting is stock"); +#else + if (enabled) + CHECK(strstr(pixel.buffer, "plasma_model_falloff") && strstr(pixel.buffer, "plasma_model_slots[1]"), "supported per-pixel lighting retained"); + else + CHECK(!strstr(pixel.buffer, "plasma_") && !strstr(pixel.buffer, "sampler3D"), "disabled per-pixel lighting has no feature code"); +#endif + if (!strstr(pixel.buffer, "plasma_model_falloff")) + { + CHECK(strstr(pixel.buffer, "light += max(1.0 - distance_squared * model_lights[1].w, 0.0)"), "first stock point light"); + CHECK(strstr(pixel.buffer, "light += max(1.0 - distance_squared * model_lights[4].w, 0.0)"), "second stock point light"); + } + free(pixel.buffer); + memset(&pixel, 0, sizeof(pixel)); + model_lighting(&pixel, 0, enabled); + CHECK(!strstr(pixel.buffer, "plasma_") && !strstr(pixel.buffer, "xWorldPosition"), "ambient-only models unchanged"); + free(pixel.buffer); + memset(&pixel, 0, sizeof(pixel)); + } + return 0; +} diff --git a/tools/harness/tests/plasma_occlusion.c b/tools/harness/tests/plasma_occlusion.c new file mode 100644 index 0000000000..6cc55cf508 --- /dev/null +++ b/tools/harness/tests/plasma_occlusion.c @@ -0,0 +1,574 @@ +#include "harness.h" +#include +#if defined(__SSE2__) +#include +#endif +#define MAX(a, b) ((a) > (b) ? (a) : (b)) +#define PIN(a,b,c) MIN(MAX(a,b),c) +#define MIN(a, b) ((a) < (b) ? (a) : (b)) +typedef struct +{ + unsigned long pixels[4096]; +} IDirect3DVolumeTexture8; +typedef IDirect3DVolumeTexture8 D3DResource; +typedef struct +{ + void *pBits; +} D3DLOCKED_BOX; +enum +{ + D3DFMT_A8R8G8B8, + D3DPOOL_MANAGED, + _collision_test_structure_bit, + _collision_test_front_facing_surfaces_bit, + _collision_test_back_facing_surfaces_bit, + _collision_test_objects_bit, + _collision_test_objects_scenery_bit, + _collision_test_objects_machines_bit, + _collision_test_objects_vehicles_bit +}; +struct collision_result +{ + real t; +}; +struct rasterizer_light_submit_parameters +{ + real_point3d position; + real radius; +}; +static struct +{ + long light_count; + struct rasterizer_light_submit_parameters lights[32]; +} rasterizer_lights; +static int on = 1, queries, allocations, blocked = 1, door, fail_upload; +static unsigned long time_ms = 1000; +static int uploads, fail_unlock; +static real specular_scale = 1; +static int muzzle_on, emitter_on, emitter_occlusion, shield_on, shield_occlusion, vehicle_on; +static long last_ignore; +static unsigned long last_flags; +static int directional_on, vehicle_only; +static int prong_on; +struct plasma_collision_scene { int unused; }; +int plasma_lighting_prong_cone(long r,float axis[3],float origin[3],float *radius) +{ axis[0]=1;axis[1]=axis[2]=0;origin[0]=origin[1]=origin[2]=0;*radius=.3f;return prong_on?3:0; } +unsigned long plasma_collision_scene_revision(struct plasma_collision_scene *scene,const real_point3d *point,float extent,int vehicles) +{ + static int last=-1; static unsigned long revision; + int state=blocked+2*door+4*vehicle_only; + if(state!=last){last=state;revision++;} + return revision; +} +static float directional_axis[3]={-.8f,0,.6f}, directional_origin, directional_radius=1; +int muzzle_lighting_vehicle_occlusion(long light) { return muzzle_on && light==500; } +int covenant_emitter_lighting_cone(long r,float axis[3],float origin[3],float *radius) +{ + int i;if(!directional_on||r<0||r>=8)return 0; + for(i=0;i<3;i++){axis[i]=directional_axis[i];origin[i]=directional_origin;} + *radius=directional_radius;return directional_on; +} +long covenant_emitter_lighting_occlusion_ignore(long i) { return emitter_on && i == 502 ? 42 : NONE; } +int covenant_emitter_lighting_enabled(void) { return emitter_on; } +int covenant_emitter_lighting_selected(long i) { return emitter_on && i == 0; } +int muzzle_lighting_selected(long i) { return muzzle_on && i == 0; } +int shield_glow_enabled(void) { return shield_on; } +int shield_glow_selected(long i) { return shield_on && i == 0; } +void shield_glow_frame_end(void) {} +void shield_glow_window_begin(void) {} +void shield_glow_submitted(long l,long r) {} +float shield_glow_radius(long l,float r) { return r; } +int lighting_config_boolean(const char *name) +{ + if (!strcmp(name, "display.plasma_occlusion") && shield_on) return shield_occlusion; + if (!strcmp(name, "display.muzzle_lighting")) return muzzle_on; + if (!strcmp(name, "display.vehicle_lighting")) return vehicle_on; + if (!strcmp(name, "display.plasma_occlusion") && emitter_on) return emitter_occlusion; + return on; +} +static unsigned long GetTickCount(void) +{ + return time_ms; +} +float plasma_occlusion_specular_scale(long index) +{ + return specular_scale; +} +static int collision_test_vector(unsigned long flags, const real_point3d *p, const real_vector3d *v, + long ignore, struct collision_result *hit) +{ + float t, y; + queries++; + last_ignore = ignore; + last_flags = flags; + if (vehicle_only && !(flags & FLAG(_collision_test_objects_vehicles_bit))) return 0; + if (!blocked || v->i == 0) + return 0; + t = (0.3f - p->x) / v->i; + y = p->y + t * v->j; + if (t < 0 || t >= 1 || (door && fabsf(y) < 0.3f)) + return 0; + hit->t = t; + return 1; +} +static void plasma_collision_begin(unsigned long flags, const real_point3d *p, long ignore) {} +static void plasma_collision_end(void) {} +static float plasma_collision_depth(unsigned long flags, const real_point3d *p, const real_vector3d *v, long ignore) +{ + struct collision_result hit; + return collision_test_vector(flags, p, v, ignore, &hit) ? hit.t : 2.0f; +} +enum { PLASMA_COLLISION_RAYS = 1536 }; +static void plasma_collision_depths(unsigned long flags, const real_point3d *p, + const real_vector3d *vectors, int count, long ignore, float *depths) +{ int i;for(i=0;ipBits = t->pixels; + return 0; +} +static int IDirect3DVolumeTexture8_UnlockBox(IDirect3DVolumeTexture8 *t, int l) +{ + return fail_unlock ? -1 : 0; +} +static void D3DResource_Release(D3DResource *p) +{ + free(p); + allocations--; +} +static void rasterizer_xbox_bitmap_swizzle3d_long(void *d, void *s, int w, int h, int depth) +{ + memcpy(d, s, 4096 * sizeof(long)); +} +void plasma_occlusion_window(void); +int plasma_lighting_vehicle_occlusion(long i) { return vehicle_on && i == 500; } +int authored_emitter_lighting_enabled(void) { return vehicle_on; } +int covenant_emitter_lighting_vehicle_occlusion(long light) { return vehicle_on && light == 502; } +#include "under_test.inc" +/* Match the renderer's linear filtering between vertical texel centres. */ +static float filtered_height(IDirect3DVolumeTexture8 *texture, float height, float radius) +{ + float z = PIN((height / radius + 1.0f) * 8.0f - 0.5f, 0.0f, 15.0f); + int lower = (int)z, upper = MIN(lower + 1, 15); + float a = (float)(texture->pixels[(lower * 16 + 8) * 16 + 8] & 255) / 255.0f; + float b = (float)(texture->pixels[(upper * 16 + 8) * 16 + 8] & 255) / 255.0f; + return a + (b - a) * (z - lower); +} + +int main(int argc, char **argv) +{ + struct occlusion_field *f; + real previous; + int n, cap, step; + real temporal[4]; + float transform[4]; + rasterizer_lights.light_count = 1; + rasterizer_lights.lights[0].radius = 1; + plasma_occlusion_window(); + plasma_occlusion_submit(1, 0); + f = field_for(0); + CHECK(f, "admitted light"); + CHECK(sample_field(f->visibility, 0.9f, 0.5f, 0.5f) < 0.01f, "wall blocks clearly hidden receiver"); + CHECK(sample_field(f->visibility, 0.4f, 0.5f, 0.5f) > 0.99f, "near side stays lit"); + n = queries; + time_ms++; + CHECK(field_for(0) == f && queries == n, "one bounded update per window, not per model draw"); + n = queries; + time_ms += 4; + plasma_occlusion_window(); + plasma_occlusion_submit(1, 0); + f = field_for(0); + CHECK(queries == n, "collision depths are briefly reused while render projection updates"); + rasterizer_lights.lights[0].position.x = 0.2f; + plasma_occlusion_window(); + plasma_occlusion_submit(1, 0); + f = field_for(0); + CHECK(queries == n + 1536, "fast movement invalidates cached depths immediately"); + rasterizer_lights.lights[0].position.x = 0; + plasma_occlusion_window(); + plasma_occlusion_submit(1, 0); + f = field_for(0); + blocked = 0; + previous = f->visibility[4095]; + time_ms += 16; + plasma_occlusion_window(); + plasma_occlusion_submit(1, 0); + f = field_for(0); + CHECK(f->visibility[4095] > previous && f->visibility[4095] < 0.5f, + "clearing a corner fades rather than popping"); + time_ms += 200; + plasma_occlusion_window(); + plasma_occlusion_submit(1, 0); + f = field_for(0); + CHECK(f->visibility[4095] > 0.9f, "clear view converges"); + on = 0; + n = queries; + CHECK(!field_for(0) && n == queries, "disabled makes no queries"); + plasma_occlusion_reset(); + CHECK(!allocations && !submitted_count, "map cleanup releases fields"); + on = 1; + blocked = 1; + door = 1; + plasma_occlusion_window(); + plasma_occlusion_submit(2, 0); + f = field_for(0); + CHECK(sample_field(f->visibility, 0.9f, 0.5f, 0.5f) > 0.99f, "door opening admits light"); + CHECK(sample_field(f->visibility, 0.9f, 0.95f, 0.5f) < 0.35f, + "filtered doorway edge remains predominantly blocked"); + CHECK(sample_field(f->visibility, 0.9f, 0.99f, 0.5f) < 0.01f, + "receiver beyond filtered edge is fully blocked"); + door = 0; + time_ms += 16; + plasma_occlusion_window(); + plasma_occlusion_submit(2, 0); + f = field_for(0); + CHECK(sample_field(f->visibility, 0.9f, 0.5f, 0.5f) < 0.3f, + "closing door blocks within bounded refresh and fade"); + time_ms += 64; + plasma_occlusion_window(); + plasma_occlusion_submit(2, 0); + f = field_for(0); + CHECK(sample_field(f->visibility, 0.9f, 0.9f, 0.5f) < 0.01f, + "thin blocker remains closed across cube face seam"); + door = 1; + time_ms += 16; + plasma_occlusion_window(); + plasma_occlusion_submit(2, 0); + f = field_for(0); + CHECK(sample_field(f->visibility, 0.9f, 0.5f, 0.5f) > 0.3f && + sample_field(f->visibility, 0.9f, 0.5f, 0.5f) < 0.8f, + "opening door clears gradually"); + plasma_occlusion_reset(); + door = 0; + rasterizer_lights.light_count = 9; + for (n = 0; n < 9; n++) + { + rasterizer_lights.lights[n].radius = 1; + plasma_occlusion_submit(10 + n, n); + } + queries = 0; + for (n = 0; n < 8; n++) + CHECK(field_for(n), "eight fields admitted"); + CHECK(!field_for(8) && queries == 8 * 1536, "ninth light falls back without evicting active fields"); + CHECK(allocations == 0, "visibility updates allocate no unused textures"); + for (n = 0; n < 8; n++) + CHECK(plasma_occlusion_texture(n, 0), "diffuse texture requested"); + CHECK(allocations == 8 && uploads == 8, "only consumed passes allocate and upload"); + CHECK(plasma_occlusion_texture(0, 0) && uploads == 8, "repeated pass reuses upload"); + time_ms += 16; + plasma_occlusion_window(); + for (n = 0; n < 9; n++) + plasma_occlusion_submit(10 + n, n); + queries = 0; + CHECK(!field_for(8), "overflow cannot replace an active field"); + for (n = 0; n < 8; n++) + CHECK(field_for(n), "rejected overflow does not consume an admitted light's update budget"); + CHECK(queries == 0, "unchanged stationary fields reuse exact collision inputs without retracing"); + + time_ms += 120; + plasma_occlusion_window(); + plasma_occlusion_submit(18, 8); + f = field_for(8); + CHECK(f && f->fading, "previous overflow is admitted with a fade"); + CHECK(field_texture(f, 0, 0) && f->texture[0]->pixels[4095] == 0xffffffffUL, "admission starts at previous unoccluded appearance"); + time_ms += 40; + plasma_occlusion_window(); + plasma_occlusion_submit(18, 8); + f = field_for(8); + CHECK(field_texture(f, 0, 0) && f->texture[0]->pixels[4095] != 0xffffffffUL && f->texture[0]->pixels[4095] != 0, + "admission blends instead of snapping"); + plasma_occlusion_submit(10, 0); + plasma_occlusion_model_slot(0, 0); + CHECK(plasma_occlusion_model_texture(0, transform), "model uses selected field"); + CHECK(!plasma_occlusion_model_texture(-1, transform), "invalid model slot rejected"); + plasma_occlusion_window(); + CHECK(!plasma_occlusion_model_texture(0, transform), "view transition clears model slots"); + plasma_occlusion_reset(); + CHECK(!allocations, "all fields released"); + fail_upload = 1; + plasma_occlusion_submit(30, 0); + CHECK(!plasma_occlusion_texture(0, 0), "allocation failure falls back"); + fail_upload = 0; + CHECK(!plasma_occlusion_texture(0, 0), "failed pass does not retry every draw in the same view"); + time_ms += 16; + plasma_occlusion_window(); + plasma_occlusion_submit(30, 0); + CHECK(plasma_occlusion_texture(0, 0), "failed upload retries on the next view"); + plasma_occlusion_reset(); + fail_upload = 0; + time_ms = 1000; + for (cap = 0; cap < 4; cap++) + { + blocked = 1; + door = 0; + plasma_occlusion_submit(40 + cap, 0); + f = field_for(0); + blocked = 0; + for (step = 1; step <= (3 << cap); step++) + { + unsigned long next = 1000 + (unsigned long)(100.0f * step / (3 << cap)); + if (step == 1) + time_ms = 1000; + time_ms = next; + plasma_occlusion_window(); + plasma_occlusion_submit(40 + cap, 0); + f = field_for(0); + } + temporal[cap] = f->visibility[4095]; + plasma_occlusion_reset(); + time_ms = 1000; + } + CHECK(fabsf(temporal[0] - temporal[1]) < 0.025f && fabsf(temporal[1] - temporal[2]) < 0.025f && fabsf(temporal[2] - temporal[3]) < 0.025f, + "30/60/120/240 response agrees within the bounded collision refresh interval"); + blocked = 0; + plasma_occlusion_submit(99, 0); + f = field_for(0); + time_ms += 4; + rasterizer_lights.lights[0].position.x = 0.1f; + plasma_occlusion_window(); + plasma_occlusion_submit(99, 0); + f = field_for(0); + CHECK(f->visibility[4095] > 0.99f, "a clear cached ray is not a wall at the old field boundary"); + plasma_occlusion_reset(); + /* Compare every output texel with the original attenuation expression, + including different specular extents and partially admitted lights. */ + for (cap = 0; cap < 3; cap++) + { + int pass, x, y, z; + specular_scale = cap == 0 ? 0.5f : cap == 1 ? 1.0f : 2.0f; + plasma_occlusion_submit(101 + cap, 0); + f = field_for(0); + for (n = 0; n < 4096; n++) f->visibility[n] = (n % 23) / 22.0f; + f->admission = 0.37f; + for (pass = 0; pass < 3; pass++) + { + IDirect3DVolumeTexture8 *t = field_texture(f, pass, 0); + CHECK(t, "requested pass uploaded"); + if (pass == 2) + CHECK((t == f->texture[1]) == (specular_scale == 1.0f), + "only equal diffuse and specular extents share the same upload"); + for (z=0; z<16; z++) for (y=0; y<16; y++) for (x=0; x<16; x++) + { + real dx=2.0f*(x+0.5f)/16-1, dy=2.0f*(y+0.5f)/16-1, dz=2.0f*(z+0.5f)/16-1; + real scale=(pass==2 ? f->specular : 1.0f)*f->radius/f->extent; + real remaining=MAX(0.0f,1-dx*dx-dy*dy-dz*dz); + real value=pass ? sample_field(f->visibility,0.5f+dx*scale*0.5f,0.5f+dy*scale*0.5f,0.5f+dz*scale*0.5f)*remaining*remaining : f->visibility[(z*16+y)*16+x]; + int expected, actual; + value=pass ? (1-f->admission)*remaining*remaining+f->admission*value : 1-f->admission+f->admission*value; + expected=(int)(255*value+0.5f); actual=(int)(t->pixels[(z*16+y)*16+x]&255); + CHECK(abs(expected-actual)<=1,"lazy texture agrees with original within one quantization level"); + } + } + if (specular_scale == 1.0f) + { + n = uploads; + CHECK(field_texture(f, 2, 0) == field_texture(f, 1, 0) && uploads == n, + "shared specular pass does not rebuild or upload a duplicate texture"); + } + n=uploads; time_ms+=16; plasma_occlusion_window(); plasma_occlusion_submit(101+cap,0); + CHECK(plasma_occlusion_texture(0,0) && uploads==n+1,"new view invalidates each pass independently"); + plasma_occlusion_reset(); + CHECK(!allocations,"all lazy passes released"); + } + /* Exact texture reuse is independent of visibility/history updates. */ + specular_scale=1;plasma_occlusion_submit(700,0);f=field_for(0); + CHECK(field_texture(f,0,0),"initial model mask upload");n=uploads; + f->texture_mask=0; + CHECK(field_texture(f,0,0)&&uploads==n,"identical texels skip backing-memory and GPU work"); + f->visibility[0]=.37f;f->texture_mask=0; + CHECK(field_texture(f,0,0)&&uploads==n+1,"changed texel still uploads"); + f->visibility[0]=.61f;f->texture_mask=0;fail_unlock=1; + CHECK(!field_texture(f,0,0),"failed changed upload falls back"); + f->visibility[0]=.37f;f->texture_mask=0;fail_unlock=0; + CHECK(field_texture(f,0,0)&&uploads==n+3,"failure invalidates byte cache even when old pixels return"); + for(n=0;nvisibility[n]=1; + f->texture_mask=0;directional_on=1; + CHECK((field_texture(f,0,0) && (f->texture[0]->pixels[(8*16+8)*16]&255)>200), + "occluded counter mask lights its facing side"); + directional_axis[0]=.8f; + CHECK((field_texture(f,0,0) && (f->texture[0]->pixels[(8*16+8)*16]&255)==0), + "rotating a counter invalidates cached texels even with identical visibility"); + directional_axis[0]=-.8f;directional_on=0; + plasma_occlusion_reset();CHECK(!allocations,"cached upload textures disposed"); + on=0; muzzle_on=1; time_ms+=200; + plasma_occlusion_window(); plasma_occlusion_submit(500,0); + CHECK(plasma_occlusion_texture(0,0), "muzzle occlusion works with projectile lighting off"); + plasma_occlusion_reset(); + plasma_occlusion_window(); plasma_occlusion_submit(501,1); + CHECK(!plasma_occlusion_texture(1,0), "muzzle option cannot enable unrelated projectile occlusion"); + muzzle_on=0; plasma_occlusion_reset(); + emitter_on=1; emitter_occlusion=1; time_ms+=200; + plasma_occlusion_window(); plasma_occlusion_submit(502,0); + CHECK(plasma_occlusion_texture(0,0), "emitter occlusion works with projectile lighting off"); + CHECK(last_ignore==42, "luminous source is excluded from its own visibility rays"); + emitter_occlusion=0; plasma_occlusion_reset(); + plasma_occlusion_window(); plasma_occlusion_submit(503,0); + CHECK(!plasma_occlusion_texture(0,0), "emitter occlusion remains independently optional"); + /* A counter remains directional with wall occlusion disabled or full. */ + directional_on=1;plasma_occlusion_reset(); + { + float axis[3]={-.8f,0,.6f},tr[4]; + IDirect3DVolumeTexture8 *t; + CHECK(ammo_counter_falloff_factor(axis,-.8f,0,.6f)==1,"screen-facing strength preserved"); + CHECK(ammo_counter_falloff_factor(axis,0,0,-1)==0,"floor behind display is dark"); + CHECK(ammo_counter_falloff_factor(axis,.8f,0,-.6f)==0,"back hemisphere is dark"); + CHECK(ammo_counter_falloff_factor(axis,0,0,1)==1,"face above screen retains brightness"); + CHECK(needler_falloff_factor(0)==1,"needles spill equally in every horizontal direction"); + CHECK(needler_falloff_factor(-.05f)==1,"nearby hands and housing below needles retain full spill"); + CHECK(needler_falloff_factor(-.09f)>.49f&&needler_falloff_factor(-.09f)<.51f,"lower spill fades softly with distance"); + CHECK(needler_falloff_factor(-.25f)==0,"distant floor spill suppressed"); + CHECK(needler_falloff_factor(1)==1,"exposed tips retain full intensity"); + plasma_occlusion_model_slot(0,0);t=plasma_occlusion_model_texture(0,tr); + CHECK(t&&tr[3]==.5f,"model directional mask independent of collision option"); + CHECK((t->pixels[(0*16+8)*16+8]&255)==0,"model floor mask dark"); + t=plasma_occlusion_texture(0,0); + CHECK(t&&(t->pixels[(0*16+8)*16+8]&255)==0,"world floor mask dark"); + n=uploads;CHECK(plasma_occlusion_texture(0,1)==t&&uploads==n,"specular reuses angular radial mask"); + CHECK(!plasma_occlusion_texture(20,0),"unrelated lights retain stock fallback"); + plasma_occlusion_window(); + CHECK(plasma_occlusion_texture(0,0)==t&&uploads==n,"unchanged view reuses directional upload"); + directional_origin=3;directional_radius=2; + plasma_occlusion_window(); + CHECK(ammo_counter_falloff_texture(0,1,tr)==t&&uploads==n&&tr[0]==3&&tr[3]==.25f,"translation and radius update transform without rebuilding mask"); + directional_axis[0]=.8f; + plasma_occlusion_window(); + CHECK(ammo_counter_falloff_texture(0,1,tr)==t&&uploads==n+1,"rotation refreshes radial mask"); + CHECK(ammo_counter_falloff_texture(0,0,tr)&&uploads==n+2,"rotation refreshes angular mask independently"); + directional_on=2; + plasma_occlusion_window(); + CHECK(ammo_counter_falloff_texture(0,1,tr)&&uploads==n+3,"profile change refreshes mask"); + directional_axis[0]=0;directional_axis[1]=1;directional_axis[2]=0; + plasma_occlusion_window(); + CHECK(ammo_counter_falloff_texture(0,1,tr)&&uploads==n+3,"radial Needler spill does not rotate with aim"); + specular_scale=2; + t=plasma_occlusion_texture(0,1); + CHECK(t&&(t->pixels[(7*16+8)*16+8]&255)==0,"unoccluded Needler specular uses physical lower fade"); + t=plasma_occlusion_texture(0,0); + CHECK(t&&(t->pixels[(7*16+8)*16+8]&255)>0,"specular cache does not overwrite diffuse mask"); + specular_scale=1; + CHECK(plasma_occlusion_texture(0,1)==t,"equal radii share diffuse and specular mask"); + specular_scale=.5f; + t=plasma_occlusion_texture(0,1); + CHECK(t&&(t->pixels[(7*16+8)*16+8]&255)>128,"changed specular radius refreshes its mask"); + specular_scale=1; + directional_axis[0]=-.8f;directional_axis[1]=0;directional_axis[2]=.6f; + directional_on=1;directional_origin=0;directional_radius=1; + plasma_occlusion_reset();CHECK(!allocations,"directional textures released on reset"); + } + on=1;emitter_on=1;emitter_occlusion=1;blocked=0; + plasma_occlusion_submit(502,0); + { + IDirect3DVolumeTexture8 *t=plasma_occlusion_texture(0,0); + CHECK(t&&(t->pixels[(0*16+8)*16+8]&255)==0,"combined collision and direction mask stays dark behind screen"); + } + /* Model visibility spans the largest specular radius. The Needler's lower + fade must still be measured against its actual diffuse radius. */ + plasma_occlusion_reset();directional_on=2;specular_scale=2; + rasterizer_lights.lights[0].radius=1; + plasma_occlusion_submit(502,0);f=field_for(0); + { + IDirect3DVolumeTexture8 *t=field_texture(f,0,0); + CHECK(t&&(t->pixels[(7*16+8)*16+8]&255)==0,"model lower fade uses physical source radius"); + t=field_texture(f,1,0); + CHECK(t&&(t->pixels[(7*16+8)*16+8]&255)>0,"nearby diffuse receiver retains lower glow"); + t=field_texture(f,2,0); + CHECK(t&&(t->pixels[(7*16+8)*16+8]&255)==0,"specular lower fade uses physical source radius"); + } + /* Captured crouched-player and short-Grunt source heights. Check filtered + output, not just the analytic mask: specular uses twice the volume radius. */ + for (cap = 0; cap < 2; cap++) + { + IDirect3DVolumeTexture8 *t; + plasma_occlusion_reset(); + on = emitter_occlusion = cap; + directional_on = 2; + directional_radius = rasterizer_lights.lights[0].radius = 1.5f; + specular_scale = 2; + plasma_occlusion_submit(502, 0); + t = plasma_occlusion_texture(0, 0); + CHECK(t && filtered_height(t, -.38f, 1.5f) == 0, "crouched holder has no diffuse foot pool"); + CHECK(filtered_height(t, -.25f, 1.5f) < .2f, "short holder has only faint near-contact diffuse spill"); + CHECK(filtered_height(t, -.05f, 1.5f) > .9f, "diffuse spill immediately below needles stays bright"); + t = plasma_occlusion_texture(0, 1); + CHECK(t && filtered_height(t, -.25f, 3.0f) == 0, "short holder has no specular foot pool"); + CHECK(filtered_height(t, -.38f, 3.0f) == 0, "crouched holder has no specular foot pool"); + } + directional_radius = rasterizer_lights.lights[0].radius = 1; + specular_scale=1; + plasma_occlusion_reset();on=0; + directional_on=0;emitter_on=0;muzzle_on=1;vehicle_only=blocked=1; + plasma_occlusion_submit(500,0);f=field_for(0); + CHECK(f&&(last_flags&FLAG(_collision_test_objects_vehicles_bit)),"turret rays include chassis"); + CHECK(f->visibility[4095]<.1f,"vehicle blocks receiver behind hull"); + plasma_occlusion_reset();plasma_occlusion_submit(501,0);f=field_for(0); + CHECK(f&&!(last_flags&FLAG(_collision_test_objects_vehicles_bit)),"other muzzle profiles retain original blockers"); + CHECK(f->visibility[4095]>.99f,"vehicle-only blocker does not change unrelated lights"); + plasma_occlusion_reset(); + muzzle_on=0;vehicle_on=1; + for(n=0;n<2;n++) + { + plasma_occlusion_reset();time_ms+=200;plasma_occlusion_window(); + plasma_occlusion_submit(n?502:500,0);f=field_for(0); + CHECK(f&&(last_flags&FLAG(_collision_test_objects_vehicles_bit)),"headlights and engine emitters include chassis with general occlusion off"); + CHECK(f->visibility[4095]<.1f,"vehicle emitter cannot illuminate through its hull"); + plasma_occlusion_submit(501,1);CHECK(!field_for(1),"vehicle switch cannot select unrelated lights"); + } + vehicle_on=0;n=queries; + CHECK(!plasma_occlusion_texture(0,0)&&queries==n,"vehicle disable skips GPU texture and collision work"); + plasma_occlusion_reset(); + on = muzzle_on = emitter_on = directional_on = 0; shield_on = shield_occlusion = 1; + plasma_occlusion_window(); plasma_occlusion_submit(600, 0); + CHECK(field_for(0), "shield-only lighting receives occlusion"); + shield_occlusion = 0; n = queries; + plasma_occlusion_window(); plasma_occlusion_submit(600, 0); + CHECK(!field_for(0) && queries == n, "shield occlusion obeys its independent toggle"); + plasma_occlusion_reset(); + on=1;shield_on=shield_occlusion=emitter_on=directional_on=vehicle_only=0; + prong_on=1;blocked=0;rasterizer_lights.lights[0].radius=.3f;specular_scale=2; + queries=0;plasma_occlusion_submit(800,0);f=field_for(0); + CHECK(f&&queries==96,"short prongs use the smaller ray grid only"); + { + float axis[3]={1,0,0}; + IDirect3DVolumeTexture8 *t=field_texture(f,0,0); + CHECK(plasma_prong_falloff_factor(axis,1,0,0)==1,"outward prong spill remains full"); + CHECK(plasma_prong_falloff_factor(axis,-1,0,0)==0,"prongs do not illuminate their rear hemisphere"); + CHECK(plasma_prong_falloff_factor(axis,0,1,0)>0&&plasma_prong_falloff_factor(axis,0,1,0)<.3f,"side spill fades broadly and softly"); + CHECK(t&&(t->pixels[(8*16+8)*16]&255)==0&&(t->pixels[(8*16+8)*16+15]&255)>240,"actual model texture carries the outward mask"); + } + blocked=1;time_ms+=16;plasma_occlusion_window();plasma_occlusion_submit(800,0);f=field_for(0); + CHECK(f&&queries==192&&f->visibility[4095]<.3f,"small prong grid still blocks a nearby wall"); + plasma_occlusion_reset();CHECK(!allocations,"prong reset releases GPU resources"); + /* A permanently blocked cell must settle to black, not retain subnormal + fade history forever at high frame rates. Reopening still fades normally. */ + prong_on=directional_on=emitter_on=muzzle_on=vehicle_on=shield_on=0; + on=blocked=1;specular_scale=1;rasterizer_lights.lights[0].radius=1; + for(cap=0;cap<4;cap++) + { + int rates[4]={30,60,120,240}; + plasma_occlusion_reset(); + blocked=0;time_ms+=100;plasma_occlusion_window();plasma_occlusion_submit(900,0);f=field_for(0); + blocked=1; + for(n=0;nvisibility[4095]==0,"blocked history settles without denormal residue"); + blocked=0;time_ms+=16;plasma_occlusion_window();plasma_occlusion_submit(900,0);f=field_for(0); + CHECK(f->visibility[4095]>0&&f->visibility[4095]<.5f,"settled cells reopen with the normal fade"); + blocked=1; + } + plasma_occlusion_reset(); + return 0; +} diff --git a/tools/harness/tests/plasma_occlusion_gl.c b/tools/harness/tests/plasma_occlusion_gl.c new file mode 100644 index 0000000000..3742ba97b2 --- /dev/null +++ b/tools/harness/tests/plasma_occlusion_gl.c @@ -0,0 +1,101 @@ +#include "harness.h" +typedef unsigned int GLuint; +typedef int GLint; +typedef unsigned int GLenum; +typedef unsigned long DWORD; +enum { GL_ACTIVE_TEXTURE, GL_TEXTURE0 = 100, GL_TEXTURE_3D = 200, + GL_TEXTURE_MIN_FILTER, GL_TEXTURE_MAG_FILTER, GL_TEXTURE_WRAP_S, + GL_TEXTURE_WRAP_T, GL_TEXTURE_WRAP_R, GL_LINEAR, GL_CLAMP_TO_EDGE, + GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE }; +struct xgpu_texture_description { int unused; }; +static int active = GL_TEXTURE0 + 3, lookups, sampler_parameters, samplers, selected = 3; +static int sampler_uniforms, enabled_location, transform_location[2]; +static float enabled_value[2]; +static int fail_sampler = 1, fallback_parameters; +static DWORD resources[2]; +static unsigned long view_serial=1; +static int fetches, uniform_writes; +static int state_queries, texture_binds; +static GLuint bound_textures[2]; +static float gpu_enabled[3][2], gpu_transform[3][2][4]; +static unsigned long plasma_occlusion_view_serial(void) {return view_serial;} +static GLint glGetUniformLocation(GLuint program, const char *name) +{ + lookups++; + if (!strcmp(name,"plasma_occ_enabled")) return program * 10; + if (!strcmp(name,"plasma_occ_transform0")) return program * 10 + 1; + if (!strcmp(name,"plasma_occ_transform1")) return program * 10 + 2; + return program * 10 + 3; +} +static void glUniform1i(GLint location, int value) +{ CHECK(value==6 || value==7,"feature samplers use only reserved units"); sampler_uniforms++; } +static void glGetIntegerv(GLenum name, GLint *value) { state_queries++; *value=active; } +static void glActiveTexture(GLenum value) { active=value; } +static void glGenSamplers(int count, GLuint *value) { samplers++; *value=fail_sampler ? 0 : 99; } +static void glSamplerParameteri(GLuint sampler, GLenum name, GLint value) +{ + CHECK(sampler==99,"only owned sampler is configured"); + CHECK(value==((name==GL_TEXTURE_MIN_FILTER || name==GL_TEXTURE_MAG_FILTER) ? GL_LINEAR : GL_CLAMP_TO_EDGE), + "sampling preserves linear filtering and clamped edges"); + sampler_parameters++; +} +static void glBindSampler(GLuint unit, GLuint sampler) +{ CHECK((unit==6 || unit==7) && sampler==(fail_sampler ? 0 : 99),"stock sampler units are untouched"); } +static void glTexParameteri(GLenum target, GLenum name, GLint value) +{ + CHECK(fail_sampler && (active==GL_TEXTURE0+6 || active==GL_TEXTURE0+7),"fallback configures only feature textures"); + CHECK(value==((name==GL_TEXTURE_MIN_FILTER || name==GL_TEXTURE_MAG_FILTER) ? GL_LINEAR : GL_CLAMP_TO_EDGE), + "allocation fallback preserves sampling"); + fallback_parameters++; +} +static void glBindTexture(GLenum target, GLuint texture) +{ CHECK(active==GL_TEXTURE0+6 || active==GL_TEXTURE0+7,"only reserved texture units are changed"); bound_textures[active-GL_TEXTURE0-6]=texture;texture_binds++; } +static void glBindTextures(GLuint first,int count,const GLuint *textures) +{ CHECK(first==6 && count==2,"multi-bind touches only feature units");memcpy(bound_textures,textures,sizeof(bound_textures));texture_binds++; } +static void glGenTextures(int count, GLuint *texture) { *texture=88; } +static void glTexImage3D(GLenum a,int b,int c,int d,int e,int f,int g,GLenum h,GLenum i,const void *p) {} +static void glUniform4fv(GLint location, int count, const float *values) +{ transform_location[location%10-1]=location;memcpy(gpu_transform[location/10][location%10-1],values,4*sizeof(float));uniform_writes++; } +static void glUniform2f(GLint location,float a,float b) +{ enabled_location=location; enabled_value[0]=a; enabled_value[1]=b;gpu_enabled[location/10][0]=a;gpu_enabled[location/10][1]=b;uniform_writes++; } +static void *plasma_occlusion_model_texture(int slot,float transform[4]) +{ int i; for(i=0;i<4;i++) transform[i]=(float)i; return selected&(1< +#if defined(__SSE2__) +#include +#endif +#define MIN(a,b) ((a)<(b)?(a):(b)) +#define MAX(a,b) ((a)>(b)?(a):(b)) +#define PIN(a,b,c) MIN(MAX(a,b),c) +enum { OCC_SIZE=16 }; +#include "under_test.inc" +int main(int argc,char **argv) +{ + unsigned int state=23; + real a[16],b[16],axis[3]; + unsigned long actual[16],reference[16]; + int row,i,profile,radial; + for(row=0;row<4096;row++) + { + real dy=(2.0f*((row%16)+.5f)/16)-1,dz=(2.0f*((row/16%16)+.5f)/16)-1; + real blend=(row%5)*.25f,admission=(row%17)/16.0f,scale=(row%3+1)*.5f; + for(i=0;i<16;i++) + { + state=state*1664525U+1013904223U;a[i]=(state&65535)/65535.0f; + state=state*1664525U+1013904223U;b[i]=(state&65535)/65535.0f; + } + for(i=0;i<3;i++) { state=state*1664525U+1013904223U;axis[i]=(state&65535)/32767.5f-1; } + for(profile=0;profile<4;profile++)for(radial=0;radial<2;radial++) + { + texture_row(actual,a,b,blend,admission,radial,profile,axis,dy,dz,scale); + reference_texture_row(reference,a,b,blend,admission,radial,profile,axis,dy,dz,scale); + CHECK(!memcmp(actual,reference,sizeof(actual)),"packed texture conversion preserves every scalar byte"); + } + } + return 0; +} diff --git a/tools/harness/tests/plasma_visibility.c b/tools/harness/tests/plasma_visibility.c new file mode 100644 index 0000000000..12eecfa0ec --- /dev/null +++ b/tools/harness/tests/plasma_visibility.c @@ -0,0 +1,36 @@ + +#include "harness.h" +#include +#if defined(__SSE2__) +#include +#endif + +#define MAX(a,b) ((a)>(b)?(a):(b)) +#define MIN(a,b) ((a)<(b)?(a):(b)) +#include "under_test.inc" +int main(int argc,char **argv) +{ + real depths[6][256],xs[16],values[16]; + int trial,face,cell,y,z,x,resolution,mismatches=0; + for(trial=0;trial<512;trial++) + { + real extent=trial%4==0?.0011f:trial%4==1?.6f:trial%4==2?3.87f:999.f; + real dx=(trial%7-3)*extent*.03125f,dy=(trial%11-5)*extent*.015625f,dz=(trial%5-2)*extent*.03125f; + resolution=trial&1?4:16; + for(face=0;face<6;face++)for(cell=0;cell<256;cell++)depths[face][cell]=(cell+trial)%4?((cell*17+face*13+trial*7)%257)/256.f:2.f; + for(x=0;x<16;x++)xs[x]=(2.f*(x+.5f)/16-1)*extent+dx; + for(z=0;z<16;z++)for(y=0;y<16;y++) + { + real py=(2.f*(y+.5f)/16-1)*extent+dy,pz=(2.f*(z+.5f)/16-1)*extent+dz; + depth_visibility_row(depths,xs,py,pz,extent,resolution,values); + for(x=0;x<16;x++) + { + real_vector3d ray={xs[x],py,pz};real expected=depth_visibility(depths,&ray,extent,resolution); + if(memcmp(&values[x], &expected, sizeof(real))){mismatches++;if(mismatches<10)printf("mismatch %d %d %d %d %.9g %.9g\n",trial,x,y,z,values[x],expected);} + } + } + } + CHECK(!mismatches,"packed visibility equals scalar across every cell"); + + return 0; +} diff --git a/tools/harness/tests/polygon_clip.c b/tools/harness/tests/polygon_clip.c index f320543597..a7201fa4a7 100644 --- a/tools/harness/tests/polygon_clip.c +++ b/tools/harness/tests/polygon_clip.c @@ -132,6 +132,58 @@ int main(int argc, char **argv) CHECK(result[index].x >= 1.0f && result[index].x <= 2.0f, "corner %d at x %g", index, result[index].x); return 0; } + /* A later portal consumes the preceding intersection, not the original + outline. Keep a nonempty finite region through repeated intersections. */ + CASE("successive-portals") + { + real_point2d region[64], outline[64], results[2][CLIP_BUFFER_SIZE]; + short count, step, index; + + points_from(region_a, 10, region); + points_from(outline_a, 11, outline); + count = convex_hull2d_intersect(10, region, 11, outline, 256, results[0], 0.0001f); + for (step = 0; step < 8; step++) + { + real_point2d *current = results[step & 1]; + + CHECK(count >= 3 && count <= 256, "portal %d has %d corners", step, count); + for (index = 0; index < count; index++) + CHECK(isfinite(current[index].x) && isfinite(current[index].y), + "portal %d corner %d is not finite", step, index); + if (step < 7) + count = convex_hull2d_intersect(11, outline, count, current, 256, + results[(step + 1) & 1], 0.0001f); + } + return 0; + } + /* The NaN correction must not turn clipping into a conservative draw-all + fallback. Exercise rejection, unchanged polygons and the in-place API. */ + CASE("clip-contract") + { + real_point2d square[4] = { {{0, 0}}, {{2, 0}}, {{2, 2}}, {{0, 2}} }; + real_point2d result[CLIP_BUFFER_SIZE]; + real_plane2d plane = { {{1, 0}}, -1 }; + boolean clipped; + unsigned long flags = 5; + short count; + + count = convex_polygon2d_clip_to_plane(4, square, &plane, 16, result, &flags, &clipped, 0.0001f); + CHECK(count == 4 && !memcmp(square, result, sizeof(square)), "inside polygon unchanged"); + CHECK(!clipped && flags == 5, "inside polygon preserves clip metadata"); + plane.d = 3; + count = convex_polygon2d_clip_to_plane(4, square, &plane, 16, result, NULL, NULL, 0.0001f); + CHECK(count == 0, "outside polygon rejected"); + plane.d = 2; + count = convex_polygon2d_clip_to_plane(4, square, &plane, 16, result, NULL, NULL, 0.0001f); + CHECK(count == 0, "edge-only intersection rejected"); + plane.d = 1; + count = convex_polygon2d_clip_to_plane(4, square, &plane, 16, square, &flags, &clipped, 0.0001f); + CHECK(count == 4 && clipped && flags == 13, "in-place clip metadata"); + CHECK(square[0].x == 1 && square[0].y == 0 && square[1].x == 2 && square[1].y == 0 && + square[2].x == 2 && square[2].y == 2 && square[3].x == 1 && square[3].y == 2, + "in-place clip retains the correct half"); + return 0; + } fprintf(stderr, "unknown case '%s'\n", case_name); return 2; } diff --git a/tools/harness/tests/render_effect_lifecycle.c b/tools/harness/tests/render_effect_lifecycle.c new file mode 100644 index 0000000000..b635cd0807 --- /dev/null +++ b/tools/harness/tests/render_effect_lifecycle.c @@ -0,0 +1,134 @@ +/* Real camera caching and cloth scheduling; graphics, rumble and cloth physics + are stubbed. The post-load callback table is extracted from the engine. */ +#include +#include "harness.h" +typedef unsigned short word; +typedef struct { real red, green, blue; } real_rgb_color; +typedef struct { real alpha, red, green, blue; } real_argb_color; +typedef struct { real yaw, pitch, roll; } real_euler_angles3d; +typedef struct { real scale; real_vector3d forward, left, up; real_point3d position; } real_matrix4x3; +#define TICKS_PER_SECOND 30 +#define MAXIMUM_LOCAL_PLAYERS 4 +#define MAXIMUM_NUMBER_OF_LOCAL_PLAYERS 4 +#define NUMBER_OF_DAMAGE_INDICATORS 4 +#define NUMBEROF(a) (sizeof(a)/sizeof((a)[0])) +#define csmemset memset +#define match_vassert(file,line,condition,...) CHECK(condition,"assertion") +#define SET_FLAG(v,b,on) ((on) ? ((v) |= FLAG(b)) : ((v) &= ~FLAG(b))) +#define MAX(a,b) ((a)>(b) ? (a):(b)) +#define PIN(v,a,b) ((v)<(a)?(a):((v)>(b)?(b):(v))) +#include "config.inc" +static struct player_effect_globals_definition globals; +static struct player_effect_globals_definition *player_effect_globals=&globals; +static real_matrix4x3 identity={1,{1,0,0},{0,1,0},{0,0,1},{0,0,0}}; +static real_matrix4x3 const *global_identity4x3=&identity; +static real_vector3d up={0,0,1}; +static real_vector3d const *global_up3d=&up; +static long tick=10; +static unsigned long seed=123; +static long game_time_get(void) { return tick; } +static short game_time_get_elapsed(void) { return 1; } +static unsigned long *get_global_local_random_seed_address(void) { return &seed; } +static real real_seed_random_range(unsigned long *s,real lo,real hi) { ++*s; return hi; } +static void rumble_player_set_scale(real scale) { } +static void rumble_player_continuous(short player,real a,real b) { } +static real effect_scale_value(short f,real zero,real elapsed,real duration) { return zero*(1-elapsed/duration); } +static real periodic_function_evaluate(short f,real t) { return 1; } +#define sine sinf +#define cosine cosf +static void cross_product3d(real_vector3d const *a,real_vector3d const *b,real_vector3d *out) { *out=*a; } +static void matrix4x3_rotation_from_axis_and_angle(real_matrix4x3 *out,real_vector3d const *axis,real s,real c) { *out=identity; } +static void matrix4x3_rotation_from_angles(real_matrix4x3 *out,real yaw,real pitch,real roll) { *out=identity; } +static void get_shake_matrix(real translation,real rotation,real_matrix4x3 *out) { out->position.x=translation; } +static void matrix4x3_multiply(real_matrix4x3 const *a,real_matrix4x3 const *b,real_matrix4x3 *out) { real_matrix4x3 copy=*a; copy.position.x+=b->position.x; *out=copy; } +struct flag_datum_prefix { long definition_index,object_index; short updates_since_last_render; }; +struct flag_definition { int unused; }; +static struct flag_datum_prefix cloth={0,1,0}; +static struct flag_definition cloth_definition; +static int steps; +static real stepped_time; +static long data_next_index(struct data_array *data,long previous) { return previous==NONE?0:NONE; } +static struct flag_datum_prefix *flag_get(long index) { return &cloth; } +static struct flag_definition *flag_definition_get(long index) { return &cloth_definition; } +static void flag_update(struct flag_datum_prefix *flag,struct flag_definition *definition,real dt) { ++steps; stepped_time=dt; } +#define data_make_valid(d) ((void)0) +#define data_make_invalid(d) ((void)0) +#include "under_test.inc" +static void impulse(short player,real value) +{ + struct player_effect_datum *effect=player_effect_get(player); + memset(effect,0,sizeof(*effect)); + effect->direction.i=1; + effect->camera_impulse.temporary_translation=value; + effect->camera_impulse.temporary_duration=10; + effect->camera_impulse.temporary_zero_scale_factor=1; + effect->camera_impulse_time_left=10; + effect->flags=FLAG(_player_effect_camera_impulse_just_started_bit); +} +static real draw(short player) +{ + real_matrix4x3 matrix=identity; + player_effect_get_camera_effect_matrix(player,&matrix); + CHECK(seed==123,"camera restores random seed"); + return matrix.position.x; +} +static void cloth_frame(real dt) { cloth.updates_since_last_render=0; flags_update(dt); } +int main(int argc,char **argv) +{ + const char *case_name=argc>1?argv[1]:""; + int i; + player_effect_initialize_for_new_map(); + flags_initialize_for_new_map(); + CASE("camera-checkpoint") + { + impulse(0,1); CHECK(draw(0)==1,"initial impulse"); + impulse(0,3); game_state_call_after_load_procs(); + CHECK(draw(0)==3,"same-tick checkpoint uses restored camera state"); + CHECK(draw(0)==3,"later frames retain the restored impulse"); + ++tick; CHECK(draw(0)<3,"next tick updates impulse"); + return 0; + } + CASE("camera-maps") + { + impulse(0,1); draw(0); + player_effect_dispose_from_old_map(); impulse(0,2); + CHECK(draw(0)==2,"unload invalidates cached camera"); + player_effect_initialize_for_new_map(); impulse(0,4); + CHECK(draw(0)==4,"new map at same tick has its own camera"); + return 0; + } + CASE("camera-windows") + { + for(i=0;i<4;++i) { impulse(i,(real)i+1); CHECK(draw(i)==i+1,"window impulse"); } + for(i=0;i<4;++i) CHECK(draw(i)==i+1,"window caches are independent"); + return 0; + } + CASE("cloth-checkpoint") + { + cloth_frame(0.01f); cloth_frame(0.02f); + CHECK(steps==1,"one cloth step in a tick"); + game_state_call_after_load_procs(); cloth_frame(0.005f); + CHECK(steps==2 && fabsf(stepped_time-0.005f)<1e-6f,"same-tick restore discards old pending time"); + return 0; + } + CASE("cloth-maps") + { + cloth_frame(0.01f); cloth_frame(0.02f); + flags_dispose_from_old_map(); cloth_frame(0.005f); + CHECK(steps==2 && fabsf(stepped_time-0.005f)<1e-6f,"unload resets cloth clock"); + cloth_frame(0.02f); flags_initialize_for_new_map(); cloth_frame(0.007f); + CHECK(steps==3 && fabsf(stepped_time-0.007f)<1e-6f,"new map resets cloth clock"); + return 0; + } + CASE("cloth-frames") + { + cloth_frame(0); for(i=0;i<7;++i) cloth_frame(1.0f/240); + CHECK(steps==0,"no physics on frames between ticks"); + ++tick; cloth_frame(1.0f/240); + CHECK(steps==1 && fabsf(stepped_time-1.0f/30)<1e-6f,"accumulate all eight render frames"); + tick+=2; cloth_frame(2.0f/30); + CHECK(steps==2 && fabsf(stepped_time-2.0f/30)<1e-6f,"low-frame-rate elapsed time is retained"); + return 0; + } + return 2; +} diff --git a/tools/harness/tests/reported_hit_sight.c b/tools/harness/tests/reported_hit_sight.c new file mode 100644 index 0000000000..bd36aaa2fe --- /dev/null +++ b/tools/harness/tests/reported_hit_sight.c @@ -0,0 +1,131 @@ +#include "harness.h" +#include +#define MIN(a,b) ((a)<(b)?(a):(b)) +#include "config.inc" + +enum { _collision_test_structure_bit, _collision_test_front_facing_surfaces_bit, + _collision_test_ignore_invisible_surfaces_bit, _collision_test_ignore_breakable_surfaces_bit, + _collision_test_ignore_two_sided_surfaces_bit }; +struct collision_result { int unused; }; +static struct damage_trail_point damage_trails[1][PLAYER_TRAIL_POINTS]; +static struct { struct damage_stuck_projectile stuck[MAXIMUM_STUCK_PROJECTILES]; } damage_players[1]; +static long now = 300; +static int mode, calls; +static boolean blocked_eye_muzzle; +static real muzzle_x = 2.0f; +static boolean accept_hands = TRUE; +static unsigned long settings_revision; +static long damage_hand_reports; +static long game_time_get(void) { return now; } +static real distributed_machine_round_trip_ticks(long machine) { CHECK(machine == 0, "machine"); return 0; } +static unsigned long config_changes(void) { return settings_revision; } +static int config_boolean(char const *name) +{ + CHECK(!strcmp(name, "network.fire_origins"), "unexpected setting"); + return accept_hands; +} +/* Object discovery is a separate boundary; this fixture supplies host-owned notes. */ +static void distributed_note_stuck_projectiles(void) {} + +static boolean collision_test_line(unsigned long flags, real_point3d const *from, + real_point3d const *to, long ignored, struct collision_result *result) +{ + CHECK(flags & FLAG(_collision_test_structure_bit), "structure must be checked"); + CHECK(ignored == NONE, "no object owns the structure trace"); + calls++; + if (mode == 0) return FALSE; + if (mode == 1) return TRUE; + /* A centre ray is blocked; both legs through the impact must be clear. */ + if (mode == 2) return from->x == 0 && to->x == 10; + if (mode == 3) return to->x == 10; + /* A muzzle or hand is useful only with a clear eye-to-origin segment. */ + if (from->x == muzzle_x) return FALSE; + if (to->x == muzzle_x) return blocked_eye_muzzle; + return TRUE; +} +#include "under_test.inc" + +static struct damage_trail_point *point(long time) +{ + struct damage_trail_point *p = &damage_trails[0][(time / PLAYER_TRAIL_INTERVAL_TICKS) & (PLAYER_TRAIL_POINTS - 1)]; + memset(p, 0, sizeof(*p)); p->time = time; p->eye = 1; + return p; +} +static boolean sight(void) +{ + real_point3d impact = { 9, 0, 1 }, centre = { 10, 0, 1 }; + struct damage_reach reach; + memset(&reach, 0, sizeof(reach)); + return distributed_report_line_of_sight(0, 0, &impact, ¢re, 1, &reach, now); +} +int main(int argc, char **argv) +{ + int i; + struct damage_trail_point *p; + struct damage_stuck_projectile *stuck; + CHECK(argc == 2, "case required"); + for (i = 0; i < PLAYER_TRAIL_POINTS; i++) damage_trails[0][i].time = NONE; + for (i = 0; i < MAXIMUM_STUCK_PROJECTILES; i++) damage_players[0].stuck[i].time = NONE; + p = point(now); + if (!strcmp(argv[1], "clear")) { + CHECK(sight(), "open line rejected"); + } else if (!strcmp(argv[1], "blocked")) { + mode = 1; CHECK(!sight(), "solid wall accepted"); + } else if (!strcmp(argv[1], "impact")) { + mode = 2; CHECK(sight(), "clear two-leg route rejected"); + mode = 3; CHECK(!sight(), "impact-to-centre wall accepted"); + } else if (!strcmp(argv[1], "mounted")) { + mode = 4; p->mounted = TRUE; p->muzzle.x = 2; + CHECK(sight(), "mounted weapon rejected"); + CHECK(!damage_hand_reports, "host-owned muzzle counted as a client hand"); + blocked_eye_muzzle = TRUE; + CHECK(!sight(), "muzzle beyond cover accepted"); + blocked_eye_muzzle = FALSE; accept_hands = FALSE; settings_revision++; + CHECK(sight(), "hand setting disabled the host-owned muzzle"); + } else if (!strcmp(argv[1], "hand") || !strcmp(argv[1], "hand_shape") || !strcmp(argv[1], "eye_priority")) { + mode = 4; muzzle_x = 0.15f; + p->mounted = TRUE; p->hand = TRUE; p->muzzle.x = muzzle_x; p->muzzle.z = 0.9f; + if (!strcmp(argv[1], "hand")) { + CHECK(sight() && damage_hand_reports == 1, "valid hand fallback rejected or not counted"); + blocked_eye_muzzle = TRUE; + CHECK(!sight() && damage_hand_reports == 1, "hand beyond cover accepted"); + blocked_eye_muzzle = FALSE; accept_hands = FALSE; settings_revision++; + CHECK(!sight() && damage_hand_reports == 1, "disabled hand fallback accepted"); + accept_hands = TRUE; settings_revision++; + CHECK(sight() && damage_hand_reports == 2, "changed hand setting not reread"); + } else if (!strcmp(argv[1], "hand_shape")) { + p->muzzle.y = 0.25f; + CHECK(!sight() && !damage_hand_reports, "hand too far around a corner accepted"); + p->muzzle.y = 0.1f; + CHECK(sight() && damage_hand_reports == 1, "valid hand shape rejected"); + } else { + point(now - PLAYER_TRAIL_INTERVAL_TICKS)->position.x = muzzle_x; + CHECK(sight() && !damage_hand_reports, "hand took priority over a recent host-owned eye"); + } + } else if (!strcmp(argv[1], "missing")) { + p->time = NONE; CHECK(!sight() && !calls, "absent living history accepted"); + } else if (!strcmp(argv[1], "window")) { + p->time = NONE; point(0); + CHECK(!sight() && !calls, "expired history accepted"); + point(now - PLAYER_TRAIL_INTERVAL_TICKS); + CHECK(sight(), "recent history rejected"); + } else if (!strcmp(argv[1], "budget")) { + mode = 1; + for (i = 0; i < PLAYER_TRAIL_POINTS && now - i * PLAYER_TRAIL_INTERVAL_TICKS >= 0; i++) + point(now - i * PLAYER_TRAIL_INTERVAL_TICKS); + CHECK(!sight(), "blocked history accepted"); + CHECK(calls == 2 * REPORT_LINE_OF_SIGHT_POINTS, "trace budget exceeded or truncated: %d", calls); + } else if (!strcmp(argv[1], "attached")) { + stuck = &damage_players[0].stuck[0]; + stuck->time = now; stuck->object_index = 7; stuck->damage_index = 9; + CHECK(!distributed_stuck_detonation(0, 8, 9), "wrong target accepted"); + CHECK(!distributed_stuck_detonation(0, 7, 8), "wrong damage accepted"); + CHECK(distributed_stuck_detonation(0, 7, 9), "host attachment rejected"); + CHECK(!distributed_stuck_detonation(0, 7, 9), "attachment spent twice"); + stuck->spent = FALSE; stuck->time = now - STUCK_PROJECTILE_TICKS - 1; + CHECK(!distributed_stuck_detonation(0, 7, 9), "expired attachment accepted"); + stuck->time++; + CHECK(distributed_stuck_detonation(0, 7, 9), "boundary attachment rejected"); + } else CHECK(FALSE, "unknown case"); + return 0; +} diff --git a/tools/harness/tests/riding_camera.c b/tools/harness/tests/riding_camera.c index 9b10a6b536..62e6442c18 100644 --- a/tools/harness/tests/riding_camera.c +++ b/tools/harness/tests/riding_camera.c @@ -28,6 +28,7 @@ static long turn_calls; #define director_get_perspective(index) _director_perspective_first_person #define director_inhibited_facing(index) FALSE #define cinematic_in_progress() FALSE +#define third_person_director_active(index) FALSE #define player_control_get_unit_index(index) 7 #define object_get(index) (&unit) #define player_control_get_facing_direction(index, output) (*(output) = facing) diff --git a/tools/harness/tests/rocket_lighting.c b/tools/harness/tests/rocket_lighting.c new file mode 100644 index 0000000000..fa0c796b78 --- /dev/null +++ b/tools/harness/tests/rocket_lighting.c @@ -0,0 +1,86 @@ +#include "harness.h" +#include +#define MAX(a,b) ((a) > (b) ? (a) : (b)) +typedef struct { real red, green, blue; } real_rgb_color; +typedef struct { real elements[13]; } real_matrix4x3; +enum { _object_type_projectile = 5, _object_mask_projectile = 1, _object_invisible_bit = 0, + MAXIMUM_NUMBER_OF_ATTACHMENTS_PER_OBJECT = 8 }; +struct object_datum { long definition_index; struct { short type; long flags; struct { int size; } node_matrices; real_point3d bounding_sphere_center; } object; }; +struct object_attachment_definition { struct { long group_tag, index; } type; }; +struct block { int count; }; +struct object_definition { struct { struct block attachments; } object; }; +static struct object_attachment_definition authored_attachment = {{'ligh',99}}; +#define TAG_BLOCK_GET_ELEMENT(b,i,t) (&authored_attachment) +static struct object_definition definition; +struct observer_result { real_point3d position; }; +static struct observer_result camera; +static real_vector3d zero, forward = {1,0,0}; +static const real_vector3d *global_zero_vector3d = &zero, *global_forward3d = &forward; +static struct object_datum objects[10]; +static int count = 10, enabled = 1, allocs, deletes, disconnects, submits, fail, missing; +static const char *name = "weapons\\rocket launcher\\rocket"; +static struct { int active, connected; long owner; real red; } storage[64]; +struct object_iterator { long index; }; +static void object_iterator_new(struct object_iterator *i, int mask, int flags) { i->index = -1; } +static void *object_iterator_next(struct object_iterator *i) { return ++i->index < count ? &objects[i->index] : NULL; } +static struct object_datum *object_try_and_get(long i) { return i >= 0 && i < count ? &objects[i] : NULL; } +static const char *tag_get_name(long i) { return name; } +static struct object_definition *object_definition_get(long i) { return &definition; } +static short local_player_get_next(short i) { return i == NONE ? 0 : NONE; } +static const struct observer_result *observer_get_camera(short i) { return &camera; } +static real distance3d(const real_point3d *a, const real_point3d *b) { return a->x - b->x; } +int lighting_config_boolean(const char *n) { return enabled; } +long light_port_glow_definition_get(void) { return missing ? NONE : 99; } +static long light_new_unattached(long d,long o,short n,const real_point3d *p,const real_vector3d *v,real s) +{ + if (fail) return NONE; + storage[allocs].active=storage[allocs].connected=1; storage[allocs].owner=o; + return 100+allocs++; +} +boolean light_port_glow_set(long l,long o,const real_rgb_color *c,real r) +{ + int i=(int)l-100; + if (i<0 || i>=allocs || !storage[i].active || storage[i].owner!=o) return FALSE; + storage[i].red=c->red; return TRUE; +} +static void light_delete(long l) { storage[l-100].active=0; deletes++; } +static void light_disconnect_from_map(long l) { CHECK(storage[l-100].connected,"disconnect requires connected light"); storage[l-100].connected=0; disconnects++; } +static void light_reconnect_to_map(long l) { CHECK(!storage[l-100].connected,"connect requires disconnected light"); storage[l-100].connected=1; } +void plasma_occlusion_submit(long l,long r) { submits++; } +#include "under_test.inc" +int main(void) +{ + int i, before; + long held; + for(i=0;i<10;i++) { objects[i].object.node_matrices.size=sizeof(real_matrix4x3); objects[i].object.type=5; objects[i].object.bounding_sphere_center.x=1; } + rocket_lighting_update(); CHECK(allocs==8,"bounded eight owned lights"); + CHECK(rocket_lighting_radius(100,0,0.25f)==1.75f,"owned radius covers template"); + CHECK(rocket_lighting_radius(100,1,0.25f)==0.25f,"wrong owner keeps bounds"); + rocket_lighting_window_begin(); + for(i=0;i<8;i++) { rocket_lighting_submitted(100+i,i); CHECK(rocket_lighting_selected(i),"submitted rocket selected"); } + CHECK(submits==8 && !rocket_lighting_selected(NONE),"only valid submissions"); + rocket_lighting_frame_end(); CHECK(disconnects==8,"owned lights disconnected before simulation"); + for(i=0;i<8;i++) CHECK(storage[i].red==0 && !rocket_lighting_selected(i),"dark and unselected between frames"); + rocket_lighting_frame_end(); CHECK(disconnects==8,"repeated frame cleanup is safe"); + rocket_lighting_update(); CHECK(storage[0].connected,"reconnect before engine scene pass"); + rocket_lighting_update(); CHECK(allocs==8,"stable identities across views/frames"); + enabled=0; rocket_lighting_update(); CHECK(deletes==8,"disable releases owned lights"); + rocket_lighting_update(); CHECK(allocs==8,"disabled never allocates"); + enabled=1; count=1; rocket_lighting_update(); CHECK(allocs==9,"re-enable allocates"); + count=0; rocket_lighting_update(); CHECK(deletes==9,"expired rocket cleaned up"); + count=1; rocket_lighting_update(); held=rocket_lights[0].light_index; + storage[held-100].owner=42; before=deletes; + rocket_lighting_update(); CHECK(deletes==before && allocs==11,"stale owner never deleted or reused"); + rocket_lighting_submitted(rocket_lights[0].light_index,2); + rocket_lighting_forget(); CHECK(!rocket_lighting_selected(2),"map/recovery forgets all handles"); + before=allocs; missing=1; rocket_lighting_update(); CHECK(allocs==before,"missing template fallback"); + missing=0; fail=1; rocket_lighting_update(); CHECK(allocs==before,"allocation failure fallback"); + fail=0; definition.object.attachments.count=1; rocket_lighting_update(); CHECK(allocs==before,"authored light prevents duplicate"); + definition.object.attachments.count=0; name="weapons\\rocket launcher\\explosion"; + rocket_lighting_update(); CHECK(allocs==before,"explosion cannot acquire flight light"); + name="weapons\\rocket launcher\\rocket"; objects[0].object.bounding_sphere_center.x=30; + rocket_lighting_update(); CHECK(allocs==before,"distant rockets leave capacity free"); + objects[0].object.bounding_sphere_center.x=1; rocket_lighting_update(); + before=deletes; enabled=0; rocket_lighting_frame_end(); CHECK(deletes==before+1,"disable at frame end releases latest owned light"); + return 0; +} diff --git a/tools/harness/tests/script_stale_objects.c b/tools/harness/tests/script_stale_objects.c index 91ac052256..562b4d44c9 100644 --- a/tools/harness/tests/script_stale_objects.c +++ b/tools/harness/tests/script_stale_objects.c @@ -178,7 +178,7 @@ boolean hs_trigger_volume_test_objects_any(short trigger_volume_index, long obje boolean hs_trigger_volume_test_objects_all(short trigger_volume_index, long object_list_index); /* This fixture exercises Xbox/CE scripting. MCC-owned extension hooks keep - their inactive behavior in this world. */ + their inactive behavior; MCC runtime coverage lives in test_mcc_*.py. */ static byte *mcc_hs_stack_end(struct hs_thread_datum *thread) { return thread->stack_data + HS_THREAD_STACK_SIZE; diff --git a/tools/harness/tests/server_teardown.c b/tools/harness/tests/server_teardown.c index c66a4a154d..0bd359cca7 100644 --- a/tools/harness/tests/server_teardown.c +++ b/tools/harness/tests/server_teardown.c @@ -35,10 +35,17 @@ static int slept, messages, broadcasts, handled, closed, terminated, errors; static int new_servers, clients_closed, joins_cleared, variants_cleared; static short expected_message; static boolean message_fails, send_fails, machines_fail; +static int network_bots = TRUE, network_bots_enabled = TRUE; +static byte owned[BOTS_MAXIMUM] = { 1 }; +static long bots_reuse_after[BOTS_MAXIMUM] = { 100 }; -/* These legacy teardown cases have no pending MCC restart. */ +/* These legacy teardown cases have no pending MCC restart. Its independent + snapshot lifetime is exercised by test_mcc_ui_network.py. */ +static void third_person_session_host_end(void) { } /* Session contract: test_camera_protocol.py. */ static void mcc_ui_network_server_dispose(struct network_game_server *server) { (void)server; } +/* These legacy teardown cases have no pending MCC restart. */ + static void note(char event) { size_t length = strlen(order); @@ -112,6 +119,8 @@ int main(int argc, char **argv) struct network_game_server host = { _network_game_server_state_pregame, FLAG(_network_game_server_game_open_bit) | FLAG(_network_game_server_game_valid_bit), &connection, 123, TRUE }; boolean deleted = FALSE; + owned[BOTS_MAXIMUM - 1] = 1; + bots_reuse_after[BOTS_MAXIMUM - 1] = 200; disposing = &host; bss_004566dc.server = &host; bss_004566dc.client = &client; bss_004566dc.quickstart_local = bss_004566dc.client_started = TRUE; @@ -135,6 +144,8 @@ int main(int argc, char **argv) if (back) CHECK(clear_multiplayer_player_joins(NULL, NULL, &deleted), "back callback failed"); else if (reopen) CHECK(ui_widget_port_host(NULL, NULL, &deleted), "reopen callback failed"); else network_game_server_dispose(&host); + CHECK(!network_bots && !network_bots_enabled && !owned[0] && !owned[BOTS_MAXIMUM - 1], "bot reservation/ownership survived host disposal"); + CHECK(!bots_reuse_after[0] && !bots_reuse_after[BOTS_MAXIMUM - 1], "bot cooldown survived host disposal"); CHECK(slept == EXPECTED_SLEEP && closed == 1 && handled == 1 && terminated == 1, "wrong sleep or incomplete teardown: %s", order); CHECK(errors == (machines_fail ? 1 : 0), "error handling changed"); int expected_messages = strcmp(case_name, "ingame") ? 1 : 0; diff --git a/tools/harness/tests/settings_focus.c b/tools/harness/tests/settings_focus.c new file mode 100644 index 0000000000..61ac721f28 --- /dev/null +++ b/tools/harness/tests/settings_focus.c @@ -0,0 +1,36 @@ +#include "harness.h" +#include +struct widget_instance { + struct widget_instance *child, *next, *focused_child; + short type; + long definition_tag_index; + char *name; + struct { + struct { struct widget_instance *extended_description; } list; + struct { short string_list_index; } text_box; + } parameters; +}; +static int setting; +static void *pc_menu_setting_get(long tag) { return tag == 7 ? &setting : NULL; } +static short pc_menu_string_index(long tag) { return tag == 6 ? 0 : NONE; } +#include "under_test.inc" +int main(int argc, char **argv) +{ + struct widget_instance list={0}, row={0}, label={0}, spinner={0}, help={0}; + row.name="op_plasma_lighting"; row.child=&label; + label.type=1; label.definition_tag_index=6; label.next=&spinner; + spinner.type=2; spinner.definition_tag_index=7; + list.focused_child=&row; list.parameters.list.extended_description=&help; + settings_help(&list); + CHECK(row.focused_child==&spinner,"returning to a row restores its setting input route"); + CHECK(help.parameters.text_box.string_list_index==1,"first setting retains help"); + row.focused_child=&label; settings_help(&list); + CHECK(row.focused_child==&label,"existing focus is not replaced"); + row.focused_child=NULL; spinner.definition_tag_index=8; settings_help(&list); + CHECK(!row.focused_child,"unrelated list does not gain setting focus"); + row.name="button_bar"; label.type=0; settings_help(&list); + CHECK(!row.focused_child && help.parameters.text_box.string_list_index==0,"button bar remains owned by normal navigation"); + list.focused_child=NULL; settings_help(&list); + CHECK(help.parameters.text_box.string_list_index==0,"no row is safe"); + return 0; +} diff --git a/tools/harness/tests/shield_effects.c b/tools/harness/tests/shield_effects.c index 51609d1286..7f0e164ab4 100644 --- a/tools/harness/tests/shield_effects.c +++ b/tools/harness/tests/shield_effects.c @@ -7,7 +7,7 @@ checked whole. */ typedef unsigned short word; typedef word message_header; #define GET_MESSAGE_TYPE(message) (((message) >> 2) & 3) -struct distributed_message_header { message_header header; byte type; byte count; long game_time; }; +#include "message_header.inc" static char const *setting = "stock"; static unsigned long changes = 1; static short connection = _game_connection_local; diff --git a/tools/harness/tests/shield_look.c b/tools/harness/tests/shield_look.c new file mode 100644 index 0000000000..776267b649 --- /dev/null +++ b/tools/harness/tests/shield_look.c @@ -0,0 +1,460 @@ +/* The whole feature module, with only engine services and cache I/O stubbed. */ +#include +#include +#include +#include +#include + +#define TRUE 1 +#define FALSE 0 +#define NONE (-1) +#define MAXIMUM_LOCAL_PLAYERS 4 +#define MAXIMUM_SHADERS_PER_MODEL 32 +#define NUMBER_OF_OUTGOING_OBJECT_FUNCTIONS 4 +#define TAG_STRING_LENGTH 31 +#define _object_type_biped 0 +#define _object_type_weapon 2 +#define _shader_type_transparent_plasma_glow 10 +#define CHECK(x) do { if (!(x)) { fprintf(stderr, "line %d: %s\n", __LINE__, #x); return 1; } } while (0) +typedef unsigned char boolean; +typedef unsigned char byte; +typedef unsigned short word; +typedef float real; +typedef struct { real red, green, blue; } real_rgb_color; +typedef struct { real i, j, k; } real_vector3d; +struct tag_reference { unsigned long group_tag; char *name; long name_length, index; }; +struct tag_block { long count; void *address; void *definition; }; +void shield_recharge_reset(void) {} /* separate draw-envelope dependency */ +#include "real_types.inc" +struct object_definition { struct { + struct tag_reference model, modifier_shader; + short function_modes[4]; struct tag_block functions; +} object; }; +struct object_datum { long definition_index; struct { short type; long parent_object_index; } object; }; +struct unit_datum { long definition_index; struct { short type; long parent_object_index; real outgoing_function_values[4]; real_rgb_color outgoing_change_colors[4]; } object; struct { long player_index; } unit; }; +struct model { struct tag_block shaders; }; +struct bitmap_data { short width, height, depth, type, format, mipmap_count; word flags; long pixels_size, pixels_offset; }; +struct bitmap_group { struct tag_block bitmaps; }; +struct game_globals_first_person_interface { struct tag_reference hands; }; +struct game_globals { struct tag_block first_person_interface; }; +struct render_model_effect { struct shader *modifier_shader; struct { + real_rgb_color const *colors; real const *values; +} modifier_animation; }; +#define TAG_BLOCK_GET_ELEMENT(block, i, type) ((type *)(block)->address + (i)) + +static const char *setting = "enhanced"; +static void *tags[16]; +static unsigned long groups[16]; +static struct unit_datum object; +static struct object_datum weapon; +static struct unit_datum unit; +static struct game_globals globals; +static int noise_matches = 1; +static int no_noise; +struct tag_iterator { long index; }; +static void tag_iterator_new(struct tag_iterator *it, unsigned long group) { (void)group; it->index = 0; } +static long tag_iterator_next(struct tag_iterator *it) { return no_noise ? NONE : it->index++ == 0 ? 3 : it->index == 2 ? 9 : NONE; } +static int overshield; +static unsigned char *reference_pixels; +static long reference_size; +static int read_failed; +static const char *config_string(const char *name) { (void)name; return setting; } +static boolean cache_file_tag_cache_contains(void const *p, long size) { return p && size > 0; } +static unsigned long tag_get_group_tag(long i) { return i >= 0 && i < 16 ? groups[i] : 0; } +static void *bitmap_group_get(long i) { return tags[i]; } +static void *object_definition_get(long i) { return tags[i]; } +static boolean shader_type_is_valid_for_modifier(short type) { return type == 1 || (type > 4 && type <= 10); } +static void *shader_definition_get(long i) { return tags[i]; } +static void *model_definition_get(long i) { return tags[i]; } +static struct object_datum *object_get(long i) { (void)i; return (struct object_datum *)&object; } +static struct object_datum *object_try_and_get(long i) { return i == NONE ? NULL : i == 1 ? &weapon : (struct object_datum *)&object; } +static struct unit_datum *unit_get(long i) { (void)i; return &unit; } +static struct game_globals *scenario_get_game_globals(void) { return &globals; } +static int SwitchToThread(void) { return 0; } +static void cache_file_read(long tag, long offset, long size, void *out, boolean *complete, boolean blocking) +{ + (void)tag; (void)offset; (void)blocking; + if (reference_pixels && reference_size >= size && !read_failed) { + memcpy(out, reference_pixels, size); *complete = TRUE; + } else *complete = 2; +} +static boolean overshield_effect_arms_values(long i, real const *source, real *out) +{ + (void)i; + if (!overshield) return FALSE; + memcpy(out, source, 4 * sizeof(real)); out[1] = 0.75f; return TRUE; +} +#include "under_test.inc" + +static struct shield_look_plasma stock; +static struct object_definition definition; +static struct object_function_definition functions[2]; +static struct shield_look_model_shader material; +static struct model model; +static struct model hands_model; +static struct shield_look_model_shader hands_material; +static struct { struct shader shader; word flags; } opaque; +static struct game_globals_first_person_interface first_person; +static struct bitmap_group bitmap_group; +static struct bitmap_data bitmap; + +static void setup(void) +{ + stock.shader.base.type = 10; + stock.intensity_source = stock.offset_source = 2; + stock.intensity_exponent = 1.f; stock.offset_exponent = 2.f; stock.offset_amount = 0.03f; + stock.perpendicular_alpha = stock.parallel_alpha = 1.f; + stock.perpendicular_color.red = 1.f; stock.perpendicular_color.green = 0.545098f; + stock.perpendicular_color.blue = 0.243137f; + stock.parallel_color.red = stock.parallel_color.green = 0.0666667f; stock.parallel_color.blue = 1.f; + stock.primary_period = 2.2f; stock.secondary_period = 3.f; + stock.primary_direction.i = 2.f; stock.primary_direction.k = -0.3f; + stock.secondary_direction.j = 2.f; stock.secondary_direction.k = 0.5f; + stock.primary_scale = 10.f; stock.secondary_scale = 6.f; + stock.reserved82[0x3B] = 6; stock.reservedE4[0x21] = 6; + stock.primary_map.index = stock.secondary_map.index = 3; + stock.primary_map.group_tag = stock.secondary_map.group_tag = 'bitm'; + functions[1].period = 1.f; functions[1].scale_function_by_function_index = 1; + functions[1].map_result_to_transition_function = 2; + functions[1].upper_bound = 1.f; functions[1].turn_off_with_function_index = NONE; + functions[1].runtime_reciprocal_bounds_range = functions[1].runtime_one_over_period = 1.f; + definition.object.function_modes[0] = 4; definition.object.function_modes[1] = 2; + definition.object.functions.count = 2; definition.object.functions.address = functions; + definition.object.modifier_shader.index = 2; definition.object.model.index = 4; + model.shaders.count = 1; model.shaders.address = &material; material.shader.index = 5; + hands_model.shaders.count = 1; hands_model.shaders.address = &hands_material; hands_material.shader.index = 8; + first_person.hands.index = 7; + globals.first_person_interface.count = 1; globals.first_person_interface.address = &first_person; + tags[1] = &definition; tags[2] = &stock; tags[3] = &bitmap_group; tags[4] = &model; + tags[5] = tags[8] = &opaque; tags[7] = &hands_model; + groups[2] = 'spla'; groups[3] = 'bitm'; groups[5] = groups[8] = 'soso'; + object.definition_index = 1; + unit.object.outgoing_function_values[1] = 0.5f; + bitmap_group.bitmaps.count = 1; bitmap_group.bitmaps.address = &bitmap; + bitmap.width = bitmap.height = bitmap.depth = 32; bitmap.type = 1; bitmap.format = 3; + bitmap.mipmap_count = 5; bitmap.pixels_size = 75008; bitmap.flags = 0x89; +} + +/* Simulate the caller's Arm Shields pass; profile code must preserve its + shader-animation state, including the pointer used by the renderer cap. */ +static int arm_setting = 1; +static real arm_values[4][4]; +static boolean draw_arms(short local, long unit_index, long hands, struct render_model_effect *effect) +{ + memset(effect, 0, sizeof(*effect)); + if (arm_setting && local >= 0 && local < 4) { + if (!overshield_effect_arms_values(unit_index, unit.object.outgoing_function_values, arm_values[local])) + memcpy(arm_values[local], unit.object.outgoing_function_values, sizeof(arm_values[local])); + effect->modifier_shader = &stock.shader; + effect->modifier_animation.values = arm_values[local]; + effect->modifier_animation.colors = unit.object.outgoing_change_colors; + } + return shield_look_arms(local, unit_index, hands, effect); +} + +static void export_shader(struct shield_look_plasma const *p) +{ + unsigned char const *b = (unsigned char const *)p; + int spans[][2] = {{0x2C,0x40},{0x60,0x82},{0xC0,0xD4},{0x108,0x11C}}; + int s, i; + for (s = 0; s < 4; s++) for (i = spans[s][0]; i < spans[s][1]; i++) printf("%02x", b[i]); +} + +int main(int argc, char **argv) +{ + struct render_model_effect effect = {0}, second = {0}; + struct shader *body; + int i; + FILE *file; + CHECK(argc >= 2); + setup(); + if (argc == 3) setting = argv[2]; + if (!strcmp(argv[1], "reference")) { + CHECK(argc == 4 || argc == 5); file = fopen(argv[2], "rb"); CHECK(file); + CHECK(fread(&stock, 1, sizeof(stock), file) == sizeof(stock)); fclose(file); + file = fopen(argv[3], "rb"); CHECK(file); fseek(file, 0, SEEK_END); reference_size = ftell(file); + rewind(file); reference_pixels = malloc(reference_size); CHECK(reference_pixels); + CHECK(fread(reference_pixels, 1, reference_size, file) == (size_t)reference_size); fclose(file); + if (argc == 5) { + bitmap.format = 11; bitmap.pixels_size = reference_size; + bitmap.flags = !strcmp(argv[4], "ce") ? 0x181 : 0x189; + } + CHECK(shield_look_read_noise(3)); reference_pixels[0] ^= 1; CHECK(!shield_look_read_noise(3)); + reference_pixels[0] ^= 1; read_failed = 1; CHECK(!shield_look_read_noise(3)); free(reference_pixels); + return 0; + } + if (!strcmp(argv[1], "player-only")) { + struct shader *player_shader; + object.unit.player_index = NONE; + CHECK(shield_look_body(0, &stock.shader) == &stock.shader); + CHECK(shield_look_count == 0); + object.unit.player_index = 0; + player_shader = shield_look_body(0, &stock.shader); + CHECK(player_shader != &stock.shader); + CHECK(shield_look_skip_shell(0, &model, &stock.shader, FALSE)); + weapon.object.type = _object_type_weapon; weapon.object.parent_object_index = 0; + CHECK(shield_look_skip_shell(1, &hands_model, &stock.shader, TRUE)); + CHECK(!shield_look_skip_shell(1, &hands_model, &stock.shader, FALSE)); + object.unit.player_index = NONE; + CHECK(!shield_look_skip_shell(0, &model, &stock.shader, FALSE)); + CHECK(!shield_look_skip_shell(0, &hands_model, &stock.shader, FALSE)); + CHECK(!shield_look_skip_shell(1, &hands_model, &stock.shader, TRUE)); + CHECK(shield_look_body(0, &stock.shader) == &stock.shader); + CHECK(!draw_arms(0, 0, 7, &effect)); + CHECK(effect.modifier_shader == &stock.shader); + object.unit.player_index = 17; /* Remote player: not a local slot. */ + CHECK(shield_look_body(0, &stock.shader) == player_shader); + CHECK(draw_arms(0, 0, 7, &effect)); + arm_setting = 0; CHECK(!draw_arms(0, 0, 7, &effect)); + CHECK(shield_look_skip_shell(1, &hands_model, &stock.shader, TRUE)); + weapon.object.parent_object_index = NONE; + CHECK(!shield_look_skip_shell(1, &hands_model, &stock.shader, TRUE)); + return 0; + } + if (!strcmp(argv[1], "removed")) { + setting = "honeycomb"; + CHECK(!shield_look_enabled()); + CHECK(shield_look_body(0, &stock.shader) == &stock.shader); + setting = "classic_honeycomb"; + CHECK(!shield_look_enabled()); + CHECK(shield_look_body(0, &stock.shader) == &stock.shader); + return 0; + } + if (!strcmp(argv[1], "classic-honeycomb")) { + struct shield_look_plasma saved_body, saved_arms; + struct shader *sprinkles, *mixed, *hands; + real_rgb_color a, b; + setting = "classic_with_sprinkles"; + sprinkles = shield_look_body(0, &stock.shader); + saved_body = *(struct shield_look_plasma *)sprinkles; + CHECK(draw_arms(0, 0, 7, &effect)); + saved_arms = *(struct shield_look_plasma *)effect.modifier_shader; + setting = "classic_honeycomb2"; + mixed = shield_look_body(0, &stock.shader); + CHECK(mixed != sprinkles && !memcmp(mixed, &saved_body, sizeof(saved_body))); + CHECK(shield_look_honeycomb_scale(mixed) == 87.5f); + CHECK(shield_look_honeycomb_classic_mode(mixed) == 3); + CHECK(!shield_look_honeycomb_classic_mode(sprinkles)); + CHECK(draw_arms(0, 0, 7, &effect)); hands = effect.modifier_shader; + CHECK(!memcmp(hands, &saved_arms, sizeof(saved_arms))); + CHECK(shield_look_honeycomb_scale(hands) == 225.f && shield_look_honeycomb_classic_mode(hands) == 1); + CHECK(effect.modifier_animation.values == arm_values[0]); + stock.perpendicular_color.red = 0.f; stock.perpendicular_color.green = 1.f; stock.perpendicular_color.blue = 0.f; + a = saved_body.perpendicular_color; b = saved_body.parallel_color; + CHECK(shield_look_colors(mixed, NULL, &a, &b)); + CHECK(a.red == 0.f && a.green == 1.f && a.blue == 0.f); + arm_setting = 0; CHECK(!draw_arms(0, 0, 7, &effect)); CHECK(!effect.modifier_shader); + setting = "honeycomb"; CHECK(!shield_look_honeycomb_classic_mode(shield_look_body(0, &stock.shader))); + CHECK(shield_look_honeycomb_classic_mode(mixed) == 3); /* queued draw retains identity */ + setting = "classic_with_sprinkles"; + CHECK(shield_look_body(0, &stock.shader) == sprinkles && !memcmp(sprinkles, &saved_body, sizeof(saved_body))); + setting = "classic"; CHECK(shield_look_body(0, &stock.shader) == &stock.shader); + shield_look_reset(); CHECK(!shield_look_honeycomb_classic_mode(mixed)); + CHECK(!shield_look_honeycomb_scale(hands)); + return 0; + } + if (!strcmp(argv[1], "sprinkles")) { + struct shield_look_plasma enhanced, saved, *p; + struct shader *previous; + real_rgb_color a, b; + previous = shield_look_body(0, &stock.shader); + enhanced = *(struct shield_look_plasma *)previous; + setting = "classic_with_sprinkles"; + body = shield_look_body(0, &stock.shader); p = (struct shield_look_plasma *)body; + CHECK(body != previous && body != &stock.shader); + CHECK(p->primary_scale == 10.f && p->secondary_scale == 6.f); + CHECK(p->primary_period == 2.2f && p->secondary_period == 3.f); + CHECK(p->perpendicular_color.red == 1.f && p->parallel_color.blue == 1.f); + CHECK(p->offset_amount == enhanced.offset_amount && p->offset_exponent == enhanced.offset_exponent); + CHECK(draw_arms(0, 0, 7, &effect)); + CHECK(((struct shield_look_plasma *)effect.modifier_shader)->primary_scale == 10.f); + CHECK(((struct shield_look_plasma *)effect.modifier_shader)->offset_amount == 0.03f); + CHECK(effect.modifier_animation.values == arm_values[0]); + saved = *p; + stock.perpendicular_color.red = 0.f; stock.perpendicular_color.green = 0.f; stock.perpendicular_color.blue = 1.f; + a = p->perpendicular_color; b = p->parallel_color; + CHECK(shield_look_colors(body, NULL, &a, &b)); + CHECK(a.red == 0.f && a.green == 0.f && a.blue == 1.f); + CHECK(!memcmp(p, &saved, sizeof(saved))); + arm_setting = 0; CHECK(!draw_arms(0, 0, 7, &effect)); CHECK(!effect.modifier_shader); + setting = "enhanced"; CHECK(shield_look_body(0, &stock.shader) == previous); + CHECK(!memcmp(previous, &enhanced, sizeof(enhanced))); + setting = "classic"; CHECK(shield_look_body(0, &stock.shader) == &stock.shader); + setting = "classic_with_sprinkles"; CHECK(shield_look_body(0, &stock.shader) == body); + shield_look_reset(); CHECK(shield_look_body(0, &stock.shader) != &stock.shader); + return 0; + } + if (!strcmp(argv[1], "colors")) { + struct shield_look_plasma saved; + real_rgb_color a, b, original_a, original_b; + real peak_a, peak_b; + body = shield_look_body(0, &stock.shader); + saved = *(struct shield_look_plasma *)body; + original_a = saved.perpendicular_color; original_b = saved.parallel_color; + peak_a = (!strcmp(setting, "classic_honeycomb2")) ? 1.f : original_a.red; + peak_b = (!strcmp(setting, "classic_honeycomb2")) ? 1.f : original_b.red; + a = original_a; b = original_b; + CHECK(!shield_look_colors(body, NULL, &a, &b)); + CHECK(!memcmp(&a, &original_a, sizeof(a))); + stock.perpendicular_color.red = 0.243137f; stock.perpendicular_color.blue = 1.f; + CHECK(shield_look_colors(body, NULL, &a, &b)); + CHECK(a.blue == peak_a && b.blue == peak_b); + CHECK(a.red < a.green && a.green < a.blue); + CHECK(!memcmp(body, &saved, sizeof(saved))); + CHECK(!shield_look_colors(&stock.shader, NULL, &a, &b)); + stock.color_source = 3; + stock.perpendicular_color.red = stock.perpendicular_color.green = stock.perpendicular_color.blue = 1.f; + memset(&stock.parallel_color, 0, sizeof(stock.parallel_color)); + unit.object.outgoing_change_colors[2].blue = 0.4f; + a = original_a; b = original_b; + CHECK(shield_look_colors(body, unit.object.outgoing_change_colors, &a, &b)); + CHECK(a.red == 0.f && a.green == 0.f && a.blue == peak_a); + CHECK(b.blue == peak_b); + CHECK(draw_arms(0, 0, 7, &effect)); + unit.object.outgoing_change_colors[2].blue = 0.f; + unit.object.outgoing_change_colors[2].green = 1.f; + a = original_a; b = original_b; + CHECK(shield_look_colors(effect.modifier_shader, unit.object.outgoing_change_colors, &a, &b)); + CHECK(a.green == peak_a && a.blue == 0.f); + CHECK(!shield_look_colors(body, NULL, &a, &b)); + stock.color_source = 5; + CHECK(!shield_look_colors(body, unit.object.outgoing_change_colors, &a, &b)); + stock.color_source = 0; + memset(&stock.perpendicular_color, 0, sizeof(stock.perpendicular_color)); + CHECK(!shield_look_colors(body, NULL, &a, &b)); + stock.perpendicular_color.blue = 1.e-39f; + a = original_a; b = original_b; + CHECK(shield_look_colors(body, NULL, &a, &b)); + CHECK(a.blue == peak_a && a.red == 0.f); + stock.perpendicular_color.blue = 1.f; + stock.shader.base.type = 6; + CHECK(!shield_look_colors(body, NULL, &a, &b)); + stock.shader.base.type = 10; + CHECK(shield_look_colors(body, NULL, &a, &b)); + CHECK(!memcmp(body, &saved, sizeof(saved))); + setting = "classic"; + CHECK(!shield_look_colors(body, NULL, &a, &b)); + setting = "enhanced"; shield_look_reset(); + CHECK(!shield_look_colors(body, NULL, &a, &b)); + return 0; + } + if (!strcmp(argv[1], "classic")) setting = "classic"; + else if (!strcmp(argv[1], "invalid-setting")) setting = "not-a-profile"; + else if (!strcmp(argv[1], "authored-shader")) { stock.primary_scale = 80.f; stock.offset_amount = 0.f; } + else if (!strcmp(argv[1], "authored-noise")) noise_matches = 0; + else if (!strcmp(argv[1], "authored-environment")) stock.shader.base.type = 1; + else if (!strcmp(argv[1], "authored-nonplasma")) stock.shader.base.type = 6; + else if (!strcmp(argv[1], "authored-channel")) stock.intensity_source = 3; + else if (!strcmp(argv[1], "authored-function")) functions[1].period = 2.f; + else if (!strcmp(argv[1], "authored-hands")) groups[8] = 'spla'; + else if (!strcmp(argv[1], "authored-body")) groups[5] = 'spla'; + else if (!strcmp(argv[1], "authored-decal")) opaque.flags = 1 << 3; + else if (!strcmp(argv[1], "no-noise")) no_noise = 1; + else if (!strcmp(argv[1], "missing")) definition.object.modifier_shader.index = NONE; + if (!strcmp(argv[1], "classic") || !strcmp(argv[1], "invalid-setting") || + !strcmp(argv[1], "missing") || !strcmp(argv[1], "no-noise")) { + CHECK(shield_look_body(0, &stock.shader) == &stock.shader); + CHECK(!draw_arms(0, 0, 7, &effect)); CHECK(effect.modifier_shader == &stock.shader); + CHECK(!shield_look_skip_shell(0, &hands_model, &stock.shader, FALSE)); return 0; + } + if (!strcmp(argv[1], "malformed-noise")) { + CHECK(!shield_look_read_noise(NONE)); CHECK(!shield_look_read_noise(3)); + bitmap.width = 33; CHECK(!shield_look_read_noise(3)); bitmap.width = 32; + bitmap_group.bitmaps.count = 2; CHECK(!shield_look_read_noise(3)); return 0; + } + body = shield_look_body(0, &stock.shader); CHECK(body != &stock.shader); + CHECK(draw_arms(0, 0, 7, &effect)); CHECK(effect.modifier_shader != body); + CHECK(stock.secondary_scale == 6.f); /* source tag was not mutated */ + if (!strncmp(argv[1], "authored-", 9)) { + CHECK(((struct shield_look_plasma *)body)->primary_scale == 18.f); + CHECK(((struct shield_look_plasma *)body)->intensity_source == stock.intensity_source); + CHECK(overshield_effect_intensity_source(0) == stock.intensity_source - 1); + CHECK(((struct shield_look_plasma *)body)->offset_source == stock.intensity_source); + CHECK(((struct shield_look_plasma *)body)->primary_map.index == (noise_matches ? 3 : 9)); + CHECK(((struct shield_look_plasma *)effect.modifier_shader)->primary_scale == 45.f); + CHECK(((struct shield_look_plasma *)effect.modifier_shader)->offset_amount == 0.03f); + CHECK(shield_look_skip_shell(0, &hands_model, &stock.shader, FALSE) == (stock.shader.base.type > 4)); + CHECK(shield_look_skip_shell(0, &model, &stock.shader, FALSE) == (stock.shader.base.type > 4)); + CHECK(!shield_look_skip_shell(0, &model, &opaque.shader, FALSE)); + setting = "classic"; + CHECK(overshield_effect_intensity_source(0) == + (stock.shader.base.type == 10 ? stock.intensity_source - 1 : NONE)); + CHECK(!shield_look_skip_shell(0, &hands_model, &stock.shader, FALSE)); + CHECK(shield_look_body(0, &stock.shader) == &stock.shader); + CHECK(!draw_arms(0, 0, 7, &effect)); + return 0; + } + CHECK(effect.modifier_animation.values[1] == 0.5f); + if (!strcmp(argv[1], "export")) { + export_shader((struct shield_look_plasma *)body); + export_shader((struct shield_look_plasma *)effect.modifier_shader); return 0; + } + if (!strcmp(argv[1], "arms-off")) { + arm_setting = 0; + CHECK(!draw_arms(0, 0, 7, &effect)); CHECK(!effect.modifier_shader); + CHECK(shield_look_skip_shell(0, &hands_model, &stock.shader, FALSE)); + CHECK(shield_look_body(0, &stock.shader) == body); + arm_setting = 1; CHECK(draw_arms(0, 0, 7, &effect)); + CHECK(effect.modifier_animation.values == arm_values[0]); + CHECK(effect.modifier_animation.colors == unit.object.outgoing_change_colors); + } else if (!strcmp(argv[1], "profiles")) { + CHECK(((struct shield_look_plasma *)effect.modifier_shader)->offset_source == stock.offset_source); + CHECK(((struct shield_look_plasma *)effect.modifier_shader)->offset_amount == stock.offset_amount); + CHECK(((struct shield_look_plasma *)effect.modifier_shader)->offset_exponent == stock.offset_exponent); + CHECK(effect.modifier_animation.values == arm_values[0]); + CHECK(((struct shield_look_plasma *)body)->primary_scale == 18.f); + CHECK(((struct shield_look_plasma *)effect.modifier_shader)->primary_scale == 45.f); + CHECK(((struct shield_look_plasma *)effect.modifier_shader)->secondary_scale == 62.f); + CHECK(((struct shield_look_plasma *)body)->primary_map.index == 3); + overshield = 1; CHECK(draw_arms(0, 0, 7, &effect)); CHECK(effect.modifier_animation.values[1] == 0.75f); + CHECK(unit.object.outgoing_function_values[1] == 0.5f); + } else if (!strcmp(argv[1], "outer")) { + struct shield_look_plasma original_body, outer_body, original_arms; + struct shader *original_pointer, *outer_pointer; + setting = "enhanced"; + original_pointer = shield_look_body(0, &stock.shader); + original_body = *(struct shield_look_plasma *)original_pointer; + CHECK(draw_arms(0, 0, 7, &effect)); + original_arms = *(struct shield_look_plasma *)effect.modifier_shader; + setting = "enhanced2"; + outer_pointer = shield_look_body(0, &stock.shader); + CHECK(outer_pointer == original_pointer); + outer_body = *(struct shield_look_plasma *)outer_pointer; + CHECK(outer_body.offset_source == 2 && outer_body.offset_amount == 0.0125f); + CHECK(outer_body.offset_exponent == 0.5f); + outer_body.offset_source = original_body.offset_source; + outer_body.offset_amount = original_body.offset_amount; + outer_body.offset_exponent = original_body.offset_exponent; + CHECK(!memcmp(&outer_body, &original_body, sizeof(outer_body))); + CHECK(draw_arms(0, 0, 7, &second)); + CHECK(!memcmp(&original_arms, second.modifier_shader, sizeof(original_arms))); + CHECK(!memcmp(&original_body, original_pointer, sizeof(original_body))); + setting = "classic"; CHECK(shield_look_body(0, &stock.shader) == &stock.shader); + CHECK(!draw_arms(0, 0, 7, &second)); + setting = "enhanced2"; CHECK(shield_look_body(0, &stock.shader) == outer_pointer); + setting = "enhanced"; CHECK(shield_look_body(0, &stock.shader) == original_pointer); + } else if (!strcmp(argv[1], "split")) { + unit.object.outgoing_function_values[1] = 0.9f; + CHECK(draw_arms(1, 0, 7, &second)); CHECK(second.modifier_animation.values != effect.modifier_animation.values); + CHECK(effect.modifier_animation.values[1] == 0.5f && second.modifier_animation.values[1] == 0.9f); + CHECK(!draw_arms(-1, 0, 7, &second)); CHECK(!draw_arms(4, 0, 7, &second)); + } else if (!strcmp(argv[1], "toggle")) { + setting = "classic"; CHECK(shield_look_body(0, &stock.shader) == &stock.shader); + CHECK(!draw_arms(0, 0, 7, &second)); + setting = argc == 3 ? argv[2] : "enhanced"; CHECK(shield_look_body(0, &stock.shader) == body); + } else if (!strcmp(argv[1], "reload")) { + shield_look_reset(); definition.object.modifier_shader.index = NONE; + CHECK(shield_look_body(0, &stock.shader) == &stock.shader); + shield_look_reset(); definition.object.modifier_shader.index = 2; + CHECK(shield_look_body(0, &stock.shader) != &stock.shader); + } else if (!strcmp(argv[1], "capacity")) { + for (i = shield_look_count; i < SHIELD_LOOK_MAXIMUM; i++) { + shield_looks[i].definition_index = NONE; + } + shield_look_count = SHIELD_LOOK_MAXIMUM; object.definition_index = 6; tags[6] = &definition; + CHECK(shield_look_body(0, &stock.shader) == &stock.shader); + CHECK(((struct shield_look_plasma *)body)->primary_scale == + ((!strcmp(setting, "classic_honeycomb2")) ? 10.f : 18.f)); + } else { fprintf(stderr, "unknown case: %s\n", argv[1]); return 1; } + return 0; +} diff --git a/tools/harness/tests/stock_bots_functions.json b/tools/harness/tests/stock_bots_functions.json new file mode 100644 index 0000000000..f2a6728c48 --- /dev/null +++ b/tools/harness/tests/stock_bots_functions.json @@ -0,0 +1,80 @@ +{ + "bots_add_roam_point": "c80d99ba6aa2f0bb094ee5a572f55b886f196ecc5d02a58a273865dae8be2417", + "bots_angle_difference": "c1542be3c2d6824301a9dd732573aaf5ddff404a8fea18c558b4c6db4fe8a509", + "bots_bot_fight": "4b88176bcf246ab678975bd7d113c532b27fd7e1d023efa0af3e8d959b91d03f", + "bots_bot_look": "58b7ab6bda739a032b5b138b8b70403456cde3529adc613a65dd9c955f139e31", + "bots_bot_reset": "3c4400fb6f72ff43d9c31810e1a519299162ba0a153eb92e0ac5dc644106e1e8", + "bots_bot_trace": "38647d45d241b472109611d6b1e0dbce8ff58bf40f1910374f880ba3d3771ed7", + "bots_bot_unstick": "d45d3d4d484811ac689809a579ff2b7b311c0f1cf37440b1691c0c2d7cf99c86", + "bots_bot_update": "8edbefe10e21bf3135c742e551ac85fd4293ca2942e53a9f172f74a581842c45", + "bots_bot_walk": "c057468656903cbd279845ae5c26ad52f8e8c3565919b79674349143ab61e6c0", + "bots_bot_weapons": "e3492c083d31ca01a2ad8951216c2dd4bddf21db5ac1031c3f0b6be863788147", + "bots_bot_yield": "717892cfd08af78dcbe3e8ef8c3d4cd27edca766601b62fe35c6ece1e78e0e4b", + "bots_build_path_unavoided": "55d3c3a1c7478b41961f10af79245c7994073d32a00c4184b568e5a52f9fd2a8", + "bots_choose_goal": "e7ae0b40ece7b9dc8c263c806da21ccde6202aa260748f9dda9af4105c93edec", + "bots_current_weapon": "e1ed1094884a7cf81a69551450213da7a851a39942a465cd678948c648a93fd3", + "bots_distance2d": "41be5000560657bafac3dd181837108653f93d7099e3774e62473b71c66f82fe", + "bots_distance3d": "7137afc484c516e0ee0951085bd4e698614c0800d558da898ddb9e61986c9c64", + "bots_find_item": "1d5791daf1c462ea2f141d1c8a81d11456eb244cac64710e8b49d22d175e9676", + "bots_find_target": "ca0c6c5e5f2c142cb599efa60087562fd92923daa15d9a6737ebd08a7e0d65ca", + "bots_follow_path": "01ade0aab6801c60870b76b894fd503d1e63496cc9a1ed7533b877ca998ab5d7", + "bots_is_enemy": "7474bb40f8018a920a012f94592cca4a8f66a8ca1f66e5d05691c923063e8e68", + "bots_item_set_unreachable": "c1e525fec5f7c18891e32f5b90caa0734794a0b5df7e0eb865162d3676388da8", + "bots_item_unreachable": "2ac4cdecda71255cd179dba8763d1ec6d197bdf154d92a3906a727cb23b77aad", + "bots_level_aim_error": "c97ef9819a32495ed15d9eb469e8c35ac941da8d9d34958c8f19f7c38c9220b5", + "bots_level_aim_point": "72eaa86c481de6cbd7dfcebbaf849d272da72e741d27614f3b6fae3c5157ca5d", + "bots_level_grenade": "4869bc152639d9848576c68b23104ff016323e2565a20b6bf3f61b1a4491cab7", + "bots_level_may_fire": "6351cb7c46b2a77e54763a70b1230c6fb84bb2901eeb25923a6bf8ecc838e214", + "bots_level_melee": "bd2be4f0cc0e348175fa181ea7ff8c927bf0c55dd08be0a982c47a2ebf312fdd", + "bots_level_move": "da06ab0900bd5169283ae4cc9bc48c075b4a1cb88d64c59b4e63b16487b8e94c", + "bots_level_prenade": "8b6450ac9ca55ee6239e4c76e47fce79e44c06746c089938446e4eee666dcac0", + "bots_level_reset": "75ab52c1e262928bc59fdb077ad4882022778116565b6eff0236d53c0e6bea3a", + "bots_level_retreat_goal": "8f394b40f348013d6800a4d18ef5886ef6a71195ca229f444e99f8256141c7db", + "bots_level_trail": "a308e0857128ee0fbb5e2f609ce7306a234bc9395e9ab3a3aa32fbe921a32c72", + "bots_line_of_sight": "a79b6f5a581babc2b6528eb6786d88053459932abf7471bb600b23543a85bafd", + "bots_object_at": "f17e625365b1ec5b3f68cca703a810d4be65e2335d5412296f984edc52b4b61c", + "bots_object_holds": "d526ffec0ad6dafa210961acff7ed3299a6d6d147bf1e2ab635d870b57737b50", + "bots_object_marks_place": "1a7af5ffa3c494080282ca0593a13ef6bfc7e0578da6fe4cd0e540871960175d", + "bots_object_supports": "2db4cf571b52e964fb74b090114eec221afe1a81f6213e247892646f4de140f0", + "bots_path_raw_steps": "cbbbae5391fc3b580fcbf14e8bceae2ef13cd42bf6f2f19ea6c0338060b8ef32", + "bots_path_stalls": "418f3625cd8e69587a2f3686417b8343f6b91d626cd54ed12b115cc4de2f22cb", + "bots_path_unsmoothed": "914203ba2fac54ddb640eb5e12807d9aea82c3ca60d762c39160a8092f37410c", + "bots_paths_close_object": "519584ba866a2ec78d1172f5037a01ac19bdecbced273de4c1e06a5c48911bd1", + "bots_paths_copy": "fe979bf9279b79563ad2e269e43f412301884095a025c769eca9542ac28cc0fe", + "bots_paths_escape_direction": "5b4f6f63873c0a6ea4aca222ec9fdec82fcee32dae02e581a4afe226c9912ea4", + "bots_paths_learn": "313f593dbf1e4b4d921f12bcc62bd1bcbf2b26c9f4131ff7259a5922594412a7", + "bots_paths_learned": "00a01fc0bef580186e5b1940ece4ee0df6b69b8baa6d34bd30fe27d4167cd88b", + "bots_paths_release": "f11bf8973a1968a6cec2cb1ca6d16edaf5f62ffaf3645a9992b2cd8f2e532650", + "bots_paths_scan": "d36fb3aeae8679f3da6254fd2f7403066ba538c049ea32c4212cca435299c225", + "bots_paths_walkable_surface": "3db4e37ae64e6e18571f511d0ca755d3e6f92355bdbb9137e1687283164a23e2", + "bots_pick_roam_goal": "ac817d5345674b5fafb14065150c19fe911f5e49c3c09fa293f90e72b337cb79", + "bots_prepare_map": "2321dcc48bb167b627b537e07c3b8f14d22ace34f5b722cb17d01a8c1ddaa1c1", + "bots_prepare_paths": "0d7dfdc0a86a7e693c5a45277299686e58132f84010f805dc98c04c61b170af4", + "bots_projectile_speed": "53fc59c027a85e364ad3ab3a6c0538b69d3c325aebcb7756cdcdd5aaa5c7f4e5", + "bots_projectile_speed_compute": "e1b45519264ecce144a5aed5a4d92cff4398da8f8a89aad9ccc35ad37fbe58b4", + "bots_random": "69db6d3edeaad3cae45a5333dbe7d883b557b192e8fbdc1d95b42d9ec511682d", + "bots_random_real": "e2d56ebe86944acfa3191b6fb0ff5474ccb91c674b3c7928628b01e14645e260", + "bots_random_signed": "5b2045ff6c9a2e5a6d3e3a7936c5d6ac5759c098e3e9e41dfeb451b3de4c980c", + "bots_report": "ba7c795f3ed2ab5368debfab2352abe1df3c54fcb799ec083377f1ee7b105606", + "bots_roam_higher": "dd20c22f4ca197feb91edb4bf4ed768c40a84a131c7683e6b59c76d42e5cd1a1", + "bots_search": "d5dd91ae63bcecaace6ea77dbd8e4208bfb24cb977037118bb9982110b40f366", + "bots_search_build": "e91021beddcb4c7fa7d9b8122410475792f01fc884f9ccff31d9bd35eaac3db7", + "bots_set_goal": "ace423ec40a92e972d490300f512cbca00e3ca62b802db8a96395f30c67559c1", + "bots_surface_below": "cda8a17c4ee6b99699d950076a108f54428d9d9c5e56a2fad7a65f113e319074", + "bots_surface_blocked": "82f7968bca03ea91c2df82b6111fa099de75fb8e71b14c5170501f3c3b26ee47", + "bots_surface_corners": "ae1419758117c81925f16b77fdf83b512515006f420b6ccc0369b4275929e658", + "bots_target_score": "e5c669b2e77f46fcb6bee57c4aadb8752d46345a6126163ca7b5a0ed200c57c9", + "bots_tick_eye": "eb77cdb19d57b60ff0902431344dedaebdd6ce05a629a00581b28008c3914d25", + "bots_unit_back_turned": "e9515db7b84976608e97b7256a09a52a5cb24d46aca41cf74f95ddcbaa91e549", + "bots_unit_surface": "7a064158d5e732bde2fd9207d1b68b04a0c15cc600309ac86a946dce142c6312", + "bots_weapon_aim_compute": "01ecf7d4f3839b7582f25eb143e1a2bb4545343d92a74b5aba53268b7e17723d", + "bots_weapon_empty": "6e581e7db3999f7472f05888faa19c85790e348c0b90a716b923b888a047d711", + "bots_weapon_kind": "ecafb36fc731f28d4139f4f6d3e40cfe35847dc8beab1bb770a3d53fdca01c1b", + "bots_weapon_loaded": "36d1384bb1bf44dc3e1915fd1308726803a8e75752741a9c317631a0bc928c7c", + "bots_weapon_range": "012a1a1e6a126aee6bde715908dd7e16ba18921fe5dfc7e70c003b795dc6bf7a", + "bots_weapon_range_compute": "4b249a6e646c8db25991536b899457b3a545d0a71833bf65460e26ee5da8b51f", + "bots_weapon_tap_ticks": "cc573c0c88a7130d8c76bc7704aeef0dae3405f66f0db39d7b8f6a949307864c", + "bots_weapon_tap_ticks_compute": "9e1c7fc3c50f72475f437ee092c7003694d94a8cc7f033084329bbc6b1577d08", + "bots_weapon_value": "d640f6bc6c88006ea138c885f4dfb2646a4b7a2ab349cd4455bc9f71f975f6ea", + "bots_weapon_value_compute": "dc5616113490855f18e8b3963eadcd000f0462d84600fb4503a9d921e7fa8369" +} diff --git a/tools/harness/tests/test_aim_assist.py b/tools/harness/tests/test_aim_assist.py index 3612e3f1bc..735bce0265 100644 --- a/tools/harness/tests/test_aim_assist.py +++ b/tools/harness/tests/test_aim_assist.py @@ -3,7 +3,7 @@ from pathlib import Path import pytest sys.path.insert(0,str(Path(__file__).resolve().parents[2])) -from harness import build,read,function,mutated,run,CHECK_FAILED +from harness import build,read,function,mutated,run,structure,CHECK_FAILED def generated(fault=None): policy=re.sub(r'^#include "[^"\n]+"\n','',read('port/linux/game/network_aim_assist.c'),flags=re.M) @@ -12,7 +12,8 @@ def generated(fault=None): if fault=='authority': policy=mutated(policy,'machine_index != NONE ||','FALSE ||') if fault=='override': inp=mutated(inp,'network_aim_assist_block_mouse() &&','FALSE &&') if fault=='controller': inp=mutated(inp,'if (gamepad_index != 0) return FALSE;','if (FALSE) return FALSE;') - return (('policy.inc',policy),('input.inc',inp),('message_ids.inc',message_ids())) + return (('policy.inc',policy),('input.inc',inp),('message_ids.inc',message_ids()), + ('message_header.inc',structure(read('port/linux/game/network_distributed.h'),'distributed_message_header'))) @pytest.mark.parametrize('case',['allowed','devices','scope','replication','admission','reset']) def test_case(case): diff --git a/tools/harness/tests/test_ambient_emitter_lighting.py b/tools/harness/tests/test_ambient_emitter_lighting.py new file mode 100644 index 0000000000..38c4879a43 --- /dev/null +++ b/tools/harness/tests/test_ambient_emitter_lighting.py @@ -0,0 +1,28 @@ +"""Run the production ambient profiles and flame aggregation against a fake world.""" +import re +import sys +from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import CHECK_FAILED, build, read, run + + +def source(): + return re.sub(r'^#include.*$', '', read('port/linux/game/ambient_emitter_lighting.h') + '\n' + + read('port/linux/game/ambient_emitter_lighting.c'), flags=re.M) + + +def test_ambient_emitters(): + status, output = run(build('ambient_emitter_lighting', (('under_test.inc', source()),)), 'ambient') + assert status == 0, output + + +def test_disabled_world_guard_is_required(): + code = source().replace('!lighting_config_boolean(profile->kind == EMITTER_VEHICLE ? "display.vehicle_lighting" : "display.world_lighting")', 'FALSE') + status, output = run(build('ambient_emitter_lighting', (('under_test.inc', code),)), 'ambient') + assert status == CHECK_FAILED, output + + +def test_flames_are_grouped_by_owner(): + code = source().replace('flames[i].owner == object->object.owner_object_index', 'FALSE') + status, output = run(build('ambient_emitter_lighting', (('under_test.inc', code),)), 'ambient') + assert status == CHECK_FAILED, output diff --git a/tools/harness/tests/test_android_cheats.py b/tools/harness/tests/test_android_cheats.py new file mode 100644 index 0000000000..1e5d0bfd6a --- /dev/null +++ b/tools/harness/tests/test_android_cheats.py @@ -0,0 +1,16 @@ +"""Real typed cheat queue and game-side permissions/lifecycle, without Android assets.""" +import re +import sys +from pathlib import Path +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import build, read, run + +@pytest.mark.parametrize("case", ["disabled", "offline", "network", "reset", "queue", "cinematic", "all-cheats", + "host", "host-disabled", "host-client", "client-lobby", "host-reset", "host-cinematic"]) +def test_cheat_menu(case): + source = read("port/android/host/host_android_cheats.c") + read("port/linux/game/android_cheats.c") + source = re.sub(r'^#include.*\n', '', source, flags=re.M) + status, output = run(build("android_cheats", (("under_test.inc", source),)), case) + assert status == 0, output diff --git a/tools/harness/tests/test_authored_emitter_lighting.py b/tools/harness/tests/test_authored_emitter_lighting.py new file mode 100644 index 0000000000..e63f906f2e --- /dev/null +++ b/tools/harness/tests/test_authored_emitter_lighting.py @@ -0,0 +1,18 @@ +"""Exact source matching, independent controls and map-scoped tag identities.""" +import re +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import CHECK_FAILED, build, read, run + + +@pytest.mark.parametrize('fault', [False, True]) +def test_authored_emitters(fault): + source = re.sub(r'^#include.*$', '', read('port/linux/game/authored_emitter_lighting.c'), flags=re.M) + if fault: + source = source.replace('definition == identities[i].light &&', 'TRUE &&') + status, output = run(build('authored_emitter_lighting', (('under_test.inc', source),)), 'profiles') + assert status == (CHECK_FAILED if fault else 0), output diff --git a/tools/harness/tests/test_bot_decisions.py b/tools/harness/tests/test_bot_decisions.py new file mode 100644 index 0000000000..0da30d8de2 --- /dev/null +++ b/tools/harness/tests/test_bot_decisions.py @@ -0,0 +1,34 @@ +"""Objective priorities and optional vehicle input, using the real feature functions.""" +import sys +from pathlib import Path +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import build, function, read, run, structure + + +@pytest.mark.parametrize("case", ["carrier", "standoff", "recovery", "powerups"]) +def test_objectives(case): + source = read("port/linux/game/enhanced_bots.c") + start = source.index("static struct\n{\n\treal head, feet") + code = source[start:source.index("};", start) + 2] + "\n" + code += "\n".join(function(source, name) for name in ( + "bots_distance3d", "bots_ctf_urgent_goal", "enhanced_bots_powerup_score", "enhanced_bots_retreat")) + status, output = run(build("bot_decisions", (("under_test.inc", code), ("bots_combat.h", read("port/linux/game/bots_combat.h")))), case) + assert status == 0, output + + +@pytest.mark.parametrize("case", ["seat", "driver", "disable", "gunner", "stuck", "ghost", "claim", "boarding", "turret", "flip", "human", "fast", "aircraft", "progress", "aircombat", "humanride", "humangunner", "large", "airfailure", "airdriverless"]) +def test_vehicles(case): + source = read("port/linux/game/bots_vehicles.c") + code = structure(source, "bots_vehicle_definition") + "\n" + # The declaration includes the vehicles array after the structure body. + code += "static " + structure(source.replace("static struct bots_vehicle_state", "struct bots_vehicle_state"), "bots_vehicle_state") + "\n" + start = source.index("static struct { real reach") + code += source[start:source.index("};", start) + 2] + "\n" + code += "\n".join(function(source, name) for name in ( + "distance", "angle", "definition", "vehicle_driver", "drivable", "bots_vehicles_reset_player", "bots_vehicles_reset", + "bots_vehicle_parent", "bots_vehicle_flying", "bots_vehicle_navigation", "bots_vehicle_weapon", "turret_seat", "seat_takeover", "seat_available", + "friendly_driver", "human_driver", "vehicle_free", "bots_vehicle_cancel", "bots_vehicle_choose_goal", "bots_vehicle_goal", "bots_vehicle_player_goal", "boarding", "turret_action", "bots_vehicle_action")) + status, output = run(build("bot_vehicles", (("under_test.inc", code),)), case) + assert status == 0, output diff --git a/tools/harness/tests/test_bots_combat.py b/tools/harness/tests/test_bots_combat.py new file mode 100644 index 0000000000..806712205e --- /dev/null +++ b/tools/harness/tests/test_bots_combat.py @@ -0,0 +1,21 @@ +"""Aim and Infection policy from the feature module, with engine inputs supplied.""" +import sys +from pathlib import Path +import pytest +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import read, function, structure, build, run + + +@pytest.mark.parametrize("case", ["precision", "explosive", "swat", "infection", "alone", "skill-mapping", "aim-precedence"]) +def test_combat(case): + source = read("port/linux/game/enhanced_bots.c") + start = source.index("static struct\n{\n\treal head, feet") + code = source[start:source.index("};", start) + 2] + "\n" + code += "\n".join(function(source, name) for name in ( + "bots_random", "bots_random_real", "bots_distance2d", "bots_distance3d", "enhanced_bots_aim", "enhanced_bots_retreat", "enhanced_bots_powerup_score")) + code += "\n" + function(read("port/linux/game/bots_combat.c"), "bots_combat_aim_head") + code += "\n" + function(read("port/linux/game/bots.c"), "bots_level_aim_point") + code += "\n" + function(read("port/linux/game/enhanced_bots_controller.c"), "bots_level_aim_point").replace("bots_level_aim_point", "enhanced_level_aim_point") + code += "\n" + read("port/linux/game/bots_infection.inl") + status, output = run(build("bots_combat", (("under_test.inc", code), ("bots_combat.h", read("port/linux/game/bots_combat.h")))), case) + assert status == 0, output diff --git a/tools/harness/tests/test_bots_lifecycle.py b/tools/harness/tests/test_bots_lifecycle.py new file mode 100644 index 0000000000..c3f9609d5a --- /dev/null +++ b/tools/harness/tests/test_bots_lifecycle.py @@ -0,0 +1,13 @@ +"""The retained route/vantage allocators, including partial and repeated disposal.""" +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import build, function, read, run + + +def test_disposal(): + source = function(read("port/linux/game/bots_routes.c"), "bots_routes_free") + source += function(read("port/linux/game/bots_vantage.c"), "bots_vantage_free") + status, output = run(build("bots_lifecycle", (("under_test.inc", source),)), "dispose") + assert status == 0, output diff --git a/tools/harness/tests/test_bots_lobby.py b/tools/harness/tests/test_bots_lobby.py index ccc06f98ea..d029d900ec 100644 --- a/tools/harness/tests/test_bots_lobby.py +++ b/tools/harness/tests/test_bots_lobby.py @@ -1,6 +1,6 @@ """The real lobby of network_server_manager.c's bots (bots.count): as many as the setting asks for join a local Slayer game's lobby, as far as it has room, on the teams bots.teams asks for, follow the players' team changes and leave when -fewer are asked for; none in a game other machines may join, in another gametype, or once the game has started.""" +fewer are asked for; stock exclusions, optional objective/network admission, ownership and no admission after game start.""" import re import sys @@ -12,14 +12,18 @@ from harness import CHECK_FAILED, build, constant, enum_with, function, mutated, read, run, structure # noqa: E402 CASES = ["fills", "room", "fewer", "even", "against", "follows-players", "never-network", "slayer-only", - "not-once-started", "no-player-no-bots", "names-and-machines"] + "not-once-started", "no-player-no-bots", "names-and-machines", "enhanced-objectives", "network-opt-in", "human-high-id", + "live", "live-permissions", "live-encode-failure", "lobby-enable", "lobby-disable", + "lobby-enable-conflict", "lobby-apply-guards", "human-count", "population-lobby", "population-live", + "population-wait", "population-invalid", "population-manual", "population-lifecycle", + "population-split", "population-human-full", "population-cancel", "population-queue", + "population-empty", "population-concurrent", "population-manual-crowded"] GAME_MANAGER_FUNCTIONS = ("network_game_invalidate_player", "network_player_is_valid", "network_game_player_is_valid", - "network_game_add_player", "network_game_remove_player") + "network_game_add_player", "network_game_remove_player", "network_game_has_free_player_slot") # a fault in network_game_server_port_bots, and the case that must catch it NEGATIVE_CONTROLS = { - "bots-in-network-games": (("network_game_is_splitscreen_local() && ", ""), "never-network"), - "bots-in-any-gametype": ((" && server->game.variant.game_engine_index == game_engine_slayer", ""), "slayer-only"), + "bots-in-any-gametype": (("bots_gametype_allowed(server->game.variant.game_engine_index)", "TRUE"), "slayer-only"), "bots-once-started": (("server->state != _network_game_server_state_pregame || server->sent_start_game_message", "server->state != _network_game_server_state_pregame"), "not-once-started"), "teams-not-evened": (("team_counts[1] < team_counts[0] ? 1 : 0", "1"), "even"), @@ -43,6 +47,7 @@ def generated(fault=None): config += f"#define MAXIMUM_LOCAL_PLAYERS {constant(read('source/game/players.h'), 'MAXIMUM_LOCAL_PLAYERS')}\n" config += f"#define NUMBER_OF_MULTIPLAYER_TEAMS {constant(server, 'NUMBER_OF_MULTIPLAYER_TEAMS')}\n" config += f"#define BOTS_MAXIMUM {constant(bots_header, 'BOTS_MAXIMUM')}\n" + config += f"#define NETWORK_GAME_PLAYER_QUIT_DELAY {constant(server, 'NETWORK_GAME_PLAYER_QUIT_DELAY')}\n" match = re.search(r"^#define BOTS_FIRST_MACHINE .*$", bots_header, re.M) assert match, "BOTS_FIRST_MACHINE not found in bots.h" config += match.group(0) + "\n" @@ -51,14 +56,30 @@ def generated(fault=None): config += enum_with(read("source/game/game_engine.h"), "game_engine_slayer") + "\n" config += structure(read("source/game/players.h"), "network_player") + "\n" code = "" + network = read("port/linux/game/bots_network.c") + code += "static int network_bots, network_bots_enabled;\nstatic byte owned[BOTS_MAXIMUM];\nint bots_machine_is_bot(long machine_index);\n" + code += "\n".join(re.findall(r"^static long population_.*;", network, re.M)) + "\n" + code += "int network_player_is_valid(struct network_player *player);\n" + code += "int bots_session_allowed(void);\nint bots_player_owned(long machine_index);\n" + for name in ("bots_network_session_begin", "bots_network_session_end", "bots_network_reserved", "bots_session_allowed", + "bots_player_ownership", "bots_player_owned", "bots_network_lobby_enable", "bots_human_count", + "bots_population_wanted", "bots_population_changed", "bots_population_after_join"): + code += function(network, name) + "\n" for name in GAME_MANAGER_FUNCTIONS: code += function(manager, name) + "\n" - for name in ("bots_machine_is_bot", "bots_network_player"): + for name in ("bots_machine_is_bot", "bots_network_player", "bots_gametype_allowed", "bots_gametype_active"): code += function(bots, name) + "\n" lobby = function(server, "network_game_server_port_bots") if fault: lobby = mutated(lobby, *fault) code += lobby + "\n" + code += read("port/linux/game/bots_management.inl") + code += read("port/linux/game/bots_population.inl") + # Exercise the actual pregame connection gate as well as player admission. + handler = function(read("source/networking/network_server_message_handler.c"), + "network_game_server_handle_message_client_join_game_request") + full = re.search(r"boolean full = .*?;", handler, re.S).group(0) + code += "\nstatic boolean lobby_join_full(struct network_game_server *server)\n{\n" + full + "\nreturn full;\n}\n" return (("config.inc", config), ("under_test.inc", code)) @@ -73,3 +94,26 @@ def test_negative_control(control): fault, case = NEGATIVE_CONTROLS[control] status, output = run(build("bots_lobby", generated(fault)), case) assert status == CHECK_FAILED, f"the bots' lobby with a fault ({control}) passed '{case}': the test cannot see it" + + +def test_lobby_setting_activation_is_required(): + files = dict(generated()) + files["under_test.inc"] = mutated(files["under_test.inc"], "bots_network_lobby_enable(enabled);", "") + status, output = run(build("bots_lobby", tuple(files.items())), "lobby-enable") + assert status == CHECK_FAILED, f"missing lobby activation passed: {output}" + + +@pytest.mark.parametrize("before,after,case", [ + ("!bots_player_owned(game->players[index].machine_index)", "1", "human-count"), + ("MIN(population_target, game->maximum_players) - humans", "MIN(population_target, game->maximum_players) - 1", "population-live"), + ("if (server->queued_player_valid || server->waiting_player_count > 0) return;", "", "population-queue"), + ("if (result) bots_population_changed(&server->game, add ? 1 : -1);", "", "population-manual"), + ("if (now - bots_population_wait_started >= 10000UL) return FALSE;", "", "population-wait"), + ("!bots_population_can_join(server);", "TRUE;", "population-lobby"), + ("MAX(population_target + change, game->player_count)", "population_target + change", "population-manual-crowded"), +]) +def test_population_negative_controls(before, after, case): + files = dict(generated()) + files["under_test.inc"] = mutated(files["under_test.inc"], before, after) + status, output = run(build("bots_lobby", tuple(files.items())), case) + assert status == CHECK_FAILED, f"population regression missed {case}: {output}" diff --git a/tools/harness/tests/test_bots_menu_actions.py b/tools/harness/tests/test_bots_menu_actions.py new file mode 100644 index 0000000000..d7773e8ec7 --- /dev/null +++ b/tools/harness/tests/test_bots_menu_actions.py @@ -0,0 +1,13 @@ +"""The actual bot UI and console handlers route typed actions and show feedback.""" +from pathlib import Path +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import build, function, read, run + + +def test_actions_and_host_feedback(): + code = read("port/linux/game/bots_menu.inl") + code += function(read("port/linux/game/bots_network.c"), "bots_console_command") + status, output = run(build("bots_menu", (("under_test.inc", code), ("bots.h", ""))), "actions") + assert status == 0, output diff --git a/tools/harness/tests/test_bots_navigation.py b/tools/harness/tests/test_bots_navigation.py new file mode 100644 index 0000000000..5a6c7f0c97 --- /dev/null +++ b/tools/harness/tests/test_bots_navigation.py @@ -0,0 +1,43 @@ +"""Real link planner, measured shortcuts, traversal and lifecycle in a tiny graph.""" +import sys +from pathlib import Path +import pytest +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import read, function, build, run, mutated + + +def implementation(): + source = read("port/linux/game/bots_navigation.inl") + code = source[source.index("#define BOTS_NAV_LINKS"):source.index("static void bots_navigation_reset")] + code += "\n".join(function(source, name) for name in ( + "bots_navigation_reset", "bots_navigation_reset_bot", "bots_navigation_climbing", "bots_navigation_pays", + "bots_navigation_cost", "bots_navigation_remaining", "bots_navigation_drop", "bots_navigation_claimers", + "bots_navigation_query", "bots_navigation_answer", "bots_navigation_update", "bots_navigation_follow", + "bots_navigation_action")) + code += function(read("port/linux/game/enhanced_bots_controller.c"), "bots_bot_unstick") + return code + + +@pytest.mark.parametrize("case", ["measure", "reject", "reservation", "ladder", "climb_recovery", "tall_ladder", "timeout", "lifecycle"]) +def test_navigation(case): + status, output = run(build("bots_navigation", (("under_test.inc", implementation()),)), case) + assert status == 0, output + + +def test_measured_cost_is_required(): + code = mutated(implementation(), "route->entrance_cost + beyond", "route->entrance_cost") + status, output = run(build("bots_navigation", (("under_test.inc", code),)), "reject") + assert status == 1 and "expensive exit" in output, output + + +def test_empty_cleanup_respects_engine_allocator(): + code = mutated(implementation(), "if (bots_navigation.vehicle_walkable) free(bots_navigation.vehicle_walkable - 1)", + "free(bots_navigation.vehicle_walkable ? bots_navigation.vehicle_walkable - 1 : NULL)") + status, output = run(build("bots_navigation", (("under_test.inc", code),)), "lifecycle") + assert status == 1 and "engine free received NULL" in output, output + + +def test_vertical_climb_is_not_stuck(): + code = mutated(implementation(), "route->climb_tick != 0", "route->climb_tick == 0") + status, output = run(build("bots_navigation", (("under_test.inc", code),)), "climb_recovery") + assert status == 1 and "climb mistaken for stuck movement" in output, output diff --git a/tools/harness/tests/test_bots_powerups.py b/tools/harness/tests/test_bots_powerups.py new file mode 100644 index 0000000000..170434bceb --- /dev/null +++ b/tools/harness/tests/test_bots_powerups.py @@ -0,0 +1,13 @@ +"""Contested powerups use distance and a stable tie-break, not duplicate pursuit.""" +import sys +from pathlib import Path +import pytest +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import read, function, build, run + + +@pytest.mark.parametrize("case", ["closer", "tie", "released"]) +def test_claims(case): + code = function(read("port/linux/game/bots_powerups.inl"), "bots_powerup_claimed") + status, output = run(build("bots_powerups", (("under_test.inc", code),)), case) + assert status == 0, output diff --git a/tools/harness/tests/test_bots_stock_preservation.py b/tools/harness/tests/test_bots_stock_preservation.py new file mode 100644 index 0000000000..989fd778e5 --- /dev/null +++ b/tools/harness/tests/test_bots_stock_preservation.py @@ -0,0 +1,32 @@ +"""Stock decision algorithms remain the 7ea7b0bf7 implementation. +The manifest hashes original function bodies, excluding admission/dispatch APIs. +""" +import hashlib +import json +import re +import sys +from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import read, function, build, run + +def test_stock_algorithms_preserved(): + expected = json.loads(Path(__file__).with_name("stock_bots_functions.json").read_text()) + source = read("port/linux/game/bots.c") + for name, digest in expected.items(): + actual = re.sub(r"\s+", "", function(source, name)) + assert hashlib.sha256(actual.encode()).hexdigest() == digest, name + +def test_enhanced_controller_is_selected_before_stock_loop(): + source = function(read("port/linux/game/bots.c"), "bots_update_actions") + dispatch = source.index("enhanced_controller_update(actions)") + assert source.index("return;", dispatch) < source.index("data_iterator_new") + enhanced = read("port/linux/game/enhanced_bots_controller.c") + assert "bots_enhanced_running" not in enhanced + assert 'include "bots.c"' not in enhanced + + +def test_controller_ownership_across_map_changes(): + source = read("port/linux/game/bots.c") + code = function(source, "bots_initialize_for_new_map") + function(source, "bots_dispose_from_old_map") + status, output = run(build("bots_controller_lifecycle", (("under_test.inc", code),)), "ownership") + assert status == 0, output diff --git a/tools/harness/tests/test_bots_worker.py b/tools/harness/tests/test_bots_worker.py new file mode 100644 index 0000000000..e69542872b --- /dev/null +++ b/tools/harness/tests/test_bots_worker.py @@ -0,0 +1,23 @@ +"""Snapshot ownership, stale replies and cleanup of the optional path worker.""" +import sys +from pathlib import Path +import pytest +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import read, build, run, mutated + + +@pytest.mark.parametrize("case", ["snapshot", "stale", "goal", "boarding", "seat", "cleanup", "disabled", "malformed", "allocation", "graph_allocation"]) +def test_worker(case): + source = read("port/linux/game/bots_worker.inl") + code = source[source.index("struct bots_path_job"):] + status, output = run(build("bots_worker", (("under_test.inc", code),)), case) + assert status == 0, output + + +def test_worker_uses_engine_allocator(): + source = read("port/linux/game/bots_worker.inl") + code = source[source.index("struct bots_path_job"):] + code = mutated(code, "malloc(BOTS_SEARCHES_A_TICK * sizeof(struct bots_path_job))", + "calloc(BOTS_SEARCHES_A_TICK, sizeof(struct bots_path_job))") + status, output = run(build("bots_worker", (("under_test.inc", code),)), "cleanup") + assert status == 1 and "does not belong to engine allocator" in output, output diff --git a/tools/harness/tests/test_cheat_spawns.py b/tools/harness/tests/test_cheat_spawns.py new file mode 100644 index 0000000000..e0457a3b78 --- /dev/null +++ b/tools/harness/tests/test_cheat_spawns.py @@ -0,0 +1,23 @@ +"""Host weapon cheats must not create unowned objectives that clients refuse.""" +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import build, enum_with, function, read, run + + +@pytest.mark.parametrize("case", ["host-list", "host-fallback", "offline-list", "offline-fallback", + "other-objects", "no-player"]) +def test_cheat_spawns(case): + source = read("source/game/cheats.c") + config = "\n".join([ + enum_with(read("source/game/game.h"), "_game_connection_local"), + enum_with(read("source/objects/object_types.h"), "_object_type_biped"), + enum_with(read("source/items/weapon_definitions.h"), "_weapon_vertical_heat_display_bit"), + ]) + code = "\n".join(function(source, name) for name in + ["cheat_objects", "cheat_objects_from_block", "cheat_all_weapons"]) + status, output = run(build("cheat_spawns", (("config.inc", config), ("under_test.inc", code))), case) + assert status == 0, output diff --git a/tools/harness/tests/test_cinematic_titles.py b/tools/harness/tests/test_cinematic_titles.py index 042b1b3336..bd2d25fc86 100644 --- a/tools/harness/tests/test_cinematic_titles.py +++ b/tools/harness/tests/test_cinematic_titles.py @@ -1,5 +1,8 @@ -"""The real cinematic_render (cinematics.c) over a fake scenario: a scenario's title is drawn in the game, not over a -menu, and its time goes on under one; on a wide screen, the edge it is justified to keeps its place.""" +"""Exercise the real cinematic_render over a fake scenario. + +Titles draw in the game, not over menus; their time advances under menus. +Widescreen placement follows alignment, and MCC non-wrapping titles avoid clipping. +""" import sys from pathlib import Path @@ -9,22 +12,23 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[2])) from harness import CHECK_FAILED, build, constant, function, mutated, read, run, structure # noqa: E402 -CASES = ["drawn-in-the-game", "not-over-a-menu", "time-goes-on-under-a-menu", "right-justified-on-a-wide-screen", - "left-justified-on-a-wide-screen", "centered-on-a-wide-screen", "unmoved-on-640-columns"] +CASES = [ + "title-screen-anchors", "default-title-anchor", "mcc-title-screen-anchor", + "mcc-title-bounds", "mcc-title-anchors", "drawn-in-the-game", + "not-over-a-menu", "time-goes-on-under-a-menu", +] # a fault in cinematic_render and the case that must catch it NEGATIVE_CONTROLS = { + "right-title-uses-box-center": (("case 1: anchor = title_bounds->x1; break;", + "case 1: anchor = (short)((title_bounds->x0 + title_bounds->x1) / 2); break;"), + "default-title-anchor"), + "mcc-title-clipped": (("mcc_hud_title_bounds(&wide_bounds, title->justification, title->text_flags);", + "(void)0;"), "mcc-title-bounds"), "drawn-over-a-menu": (("if (!ui_widgets_active())", "if (TRUE)"), "not-over-a-menu"), "time-stops-under-a-menu": (("active_title->time += game_time_get_paused()", "active_title->time += ui_widgets_active() || game_time_get_paused()"), "time-goes-on-under-a-menu"), - # the box's middle moved, whatever the justification, as before the fix - "right-justified-moved-by-its-middle": (("anchor = title_bounds->x1;", - "anchor = (short)((title_bounds->x0 + title_bounds->x1) / 2);"), - "right-justified-on-a-wide-screen"), - "left-justified-moved-by-its-middle": (("anchor = title_bounds->x0;", - "anchor = (short)((title_bounds->x0 + title_bounds->x1) / 2);"), - "left-justified-on-a-wide-screen"), } @@ -39,7 +43,8 @@ def generated(fault=None): code = function(cinematics, "cinematic_render") if fault: code = mutated(code, *fault) - return (("config.inc", config), ("under_test.inc", code + "\n")) + helper = function(read("port/linux/game/mcc_hud_draw.c"), "mcc_hud_title_bounds") + return (("config.inc", config), ("under_test.inc", helper + "\n" + code + "\n")) @pytest.mark.parametrize("case", CASES) diff --git a/tools/harness/tests/test_contrail_tick_points.py b/tools/harness/tests/test_contrail_tick_points.py index 8aa538e9c1..eb7e13f506 100644 --- a/tools/harness/tests/test_contrail_tick_points.py +++ b/tools/harness/tests/test_contrail_tick_points.py @@ -12,7 +12,7 @@ from harness import CHECK_FAILED, build, constant, enum_with, function, mutated, read, run, structure # noqa: E402 CASES = ["steady-at-144", "uneven-frames", "time-jumps"] -FUNCTIONS = ("contrail_scale_value", "contrail_scale_random_value", "contrail_next_frame", +FUNCTIONS = ("contrails_reset_render_state", "contrail_scale_value", "contrail_scale_random_value", "contrail_next_frame", "contrail_compute_new_point_count", "contrail_add_points", "contrail_update_points", "contrails_update") # a fault in the code and the case that must catch it @@ -21,8 +21,8 @@ "frames-time": (("point_dt = (real)ticks / TICKS_PER_SECOND;", "point_dt = dt * 4.8f * (real)ticks;"), "uneven-frames"), # the points aged every frame by its own time (before fix-contrail-point-ticks) - "aged-each-frame": (("if (point_dt > 0.0f)\n\t\t\tcontrail_update_points(contrail_index, point_dt);", - "if (dt > 0.0f)\n\t\t\tcontrail_update_points(contrail_index, dt);"), "steady-at-144"), + "aged-each-frame": (("contrail_update_points(contrail_index, dt, point_dt);", + "contrail_update_points(contrail_index, dt, dt);"), "steady-at-144"), # a game time gone back ages the points backwards "time-back": (("ticks < 1 || ", ""), "time-jumps"), # a game time jumping ahead ages them all at once @@ -47,7 +47,8 @@ def generated(fault=None): structure(definitions, "contrail_shader"), structure(definitions, "contrail_definition"), ]) + "\n" - code = "\n".join(function(source, name) for name in FUNCTIONS) + "\n" + clocks = source.split("/* ---------- globals */", 1)[1].split("/* ---------- public code */", 1)[0] + code = clocks + "\n".join(function(source, name) for name in FUNCTIONS) + "\n" if fault: code = mutated(code, *fault) return (("config.inc", config), ("under_test.inc", code)) diff --git a/tools/harness/tests/test_contrails.py b/tools/harness/tests/test_contrails.py new file mode 100644 index 0000000000..ec525de1ae --- /dev/null +++ b/tools/harness/tests/test_contrails.py @@ -0,0 +1,67 @@ +"""Real contrail emission, point-state aging and map lifecycle at varied render rates.""" +import os +import re +from pathlib import Path +import subprocess +import sys + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import HARNESS, enum_with, function, read, structure + + +@pytest.fixture(scope="module") +def executables(tmp_path_factory): + source = read("source/effects/contrails.c") + header = read("source/effects/contrails.h") + definitions = read("source/effects/contrail_definitions.h") + config = "\n".join(structure(header, n) for n in ("contrail_datum", "contrail_point_datum")) + config += "\n" + structure(definitions, "contrail_point_state") + config += "\n" + "\n".join(enum_with(source, n) for n in ( + "_contrail_active_bit", "_contrail_point_new_bit", "_contrail_state_duration_bit", + "_contrail_scales_point_generation_rate_bit")) + code = "\n".join(function(source, n) for n in ( + "contrails_reset_render_state", "contrails_initialize_for_new_map", "contrails_dispose_from_old_map", + "contrail_scale_value", "contrail_scale_random_value", "contrail_compute_new_point_count", + "contrail_update_points", "contrails_update")) + clocks = source.split("/* ---------- globals */", 1)[1].split("/* ---------- public code */", 1)[0] + state = read("source/saved games/game_state.c") + callbacks = re.search(r"static game_state_after_load_proc after_load_procs\[\] =\s*\{.*?\};", state, re.S).group(0) + names = re.findall(r"^\s*(\w+)\s*,?\s*$", callbacks, re.M) + after_load = "typedef void (*game_state_after_load_proc)(void);\n#define NUMBEROF(a) (sizeof(a) / sizeof((a)[0]))\n" + after_load += "\n".join(f"static void {name}(void) {{ }}" for name in names if name != "contrails_reset_render_state") + after_load += "\n" + callbacks + "\n" + function(state, "game_state_call_after_load_procs") + result = {} + for variant in ("fixed", "frame-aging", "stale-clock", "missing-hook"): + work = tmp_path_factory.mktemp("contrails-" + variant) + (work / "config.inc").write_text(config) + selected = code + if variant == "frame-aging": + before = "contrail_update_points(contrail_index, dt, point_dt);" + assert selected.count(before) == 1 + selected = selected.replace(before, "contrail_update_points(contrail_index, dt, dt);") + if variant == "stale-clock": + selected = selected.replace("last_point_game_time = NONE;", "") + (work / "under_test.inc").write_text(clocks + selected) + (work / "after_load.inc").write_text(after_load.replace("\tcontrails_reset_render_state,", "") if variant == "missing-hook" else after_load) + exe = work / ("contrails.exe" if os.name == "nt" else "contrails") + flags = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld"] if os.name == "nt" else ["-m32"] + subprocess.run([os.environ.get("CC", "clang"), *flags, "-std=gnu89", "-O2", "-Wall", "-Werror", + "-Wno-unused-function", "-Wno-unused-variable", "-Wno-parentheses", + "-I", str(HARNESS / "include"), "-I", str(work), + str(HARNESS / "tests/contrails.c"), "-o", str(exe)], check=True) + result[variant] = exe + return result + + +@pytest.mark.parametrize("case", ["rates", "irregular", "lifecycle", "new-point", "pause-activation", "detached", "checkpoint", "catch-up", "double-speed"]) +def test_contrails(executables, case): + result = subprocess.run([str(executables["fixed"]), case], capture_output=True, text=True) + assert result.returncode == 0, result.stdout + result.stderr + + +@pytest.mark.parametrize("variant,case", [("frame-aging", "rates"), ("frame-aging", "irregular"), ("stale-clock", "lifecycle"), ("missing-hook", "checkpoint")]) +def test_negative_control(executables, variant, case): + result = subprocess.run([str(executables[variant]), case], capture_output=True, text=True) + assert result.returncode == 1, result.stdout + result.stderr diff --git a/tools/harness/tests/test_coop_wipe.py b/tools/harness/tests/test_coop_wipe.py index 37d86efa53..669cf3eecc 100644 --- a/tools/harness/tests/test_coop_wipe.py +++ b/tools/harness/tests/test_coop_wipe.py @@ -9,7 +9,7 @@ from harness.coop_wipe import generated -@pytest.mark.parametrize('case', ['policy', 'authority', 'roster', 'save', 'new-map', 'delay', 'failure']) +@pytest.mark.parametrize('case', ['policy', 'authority', 'roster', 'save', 'new-map', 'mcc-save', 'console-save', 'delay', 'failure']) def test_team_wipe(case): status, output = run(build('coop_wipe', generated()), case) assert status == 0, output diff --git a/tools/harness/tests/test_covenant_emitter_lighting.py b/tools/harness/tests/test_covenant_emitter_lighting.py new file mode 100644 index 0000000000..e64f9dbff2 --- /dev/null +++ b/tools/harness/tests/test_covenant_emitter_lighting.py @@ -0,0 +1,57 @@ +"""Exercise the real emitter policy, render-time easing and light ownership.""" +import re +import sys +from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import CHECK_FAILED, build, read, run + + +def source(): + return re.sub(r'^#include.*$', '', read('port/linux/game/ambient_emitter_lighting.h') + '\n' + read('port/linux/game/needler_lighting.c') + '\n' + read('port/linux/game/ammo_counter_lighting.c') + '\n' + read('port/linux/game/covenant_emitter_lighting.c'), flags=re.M) + + +def test_emitters(): + status, output = run(build('covenant_emitter_lighting', (('under_test.inc', source()),)), 'emitters') + assert status == 0, output + + +def test_ambient_saturation_preserves_existing_emitters(): + code = source().replace('sample.kind < EMITTER_VEHICLE && sample.strength > 0.0f', 'FALSE') + status, output = run(build('covenant_emitter_lighting', (('under_test.inc', code),)), 'emitters') + assert status == CHECK_FAILED, output + + +def test_shield_permutation_guard_is_required(): + code = source().replace('object->object.region_permutations[i] == 0', 'TRUE') + status, output = run(build('covenant_emitter_lighting', (('under_test.inc', code),)), 'emitters') + assert status == CHECK_FAILED, output + + +def test_tick_only_fade_is_detected(): + code = source().replace('render_interpolation_game_time_sec(game_time_get())', '(real)game_time_get() / 30.0f') + status, output = run(build('covenant_emitter_lighting', (('under_test.inc', code),)), 'emitters') + assert status == CHECK_FAILED, output + + +def test_first_person_counter_pose_is_required(): + code = source().replace('if (first_person_weapon_adjust_light(index, "primary trigger", position, &forward, &up))', 'if (FALSE)') + status, output = run(build('covenant_emitter_lighting', (('under_test.inc', code),)), 'emitters') + assert status == CHECK_FAILED, output + + +def test_shield_damage_colour_is_required(): + code = source().replace('PIN(object->object.outgoing_function_values[0], 0.0f, 1.0f)', '0.0f') + status, output = run(build('covenant_emitter_lighting', (('under_test.inc', code),)), 'emitters') + assert status == CHECK_FAILED, output + + +def test_needle_crystal_glow_is_required(): + code = source().replace('*output |= 0x10000UL;', '*output |= 0;') + status, output = run(build('covenant_emitter_lighting', (('under_test.inc', code),)), 'emitters') + assert status == CHECK_FAILED, output + + +def test_first_person_counter_strength_is_required(): + code = source().replace('counter_pose == 2 ? 1.35f / 0.65f : 1.0f', '1.0f') + status, output = run(build('covenant_emitter_lighting', (('under_test.inc', code),)), 'emitters') + assert status == CHECK_FAILED, output diff --git a/tools/harness/tests/test_covenant_lighting.py b/tools/harness/tests/test_covenant_lighting.py new file mode 100644 index 0000000000..22f1090b4a --- /dev/null +++ b/tools/harness/tests/test_covenant_lighting.py @@ -0,0 +1,35 @@ +"""Flight-light ownership uses the real feature module with fake engine services.""" +import re +import sys +from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import CHECK_FAILED, build, read, run + + +def test_owned_lights(): + code = re.sub(r'^#include.*$', '', read('port/linux/game/covenant_lighting.c'), flags=re.M) + status, output = run(build('covenant_lighting', (('under_test.inc', code),)), 'ownership') + assert status == 0, output + + +def test_render_color_and_map_lifecycle(): + code = re.sub(r'^#include.*$', '', read('port/linux/game/covenant_lighting.c'), flags=re.M) + status, output = run(build('covenant_lighting', (('under_test.inc', code),)), 'color') + assert status == 0, output + + +def test_missing_reconnection_is_detected(): + code = re.sub(r'^#include.*$', '', read('port/linux/game/covenant_lighting.c'), flags=re.M) + assert code.count('light_reconnect_to_map(light->light_index);') == 1 + code = code.replace('light_reconnect_to_map(light->light_index);', '(void)0;') + status, output = run(build('covenant_lighting', (('under_test.inc', code),)), 'ownership') + assert status == CHECK_FAILED, output + + +def test_particle_only_rejection_is_detected(): + code = re.sub(r'^#include.*$', '', read('port/linux/game/covenant_lighting.c'), flags=re.M) + guard = ' && definition->object.model.index != NONE' + assert code.count(guard) == 1 + code = code.replace(guard, '') + status, output = run(build('covenant_lighting', (('under_test.inc', code),)), 'ownership') + assert status == CHECK_FAILED, output diff --git a/tools/harness/tests/test_damage_owner_lookup.py b/tools/harness/tests/test_damage_owner_lookup.py new file mode 100644 index 0000000000..3d96d06a8f --- /dev/null +++ b/tools/harness/tests/test_damage_owner_lookup.py @@ -0,0 +1,24 @@ +"""Late projectile damage must tolerate a retired owner without following its slot.""" +import pytest +from tools.harness import CHECK_FAILED, build, function, mutated, read, run + + +def executable(fault=False): + code = function(read('source/objects/damage.c'), 'get_player_index_from_object_or_parents') + if fault: + code = mutated(code, 'object = object_try_and_get(object_index);', + 'object = object_get(object_index);') + return build('damage_owner_lookup', (('under_test.inc', code),)) + + +@pytest.mark.parametrize('case', ['none', 'live', 'ai', 'parent', 'chain', + 'unparented', 'deleted', 'reused', 'deleted-parent']) +def test_lookup(case): + status, output = run(executable(), case) + assert status == 0, output + + +@pytest.mark.parametrize('case', ['deleted', 'reused', 'deleted-parent']) +def test_strict_lookup_regression(case): + status, output = run(executable(True), case) + assert status == CHECK_FAILED, output diff --git a/tools/harness/tests/test_dualsense_rules.py b/tools/harness/tests/test_dualsense_rules.py new file mode 100644 index 0000000000..9efef4c0bc --- /dev/null +++ b/tools/harness/tests/test_dualsense_rules.py @@ -0,0 +1,74 @@ +"""A PS5 DualSense's output bytes (port/linux/src/dualsense_rules.c): the trigger effects, the weapon profiles by the +weapon's state and the trigger strength, the lightbar and player lights, the USB and Bluetooth reports with their CRC, +and the link that writes only what changed (one report a frame, one every 50 ms on Bluetooth).""" + +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import CHECK_FAILED, build, mutated, read, run # noqa: E402 + +CASES = [ + "effects", "kinds", "held", "strength", "events", "left", "lights", "reports", "link-usb", + "link-bluetooth", "bind", +] + +# a fault in dualsense_rules.c and the case that must catch it +NEGATIVE_CONTROLS = { + "strength-zero-not-off": (("\tif (strength <= 0)\n\t{\n\t\tdualsense_effect_off(effect);\n\t\treturn;\n\t}\n\tmemset(effect, 0, " + "DUALSENSE_EFFECT_SIZE);\n\teffect[0] = 0x21;\n\tzones(effect, clamp(position", + "\tmemset(effect, 0, DUALSENSE_EFFECT_SIZE);\n\teffect[0] = 0x21;\n\tzones(effect, clamp(position"), + "effects"), + "weapon-end-before-start": (("end = clamp(end, start + 1, 8);", "end = clamp(end, start, 8);"), "effects"), + "any-maker": (("return vendor == 0x054c && (product", "return (product"), "kinds"), + "reload-not-free": (("state->readying || (state->reloading && !state->overheated)", "state->readying"), "held"), + "empty-not-dry": (("\tif (state->empty)\n\t{", "\tif (0)\n\t{"), "held"), + "readying-not-free": (("shape.mode == OFF || state->readying ||", "shape.mode == OFF ||"), "held"), + "overheat-not-locked": (("\tif (state->overheated)\n\t{", "\tif (0)\n\t{"), "held"), + "sniper-needs-no-zoom": (("zoom_levels >= 2 && rate_of_fire < 3.0f", "zoom_levels >= 1 && rate_of_fire < 3.0f"), "kinds"), + "light-not-hair": (("return percent <= DUALSENSE_STRENGTH_LIGHT;", "return percent < DUALSENSE_STRENGTH_LIGHT;"), + "strength"), + "strong-one-step": (("#define STRONG_STEPS 2", "#define STRONG_STEPS 1"), "strength"), + "automatic-kicks": (("{ F(3, 2), V(3, 5, 0), NO, 0, 1, 0, 0, \"light hold, a pulse a round\", NO, 0 }", + "{ F(3, 2), V(3, 5, 0), F(0, 7), 35, 1, 0, 0, \"light hold, a pulse a round\", NO, 0 }"), + "events"), + "grenade-hair-tick-missing": (("else if (grenades > 0)", "else if (0)"), "left"), + "player-lights-slow": (("return (unsigned char)(player_lights[player_number - 1] | 0x20);", + "return player_lights[player_number - 1];"), "lights"), + "crc-without-header": (("crc = dualsense_crc32(0, &hidp_header, 1);", "crc = 0;"), "reports"), + "sequence-dropped": (("report[1] = (unsigned char)((sequence & 0x0f) << 4);", "report[1] = 0;"), "reports"), + "gone-is-refused": (("\tcase ENODEV:\n", ""), "reports"), + "changes-not-seen": (("memcmp(link->want + span->at, link->sent + span->at, (size_t)span->size))", "0)"), "link-usb"), + "bluetooth-no-window": (("link->open_ms = now + (link->bluetooth ? DUALSENSE_BLUETOOTH_INTERVAL_MS : 0);", + "link->open_ms = now;"), "link-bluetooth"), + "busy-retried-at-once": (("link->open_ms = now + (link->bluetooth ? DUALSENSE_BLUETOOTH_INTERVAL_MS : " + "DUALSENSE_BUSY_RETRY_MS);", "link->open_ms = now;"), "link-bluetooth"), + "gone-not-forgotten": (("\tif (result == DUALSENSE_WRITE_GONE)\n\t\tdualsense_link_forget(link);", ""), + "link-bluetooth"), + "all-enable-bits": (("\tif (fields & DUALSENSE_FIELD_LIGHTBAR)\n\t\tbody[DUALSENSE_BODY_ENABLE2] |= " + "DUALSENSE_ENABLE2_LIGHTBAR;", "\tbody[DUALSENSE_BODY_ENABLE2] |= DUALSENSE_ENABLE2_LIGHTBAR;"), + "link-usb"), + "pad-keeps-old-port": (("if (other != port && bound[other] == id)", "if (0)"), "bind"), +} + + +def generated(fault=None): + code = read("port/linux/src/dualsense_rules.c") + if fault: + code = mutated(code, *fault) + return (("dualsense_rules.h", read("port/linux/src/dualsense_rules.h")), ("under_test.inc", code)) + + +@pytest.mark.parametrize("case", CASES) +def test_case(case): + status, output = run(build("dualsense_rules", generated()), case) + assert status == 0, output + + +@pytest.mark.parametrize("control", NEGATIVE_CONTROLS) +def test_negative_control(control): + fault, case = NEGATIVE_CONTROLS[control] + status, output = run(build("dualsense_rules", generated(fault)), case) + assert status == CHECK_FAILED, f"dualsense_rules.c with a fault ({control}) passed '{case}': the test cannot see it" diff --git a/tools/harness/tests/test_dynamic_shader_isolation.py b/tools/harness/tests/test_dynamic_shader_isolation.py new file mode 100644 index 0000000000..2314d73e7e --- /dev/null +++ b/tools/harness/tests/test_dynamic_shader_isolation.py @@ -0,0 +1,45 @@ +"""Exercise real shader selection/caching and GPU guards with counted GL calls.""" +import pytest +from tools.harness import CHECK_FAILED, build, function, mutated, read, run, structure + + +def executable(android=False, fault=None): + renderer = read('port/linux/src/d3d8_gl.c') + header = read('port/linux/src/xgpu.h') + code = '#define HALO_ANDROID 1\n' if android else '' + code += '\n'.join(structure(header, n) for n in ('nv2a_vertex_lighting', 'nv2a_pixel_shader_key')) + code += '\n' + structure(renderer, 'vertex_element') + code += '\n' + structure(renderer, 'vertex_shader_object') + code += '\nstatic struct { struct vertex_shader_object *vertex_shader; } device;\n' + code += '\n'.join(function(renderer, n) for n in ('vertex_shader_get', 'draw_program_get')) + # Take the integration blocks verbatim, including their platform and + # activation guards. The rest of prepare_draw concerns stock GPU state. + init = function(renderer, 'program_get') + init = init[init.index('#ifndef HALO_ANDROID\n\tentry->plasma_model_slots'):] + init = init[:init.index('\n\tfor (stage =')] + draw = function(renderer, 'prepare_draw') + draw = draw[draw.index('#ifndef HALO_ANDROID\n\tif (plasma_mask &&'):] + draw = draw[:draw.index('\n\t/* the lights of a draw')] + code += '\nstatic void initialize(struct program_entry *entry, BOOL plasma_model) {\n' + init + '\n}\n' + code += '\nstatic void bind_model(struct program_entry *entry, unsigned int plasma_mask) {\n' + draw + '\n}\n' + if fault: + code = mutated(code, *fault) + return build('dynamic_shader_isolation', (('under_test.inc', code),)) + + +@pytest.mark.parametrize('android', [False, True]) +@pytest.mark.parametrize('case', ['toggle', 'failure', 'unmarked', 'gpu']) +def test_isolation(case, android): + status, output = run(executable(android), case) + assert status == 0, output + + +@pytest.mark.parametrize('fault,case', [ + (('plasma_mask && program->plasma_model', 'program->plasma_model'), 'toggle'), + (('failed = &program->plasma_lighting_failed;', 'failed = &program->lighting_failed;'), 'failure'), + (('if (plasma_model)\n\t{\n\t\tentry->plasma_model_slots', 'if (TRUE)\n\t{\n\t\tentry->plasma_model_slots'), 'gpu'), + (('if (plasma_mask && entry->plasma_model_slots >= 0)', 'if (entry->plasma_model_slots >= 0)'), 'gpu'), +]) +def test_negative_control(fault, case): + status, output = run(executable(fault=fault), case) + assert status == CHECK_FAILED, output diff --git a/tools/harness/tests/test_elevator_correction.py b/tools/harness/tests/test_elevator_correction.py index 55aba79954..54ba7fc544 100644 --- a/tools/harness/tests/test_elevator_correction.py +++ b/tools/harness/tests/test_elevator_correction.py @@ -12,7 +12,7 @@ from test_vehicle_riding import engine, without_includes SOURCE = "port/linux/game/network_distributed.c" -CASES = ["100ms", "200ms", "100ms-up", "200ms-up", "jump", "walk-off", "other-elevator", "teleport", "unpredicted", "no-history", "on-foot", "far"] +CASES = ["100ms", "200ms", "100ms-up", "200ms-up", "jump", "walk-off", "other-elevator", "teleport", "unpredicted", "no-history", "on-foot", "far", "scripted"] # a fault in distributed_correct_own_unit and the case that must catch it diff --git a/tools/harness/tests/test_elevator_prediction.py b/tools/harness/tests/test_elevator_prediction.py index 633f638d38..efe092f273 100644 --- a/tools/harness/tests/test_elevator_prediction.py +++ b/tools/harness/tests/test_elevator_prediction.py @@ -13,12 +13,13 @@ SOURCE = "port/linux/game/network_distributed.c" CASES = ["riding-up", "elevator-at-rest", "on-foot", "jump-at-rest", "left-platform", - "reversals-100ms", "reversals-200ms"] -FUNCTIONS = ("distributed_supported_elevator", "distributed_riding_elevator", "distributed_air_part_vehicle", - "distributed_take_prediction") + "reversals-100ms", "reversals-200ms", "mcc-host-movement"] +FUNCTIONS = ("distributed_supported_elevator", "distributed_riding_elevator", "distributed_air_part_vehicle", "distributed_take_prediction") # a fault in network_distributed.c, the function it is in, and the case that must catch it NEGATIVE_CONTROLS = { + "mcc-client-position-taken": (("if (mcc_script_effects_host_movement())", "if (0)"), + "distributed_take_prediction", "mcc-host-movement"), "height-taken-riding": (("if (distributed_riding_elevator(unit_index))\n\t\tposition.z", "if (0)\n\t\tposition.z"), "distributed_take_prediction", "riding-up"), "stopped-floor-not-protected": (("distributed_supported_elevator(unit_index) != NONE", diff --git a/tools/harness/tests/test_enhanced_controller.py b/tools/harness/tests/test_enhanced_controller.py new file mode 100644 index 0000000000..558f6c0200 --- /dev/null +++ b/tools/harness/tests/test_enhanced_controller.py @@ -0,0 +1,30 @@ +"""Real goal arbitration across ticks, objective feedback and search fairness.""" +import sys +from pathlib import Path +import pytest +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import read, function, build, run, mutated + +def implementation(): + source = read("port/linux/game/enhanced_bots_controller.c") + code = "\n".join(function(source, name) for name in ( + "bots_distance2d", "bots_distance3d", "bots_set_goal", "bots_goal_failed", "bots_choose_goal", "bots_search_turn")) + return code + function(read("port/linux/game/enhanced_bots.c"), "enhanced_bots_capture_approach") + +@pytest.mark.parametrize("case", ["seat", "objectives", "capture", "fairness"]) +def test_controller(case): + status, output = run(build("enhanced_controller", (("under_test.inc", implementation()),)), case) + assert status == 0, output + +def test_seat_commitment_regression_detected(): + code = mutated(implementation(), "else if (bots_vehicle_seeking(index))", "else if (FALSE)") + status, output = run(build("enhanced_controller", (("under_test.inc", code),)), "seat") + assert status == 1, output + + +def test_capture_does_not_cut_through_wall(): + code = mutated(implementation(), + "if (collision_test_vector(collision_flags, &start, &delta, player->unit_index, &hit)) return FALSE;", + "if (collision_test_vector(collision_flags, &start, &delta, player->unit_index, &hit) && FALSE) return FALSE;") + status, output = run(build("enhanced_controller", (("under_test.inc", code),)), "capture") + assert status == 1 and "base wall" in output, output diff --git a/tools/harness/tests/test_enhanced_flight.py b/tools/harness/tests/test_enhanced_flight.py new file mode 100644 index 0000000000..0c2212b221 --- /dev/null +++ b/tools/harness/tests/test_enhanced_flight.py @@ -0,0 +1,13 @@ +"""Exercise the actual bounded aircraft planner against geometric obstacles.""" +import sys +from pathlib import Path +import pytest +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import read, build, run + +@pytest.mark.parametrize("case", ["clear", "wall", "sealed", "landing", "takeoff", "clearance", "retarget", "braking", "shape", "partial", "recovery", "mass_budget", "vertical", "forward_flight", "fighter_landing", "dynamic_hull", "terrain", "hold", "winged", "lookahead", "climb_progress", "landing_site", "low_approach"]) +def test_flight(case): + source = read("port/linux/game/enhanced_bots_flight.c") + code = source[source.index("enum\n{"):] + status, output = run(build("enhanced_flight", (("under_test.inc", code),)), case) + assert status == 0, output diff --git a/tools/harness/tests/test_enhanced_objective_policy.py b/tools/harness/tests/test_enhanced_objective_policy.py new file mode 100644 index 0000000000..bff453b458 --- /dev/null +++ b/tools/harness/tests/test_enhanced_objective_policy.py @@ -0,0 +1,11 @@ +import sys +from pathlib import Path +import pytest +sys.path.insert(0,str(Path(__file__).resolve().parents[2])) +from harness import read,function,build,run +@pytest.mark.parametrize("case",["attacker","defender","carrier","hill"]) +def test_objective_policy(case): + source=read("port/linux/game/enhanced_bots.c") + code=function(source,"enhanced_bots_goal")+function(source,"enhanced_bots_advancing") + status,output=run(build("enhanced_objective_policy",(("under_test.inc",code),)),case) + assert status==0,output diff --git a/tools/harness/tests/test_first_person_interpolation.py b/tools/harness/tests/test_first_person_interpolation.py index 7740eb817e..6f806b0b38 100644 --- a/tools/harness/tests/test_first_person_interpolation.py +++ b/tools/harness/tests/test_first_person_interpolation.py @@ -1,66 +1,76 @@ -"""The first-person weapon drawn between ticks: its own animations blended however far they move in a tick (a -rocket launcher's melee), another weapon's or skeleton's pose never blended to, and a node's half turn snapped.""" +"""Exercise the production first-person snapshot and matrix blending code.""" +from pathlib import Path +import os import re +import shutil +import subprocess import sys -from pathlib import Path import pytest sys.path.insert(0, str(Path(__file__).resolve().parents[2])) -from harness import CHECK_FAILED, build, function, mutated, read, run, structure - -CASES = ['melee', 'weapon', 'graph', 'within a tick', 'gap', 'not a number', 'half turn', 'large turn'] -CONTROLS = [ - # the distance limit the weapon's identity replaced - ('<= REAL_MAX))', '<= 0.25f * 0.25f))', 'melee'), - ('first_person->node_count == node_count &&\n\t\t\tfirst_person->weapon_index == weapon_index &&', - 'first_person->node_count == node_count &&', 'weapon'), - ('first_person->weapon_index == weapon_index &&\n\t\t\tfirst_person->animation_graph_index == animation_graph_index;', - 'first_person->weapon_index == weapon_index;', 'graph'), - ('if (first_person->tick != interpolation_tick ||\n\t\tfirst_person->weapon_index != weapon_index ||\n' - '\t\tfirst_person->animation_graph_index != animation_graph_index)', - 'if (first_person->tick != interpolation_tick)', 'within a tick'), - ('first_person->has_previous = first_person->tick == interpolation_tick - 1 &&', - 'first_person->has_previous = ', 'gap'), - ('< FIRST_PERSON_HALF_TURN_COSINE)', '< 0.0f)', 'half turn'), -] - - -def generated(fault=None): - source = read('port/linux/game/render_interpolation.c') - maths = read('source/math/real_math.h') - matrices = read('source/math/matrix_math.c') - config = '\n'.join([ - '#define MAXIMUM_LOCAL_PLAYERS 4', - re.search(r'^#define MAXIMUM_INTERPOLATED_NODES .*', source, re.M).group(), - re.search(r'^#define FIRST_PERSON_HALF_TURN_COSINE .*', source, re.M).group(), - re.search(r'^#define REAL_MAX .*', maths, re.M).group(), - structure(maths, 'real_matrix4x3'), - 'typedef struct real_matrix4x3 real_matrix4x3;', - ]) + '\n' - code = '\n'.join( - [function(matrices, name) for name in - ['matrix4x3_inverse', 'matrix4x3_rotation_from_vectors', 'matrix4x3_from_point_and_vectors', - 'matrix4x3_multiply']] + - [structure(source, name) for name in - ['interpolation_quaternion', 'interpolation_rotation', 'interpolated_first_person']] + - ['static struct interpolated_first_person interpolated_first_person[MAXIMUM_LOCAL_PLAYERS];'] + - [function(source, name) for name in - ['lerp', 'point_lerp', 'vector_length', 'basis_is_rotation', 'quaternion_from_basis', - 'basis_from_quaternion', 'rotation_from_matrix', 'matrix_blend_rotations', 'distance_squared', - 'render_interpolation_first_person']]) - if fault: - code = mutated(code, *fault) - return (('config.inc', config), ('under_test.inc', code)) - - -@pytest.mark.parametrize('case', CASES) -def test_case(case): - status, output = run(build('first_person_interpolation', generated()), case) - assert status == 0, output - - -@pytest.mark.parametrize('before,after,case', CONTROLS) -def test_negative_control(before, after, case): - status, output = run(build('first_person_interpolation', generated((before, after))), case) - assert status == CHECK_FAILED, output +from harness import function, mutated, read, structure + + +CASES = ["fast-motion", "weapon-change", "graph-change", "same-tick-change", + "node-count", "gap", "disabled", "reset", "players", "camera", "invalid", "capacity", "missing", + "chamber-reset", "large-rotation"] + + +def generated(): + source = read("port/linux/game/render_interpolation.c") + math = read("source/math/matrix_math.c") + matrices = "\n".join(function(math, name) for name in + ["matrix4x3_inverse", "matrix4x3_rotation_from_vectors", + "matrix4x3_from_point_and_vectors", "matrix4x3_multiply"]) + types = "\n".join(structure(source, name) for name in + ["interpolation_quaternion", "interpolation_rotation", + "interpolated_first_person"]) + blend = "\n".join(function(source, name) for name in + ["lerp", "point_lerp", "vector_length", "basis_is_rotation", + "quaternion_from_basis", "basis_from_quaternion", + "rotation_from_matrix", "matrix_blend_rotations", "distance_squared"]) + # Reset's object/camera storage is stubbed; the first-person reset runs intact. + cutoff = re.search(r"^#define FIRST_PERSON_HALF_TURN_COSINE .*", source, re.M).group(0) + return cutoff + "\n" + matrices + "\n" + types + "\n" + blend + "\n" + ( + "static struct interpolated_first_person interpolated_first_person[MAXIMUM_LOCAL_PLAYERS];\n" + ) + function(source, "render_interpolation_reset") + "\n" + function(source, "render_interpolation_first_person") + + +def compile_fixture(work, source): + compiler = shutil.which(os.environ.get("CC", "clang")) + if not compiler: + pytest.skip("clang required") + (work / "under_test.inc").write_text(source) + fixture = Path(__file__).with_name("first_person_interpolation.c") + binary = work / ("test.exe" if sys.platform == "win32" else "test") + flags = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld"] if sys.platform == "win32" else ["-m32", "-lm"] + subprocess.run([compiler, "-std=gnu89", "-O2", "-Wall", "-Wextra", "-Werror", + "-Wno-unused-function", "-I", str(work), "-I", str(fixture.parent.parent / "include"), + str(fixture), *flags, "-o", str(binary)], check=True) + return binary + + +@pytest.fixture(scope="module") +def executable(tmp_path_factory): + return compile_fixture(tmp_path_factory.mktemp("first-person-interpolation"), generated()) + + +@pytest.mark.parametrize("case", CASES) +def test_first_person_interpolation(executable, case): + result = subprocess.run([str(executable), case], capture_output=True, text=True, timeout=10) + assert result.returncode == 0, result.stdout + result.stderr + + +def test_old_distance_cutoff_fails(tmp_path): + source = mutated(generated(), "REAL_MAX))", "0.25f * 0.25f))") + binary = compile_fixture(tmp_path, source) + result = subprocess.run([str(binary), "fast-motion"], capture_output=True, text=True, timeout=10) + assert result.returncode == 1 and "position" in result.stderr, result.stdout + result.stderr + + +def test_blending_chamber_reset_fails(tmp_path): + source = mutated(generated(), "< FIRST_PERSON_HALF_TURN_COSINE", "< 0.0f") + binary = compile_fixture(tmp_path, source) + result = subprocess.run([str(binary), "chamber-reset"], capture_output=True, text=True, timeout=10) + assert result.returncode == 1 and "half-turn" in result.stderr, result.stdout + result.stderr diff --git a/tools/harness/tests/test_first_person_legs.py b/tools/harness/tests/test_first_person_legs.py new file mode 100644 index 0000000000..324e76f048 --- /dev/null +++ b/tools/harness/tests/test_first_person_legs.py @@ -0,0 +1,93 @@ +"""The local player's own legs in first person (port/linux/game/first_person_legs.c, display.first_person_legs): the +legs found from the biped's pelvis and head, the intact pose guarded by geometry preparation, only the player's own +living biped on foot in first person, a pose per local player, and the legs found forgotten with a map.""" +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import CHECK_FAILED, build, enum_with, function, mutated, read, run + +CASES = ["off", "legs", "setback", "turn", "pivot", "interpolated", "fov-shape", "geometry-failure", "geometry-reset", + "pitch-stable", "who", "unusable", "loops", "split", "reset"] +CONTROLS = { + # a separate root makes the hips orbit as the view turns + "root-pivot": (("pivot = nodes[definition->biped.runtime_pelvis_node_index].position;", + "pivot = nodes[0].position;"), "pivot"), + # interpolation must move the pivot with the drawn pelvis, not its tick pose + "tick-pivot": (("pivot = nodes[definition->biped.runtime_pelvis_node_index].position;", + "pivot = ((real_matrix4x3 const *)object_header_block_get(object_index, " + "&object->object.node_matrices))[definition->biped.runtime_pelvis_node_index].position;"), + "interpolated"), + # the setting ignored + "always-on": (("if (!first_person_legs_enabled() || local_player_index", "if (local_player_index"), "off"), + "collapsed-again": (("pose[index] = nodes[index];", "pose[index] = nodes[index]; pose[index].scale *= 0.001f;"), "legs"), + "head-retained": (("node_index != head_index &&", "TRUE &&"), "legs"), + "geometry-failure-ignored": (("model, legs->omitted, legs->lower) ? 1 : -1", "model, legs->omitted, legs->lower) ? 1 : 1"), "geometry-failure"), + "geometry-not-reset": (("first_person_legs_geometry_reset();", ""), "geometry-reset"), + # the view's heading from its forward alone: none looking straight down + "forward-only-heading": (("heading->i = forward->i - forward->k * up->i;", "heading->i = forward->i;"), "setback"), + # the body's heading from its first node (the pelvis's axis, up the spine) + "first-node-facing": (("first_person_legs_body_heading(&object->object.forward,", + "first_person_legs_body_heading(&nodes[0].forward,"), "turn"), + # not turned to the view: the legs lag its turns, and after a jump's half turn stand in front of it + "not-turned": (("cosine = dot_product3d(&body, &view);\n\t\tsine = body.i * view.j - body.j * view.i;", ""), "turn"), + # set back along the body's facing, not the view's + "body-set-back": (("back.i = -view.i;\n\tback.j = -view.j;", + "back.i = -object->object.forward.i;\n\tback.j = -object->object.forward.j;"), "turn"), + # the bones' axes left as they were + "axes-unturned": (("first_person_legs_turn(&pose[index].forward, cosine, sine);", ""), "turn"), + # the body's facing from the tick's frame alone, a tick behind the pose drawn + "tick-facing": (("(real_matrix4x3 const *)object_header_block_get(object_index, &object->object.node_matrices),", + "&nodes[0],"), "interpolated"), + # in third person too + "third-person": (("director_get_perspective(local_player_index) != _director_perspective_first_person", "FALSE"), + "who"), + # a dead body's legs + "dead-drawn": (("TEST_FLAG(object->object.damage_flags, _object_dead_bit) ||", ""), "who"), + # found again (and said again) each frame + "not-cached": (("if (first_person_legs_models[index].definition_index == definition_index)\n" + "\t\t\treturn &first_person_legs_models[index];", ""), "unusable"), + # one pose for every view + "one-pose": (("pose = first_person_legs_matrices[local_player_index];", "pose = first_person_legs_matrices[0];"), + "split"), + # the last map's legs kept + "no-reset": (("first_person_legs_models[index].definition_index = NONE;", ";"), "reset"), +} + + +def define(source, name): + line = next((line for line in source.splitlines() if line.startswith(f"#define {name} ")), None) + if line is None: + raise LookupError(f"#define not found in the sources: {name}") + return line + + +def generated(control=None): + source = read("port/linux/game/first_person_legs.c") + globals_ = source[source.index("/* ---------- globals */"):source.index("/* ---------- private code */")] + code = "\n".join([enum_with(source, "FIRST_PERSON_LEGS_MODELS"), + define(source, "FIRST_PERSON_LEGS_SET_BACK"), + "void first_person_legs_reset(void);", globals_] + + [function(source, name) for name in ["first_person_legs_enabled", "first_person_legs_below", + "first_person_legs_find", "first_person_legs_model_get", + "first_person_legs_reset", "first_person_legs_view_heading", + "first_person_legs_body_heading", + "first_person_legs_turn", + "first_person_legs_node_matrices"]]) + if control: + code = mutated(code, *CONTROLS[control][0]) + return (("under_test.inc", code),) + + +@pytest.mark.parametrize("case", CASES) +def test_case(case): + status, output = run(build("first_person_legs", generated()), case) + assert status == 0, output + + +@pytest.mark.parametrize("control", CONTROLS) +def test_negative_control(control): + status, output = run(build("first_person_legs", generated(control)), CONTROLS[control][1]) + assert status == CHECK_FAILED, f"{control} escaped its check: {output}" diff --git a/tools/harness/tests/test_first_person_legs_geometry.py b/tools/harness/tests/test_first_person_legs_geometry.py new file mode 100644 index 0000000000..e120c935e6 --- /dev/null +++ b/tools/harness/tests/test_first_person_legs_geometry.py @@ -0,0 +1,45 @@ +"""Exercise the actual private mesh builder and animated surface clearance.""" +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import CHECK_FAILED, build, mutated, read, run + +CASES = ["mesh", "strip", "weights", "palette", "malformed", "failure", + "lifecycle", "boundary", "clearance", "invalid-view"] +CONTROLS = { + "retain-head": (("node >= node_count || upper[node]", "node >= node_count"), "mesh"), + "strip-winding": (("(triangle & 1) ? b : a", "FALSE ? b : a"), "strip"), + "ignore-second-weight": (("index < 2", "index < 1"), "weights"), + "ignore-cut": (("edge[vertex] || !leg_only", "!leg_only"), "boundary"), + "ignore-torso": (("edge[vertex] || !leg_only", "edge[vertex] || (leg_only && FALSE)"), "boundary"), + "bone-instead-of-surface": (("&boundary->local[0], &a", "&origin, &a"), "clearance"), + "ignore-animation": (("&nodes[boundary->nodes[0]]", "&identity"), "clearance"), + "ignore-weight": (("a.z * boundary->weight + b.z * (1.f - boundary->weight)", "a.z"), "clearance"), + "no-clearance": (("result = MAX(result, required - current);", ";"), "clearance"), + "no-release": (("rasterizer_triangle_buffer_delete(&first_person_legs_parts[index].triangles);", ";"), "lifecycle"), +} + + +def generated(control=None): + source = read("port/linux/game/first_person_legs_geometry.c") + # The complete production implementation, with only its engine includes + # replaced by the fixture's API/type declarations. + source = "\n".join(line for line in source.splitlines() if not line.startswith("#include")) + if control: + source = mutated(source, *CONTROLS[control][0]) + return (("under_test.inc", source),) + + +@pytest.mark.parametrize("case", CASES) +def test_case(case): + status, output = run(build("first_person_legs_geometry", generated()), case) + assert status == 0, output + + +@pytest.mark.parametrize("control", CONTROLS) +def test_negative_control(control): + status, output = run(build("first_person_legs_geometry", generated(control)), CONTROLS[control][1]) + assert status == CHECK_FAILED, f"{control} escaped its check: {output}" diff --git a/tools/harness/tests/test_fragment_source_cache.py b/tools/harness/tests/test_fragment_source_cache.py new file mode 100644 index 0000000000..ccc2844524 --- /dev/null +++ b/tools/harness/tests/test_fragment_source_cache.py @@ -0,0 +1,38 @@ +"""Compile the real full-key/source cache against a counted shader compiler.""" +import pytest +from tools.harness import CHECK_FAILED, build, function, mutated, read, run, structure + + +def executable(collision=False, fault=None): + source = read('port/linux/src/d3d8_gl.c') + code = '\n'.join(structure(source, name) for name in ('fragment_entry', 'fragment_source_entry')) + code += '\n#define FRAGMENT_BUCKETS 1024\n' + code += 'static struct fragment_entry *fragment_buckets[FRAGMENT_BUCKETS];\n' + code += 'static struct fragment_source_entry *fragment_source_buckets[FRAGMENT_BUCKETS];\n' + code += 'static unsigned long long *shader_hashes;\nstatic GLuint shader_hashes_size;\n' + code += '\n'.join(function(source, name) for name in ( + 'source_hash', 'shader_hash_set', 'hash_words', 'words_equal', + 'fragment_source_hash', 'fragment_source_get', 'fragment_shader_get')) + if collision: + hashing = function(source, 'fragment_source_hash') + code = code.replace(hashing, hashing.replace('return hash;', '(void)hash; return 0;')) + if fault: + code = mutated(code, *fault) + return build('fragment_source_cache', (('under_test.inc', code),)) + + +@pytest.mark.parametrize('collision', [False, True]) +@pytest.mark.parametrize('case', ['reuse', 'distinct', 'failure', 'allocation', 'recent', 'prefix']) +def test_cache(case, collision): + status, output = run(executable(collision), case) + assert status == 0, output + + +@pytest.mark.parametrize('fault,case', [ + (('entry->hash == hash && !strcmp(entry->source, source)', 'entry->hash == hash'), 'distinct'), + (('entry->hash == hash && !strcmp(entry->source, source)', 'FALSE'), 'reuse'), + (('shader_hash_set(shader, source);', '(void)0;'), 'reuse'), +]) +def test_negative_control(fault, case): + status, output = run(executable(True, fault), case) + assert status == CHECK_FAILED, output diff --git a/tools/harness/tests/test_game_time_sync.py b/tools/harness/tests/test_game_time_sync.py new file mode 100644 index 0000000000..e2cc6b020d --- /dev/null +++ b/tools/harness/tests/test_game_time_sync.py @@ -0,0 +1,80 @@ +"""Actual frame processing catches small reliable-host clock lag without jumps.""" +from pathlib import Path +import re +import sys + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import build, constant, enum_with, function, mutated, read, run, structure, CHECK_FAILED + + +FUNCTIONS = ( + 'game_time_initialize', 'game_time_initialize_for_new_map', 'game_time_dispose_from_old_map', + 'game_time_end', 'game_time_set_distributed', 'game_time_synchronize_distributed', + 'game_time_get', 'game_time_get_paused', 'game_time_set_paused', + 'game_time_get_speed', 'game_time_held', 'game_time_menu_scene', 'game_time_start', 'game_time_update', +) + + +def generated(fault=None): + time_source = read('source/game/game_time.c') + config = '\n'.join(( + enum_with(read('source/game/game.h'), '_game_connection_local'), + enum_with(read('source/scenario/scenario_definitions.h'), '_scenario_type_main_menu'), + f'#define TICKS_PER_SECOND {constant(read("source/cseries/cseries.h"), "TICKS_PER_SECOND")}', + f'#define SOME_LARGE_NUMBER_OF_TICKS {constant(time_source, "SOME_LARGE_NUMBER_OF_TICKS")}', + structure(time_source, 'game_time_globals_struct'), + )) + # The target is transient engine state, not a field of the saved clock. + transient = re.findall(r'^static long game_time_distributed_target\s*=\s*[^;]+;', time_source, re.M) + assert len(transient) == 1, 'The saved clock fixture needs its actual transient target declaration' + functions = {name:function(time_source, name) for name in FUNCTIONS} + functions['network_game_client_handle_game_update'] = function( + read('source/networking/network_client_manager.c'), 'network_game_client_handle_game_update') + if fault: + name, before, after = fault + functions[name] = mutated(functions[name], before, after) + source = '\n'.join(transient + list(functions.values())) + return (('config.inc', config), ('under_test.inc', source)) + + +CASES = ( + 'lag-5', 'lag-6', 'lag-7', 'lag-8', 'lag-30', 'scaled-convergence', + 'nominal', 'fraction', 'work-budget', 'target-bound', 'repeat-target', + 'stale-target', 'sub-tick', 'no-target', 'client-ahead', 'held', 'pause', + 'mcc-rate-changes', 'menu', 'local', 'host', 'initial-sync', 'large-stall', + 'invalid-times', 'lifecycle-new-map', 'lifecycle-dispose', 'lifecycle-end', + 'lifecycle-set', 'invalid-targets', 'setter-local', 'setter-host', + 'setter-menu', 'setter-inactive', 'setter-uninitialized', 'negative-clock', + 'lifecycle-initialize', 'initialize-start', +) + + +@pytest.mark.parametrize('case', CASES) +def test_frame_clock(case): + status, output = run(build('game_time_sync', generated()), case) + assert status == 0, output + + +@pytest.mark.parametrize('fault,case', ( + (('network_game_client_handle_game_update', + 'game_time_synchronize_distributed(message_packet->game_time);', '(void)message_packet;'), 'lag-7'), + (('game_time_update', 'ticks_elapsed += MIN(extra_ticks, TICKS_PER_SECOND - ticks_elapsed);', + '(void)extra_ticks;'), 'lag-8'), + (('game_time_update', 'ticks_elapsed += MIN(extra_ticks, TICKS_PER_SECOND - ticks_elapsed);', + 'game_time_set_distributed(game_time_distributed_target);'), 'lag-7'), + (('game_time_update', 'MIN(ticks_elapsed, ticks_behind - ticks_elapsed)', + '(ticks_behind - ticks_elapsed)'), 'lag-8'), + (('game_time_update', 'MIN(extra_ticks, TICKS_PER_SECOND - ticks_elapsed)', + 'extra_ticks'), 'work-budget'), + (('game_time_update', '!game_time_menu_scene() &&', 'TRUE &&'), 'menu'), + (('game_time_update', 'game_time_globals->local_time >= 0 &&', 'TRUE &&'), 'negative-clock'), + (('game_time_synchronize_distributed', 'time > 0x3FFFFFFF', 'FALSE'), 'invalid-targets'), + (('game_time_synchronize_distributed', 'game_time_distributed_target = time;', + '{ game_time_distributed_target = time; game_time_globals->leftover_dt = 0.f; }'), 'fraction'), + (('game_time_initialize_for_new_map', 'game_time_distributed_target = NONE;', '(void)0;'), 'lifecycle-new-map'), +)) +def test_fault_is_detected(fault, case): + status, output = run(build('game_time_sync', generated(fault)), case) + assert status == CHECK_FAILED, output diff --git a/tools/harness/tests/test_glow_endpoint.py b/tools/harness/tests/test_glow_endpoint.py new file mode 100644 index 0000000000..25d6f08314 --- /dev/null +++ b/tools/harness/tests/test_glow_endpoint.py @@ -0,0 +1,28 @@ +"""Original glow interval lookup accepts the endpoint its particle updates admit.""" +import sys +from pathlib import Path +import pytest +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import read, function, build, run, mutated + + +def implementation(): + code = function(read("source/objects/widgets/glow.c"), "get_particle_world_position") + start = code.index("\tfor (marker_index = 0;") + end = code.index("\n", code.index("\tparticle->parent_marker_index =")) + return ("static short marker_at(struct glow_datum *glow, struct glow_particle *particle)\n" + "{ short marker_index;\n" + code[start:end] + "\nreturn particle->parent_marker_index; }\n") + + +@pytest.mark.parametrize("case", ["endpoint", "interior", "invalid"]) +def test_glow_interval(case): + status, output = run(build("glow_endpoint", (("under_test.inc", implementation()),)), case) + assert status == (1 if case == "invalid" else 0), output + if case == "invalid": + assert "marker interval missing" in output, output + + +def test_original_endpoint_defect_is_detected(): + code = mutated(implementation(), "marker_index == glow->number_of_markers - 2", "FALSE") + status, output = run(build("glow_endpoint", (("under_test.inc", code),)), "endpoint") + assert status == 1 and "marker interval missing" in output, output diff --git a/tools/harness/tests/test_lighting_config.py b/tools/harness/tests/test_lighting_config.py new file mode 100644 index 0000000000..46211d4cf0 --- /dev/null +++ b/tools/harness/tests/test_lighting_config.py @@ -0,0 +1,12 @@ +"""Lighting preference cache observes settings changes without caching policy.""" +import re +import sys +from pathlib import Path +sys.path.insert(0,str(Path(__file__).resolve().parents[2])) +from harness import build,read,run + + +def test_lighting_preferences_refresh_on_change(): + code=re.sub(r'^#include.*$','',read('port/linux/game/lighting_config.c'),flags=re.M) + status,output=run(build('lighting_config',(('under_test.inc',code),)),'settings') + assert status==0,output diff --git a/tools/harness/tests/test_lighting_menu.py b/tools/harness/tests/test_lighting_menu.py new file mode 100644 index 0000000000..3287a7c9ca --- /dev/null +++ b/tools/harness/tests/test_lighting_menu.py @@ -0,0 +1,16 @@ +"""Grouped ON/OFF controls only write on Save; migration is tested separately.""" +import re +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import build, read, run, function, structure + + +def test_groups(): + source = re.sub(r'^#include.*$', '', read('port/linux/game/lighting_menu.c'), flags=re.M) + menus = read('port/linux/game/menu_functions.c') + names = ('text_is_number', 'spinner_item', 'setting_value_index', 'setting_text', 'setting_write', 'setting_load', 'setting_save', 'setting_changed_save', 'setting_default_show') + source += '\n' + '\n'.join(function(menus, name) for name in names) + status, output = run(build('lighting_menu', (('under_test_types.inc', structure(menus, 'pc_menu_setting')), ('under_test.inc', source))), 'groups') + assert status == 0, output diff --git a/tools/harness/tests/test_lighting_migration.py b/tools/harness/tests/test_lighting_migration.py new file mode 100644 index 0000000000..9f521f7f7e --- /dev/null +++ b/tools/harness/tests/test_lighting_migration.py @@ -0,0 +1,14 @@ +"""Run the lighting migration against the production TOML parser.""" +import sys +from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import build, read, run + + +def test_saved_lighting_reset_once(): + status, output = run(build('lighting_migration', ( + ('tomlc17.h', read('port/third_party/tomlc17/tomlc17.h')), + ('toml.inc', read('port/third_party/tomlc17/tomlc17.c')), + ('under_test.inc', read('port/linux/src/lighting_settings_migration.inl')), + )), 'migration') + assert status == 0, output diff --git a/tools/harness/tests/test_lightning_tick_shape.py b/tools/harness/tests/test_lightning_tick_shape.py index a250597769..bae20caae3 100644 --- a/tools/harness/tests/test_lightning_tick_shape.py +++ b/tools/harness/tests/test_lightning_tick_shape.py @@ -12,9 +12,10 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[2])) from harness import CHECK_FAILED, build, constant, enum_with, function, mutated, read, run, structure # noqa: E402 -CASES = ["same-shape-in-a-tick", "follows-its-markers", "seed-left-as-found", "windows-apart", "new-lightning"] -FUNCTIONS = ("lightning_offset_marker_position", "lightnings_initialize_for_new_map", "lightning_new", - "lightning_submit") +CASES = ["same-shape-in-a-tick", "follows-its-markers", "seed-left-as-found", "windows-apart", "new-lightning", + "tick-zero", "map-reset", "checkpoint-load", "multiple-lightnings", "failed-redraw", "failed-first-draw"] +FUNCTIONS = ("lightning_offset_marker_position", "lightnings_reset_render_state", "lightnings_initialize_for_new_map", + "lightning_new", "lightning_submit") # a fault in the code and the case that must catch it NEGATIVE_CONTROLS = { @@ -29,6 +30,7 @@ "windows-apart"), # a new lightning draws the one before it's bolt for the rest of the tick "seed-of-the-one-before": (("sizeof(lightning_tick_seeds[0]));", "0);"), "new-lightning"), + "reset-left-stale": (("csmemset(lightning_tick_seeds, 0, sizeof(lightning_tick_seeds));", ""), "map-reset"), } @@ -54,7 +56,16 @@ def generated(fault=None): code = "\n".join(function(source, name) for name in FUNCTIONS) + "\n" if fault: code = mutated(code, *fault) - return (("config.inc", config), ("under_test.inc", code)) + # Execute the engine's actual post-load callback table and dispatcher; + # only unrelated subsystems are stubbed in this renderer-only world. + state = read("source/saved games/game_state.c") + callbacks = re.search(r"static game_state_after_load_proc after_load_procs\[\] =\s*\{.*?\};", state, re.S).group(0) + names = re.findall(r"^\s*(\w+)\s*,?\s*$", callbacks, re.M) + after_load = "typedef void (*game_state_after_load_proc)(void);\n#define NUMBEROF(a) (sizeof(a) / sizeof((a)[0]))\n" + after_load += "\n".join(f"static void {name}(void) {{ }}" for name in names + if name != "lightnings_reset_render_state") + after_load += "\n" + callbacks + "\n" + function(state, "game_state_call_after_load_procs") + return (("config.inc", config), ("under_test.inc", code), ("after_load.inc", after_load)) @pytest.mark.parametrize("case", CASES) @@ -68,3 +79,10 @@ def test_negative_control(control): fault, case = NEGATIVE_CONTROLS[control] status, output = run(build("lightning_tick_shape", generated(fault)), case) assert status == CHECK_FAILED, f"the lightning with a fault ({control}) passed '{case}': the test cannot see it" + + +def test_checkpoint_hook_negative_control(): + includes = tuple((name, mutated(text, "\tlightnings_reset_render_state,", "")) + if name == "after_load.inc" else (name, text) for name, text in generated()) + status, output = run(build("lightning_tick_shape", includes), "checkpoint-load") + assert status == CHECK_FAILED, output diff --git a/tools/harness/tests/test_lobby_countdown.py b/tools/harness/tests/test_lobby_countdown.py index b2f26b3625..42403d1847 100644 --- a/tools/harness/tests/test_lobby_countdown.py +++ b/tools/harness/tests/test_lobby_countdown.py @@ -18,8 +18,11 @@ "two-machines-team-game-needs-both-teams", "playerless-machine-keeps-countdown", "split-screen-team-game-one-team", "dedicated-one-team-starts", "dedicated-both-teams-waits", "dedicated-below-minimum-waits", "dedicated-minimum-clamped", "dedicated-director-refuses", + "one-bot-start", "31-bots-start", "63-bots-start", "split-screen-bots-start", + "bots-team-rule", "bots-minimum-rule", "bots-paused", "bots-no-machine", + "bots-existing-countdown", "bots-second-machine", "bots-ownership-lifecycle", "dedicated-start-now-five-seconds", - "split-screen-team-game-one-team", "host-start-now-starts", "host-start-now-ends-countdown", + "host-start-now-starts", "host-start-now-ends-countdown", "split-screen-host-start-now-starts", "client-start-now-five-seconds", "host-start-now-team-game-needs-both-teams", ] FUNCTIONS = ( @@ -39,6 +42,10 @@ # a fault in network_server_manager.c, the function it is in, and the case that must catch it NEGATIVE_CONTROLS = { + "bot-start-hook-missing": ( + ("bots_lobby_can_start(&server->game)", "FALSE"), + "network_game_server_update_countdown", "31-bots-start", + ), "one-player-only": ( ("else if ((short)player->machine_index != first_machine_index)", "else"), "server_players_on_one_machine", "split-screen-start-now", @@ -129,7 +136,15 @@ def generated(fault=None, faulty_function=None): config += structure(source, name) + "\n" config += enum_with(read("port/linux/game/server_director.h"), "_server_state_lobby") + "\n" config += "#define MAX(a, b) ((a) > (b) ? (a) : (b))\n" + config += f"#define BOTS_MAXIMUM {constant(read('port/linux/game/bots.h'), 'BOTS_MAXIMUM')}\n" + config += "#define BOTS_FIRST_MACHINE (MAXIMUM_NETWORK_MACHINE_COUNT - BOTS_MAXIMUM)\n" text = "" + network_bots = read("port/linux/game/bots_network.c") + text += "\n".join(re.findall(r"^static long population_.*;", network_bots, re.M)) + "\n" + text += function(read("port/linux/game/bots.c"), "bots_machine_is_bot") + "\n" + for name in ("bots_network_session_begin", "bots_network_session_end", "bots_player_ownership", + "bots_player_owned", "bots_session_allowed", "bots_lobby_can_start"): + text += function(network_bots, name) + "\n" for name in DIRECTOR_FUNCTIONS: code = re.sub(r'(?ai_initialized_for_map)', 'if (TRUE)') + code += adapter + '\n' + if fault == 'legacy-admission': + policy = mutated(policy, 'FALSE, /* ai_deselect:', 'TRUE, /* ai_deselect:') + code += policy + code += function(hs, 'hs_syntax_try_get') + '\n' + code += function(hs, 'hs_syntax_node_check') + '\n' + code += function(hs, 'hs_syntax_node_refusal') + '\n' + code += function(hs, 'hs_expression_changes_no_game') + '\n' + return (('types.inc', types), ('under_test.inc', code)) + + +@pytest.mark.parametrize('case', ['clear', 'inactive', 'already-clear', 'actor-only', 'legacy-policy', 'client-policy']) +def test_mcc_ai_deselect_semantics_and_boundaries(case): + assert run(build('mcc_ai_deselect', generated()), case) == (0, '') + + +@pytest.mark.parametrize('fault,case', [ + ('no-clear', 'clear'), ('ignore-initialization', 'inactive'), ('legacy-admission', 'legacy-policy'), +]) +def test_mcc_ai_deselect_controls_detect_faults(fault, case): + status, output = run(build('mcc_ai_deselect', generated(fault)), case) + assert status == CHECK_FAILED, output diff --git a/tools/harness/tests/test_mcc_mods.py b/tools/harness/tests/test_mcc_mods.py new file mode 100644 index 0000000000..c5ca1bdd54 --- /dev/null +++ b/tools/harness/tests/test_mcc_mods.py @@ -0,0 +1,16 @@ +"""Exercise the production mod lifecycle across map families and failed loads.""" +from tools.harness import build, function, read, run + + +def test_map_transitions(): + source = read("port/linux/game/mods.c") + start = source.index("static struct") + end = source.index("} mods_globals;", start) + len("} mods_globals;") + cache = read("port/linux/game/mcc_cache.c") + code = source[start:end] + "\n" + code += function(cache, "mcc_prefix") + "\n" + function(cache, "mcc_level_name") + "\n" + for name in ("mods_update", "mods_let_go", "mods_tags_loaded", "mods_tags_unloaded", + "mods_reload", "mods_apply", "mods_enable", "mods_map_loaded"): + code += function(source, name) + "\n" + status, output = run(build("mcc_mods", (("under_test.inc", code),)), "transitions") + assert status == 0, output diff --git a/tools/harness/tests/test_mcc_player_indicator.py b/tools/harness/tests/test_mcc_player_indicator.py index f03c34045a..c17a3c06a7 100644 --- a/tools/harness/tests/test_mcc_player_indicator.py +++ b/tools/harness/tests/test_mcc_player_indicator.py @@ -6,6 +6,8 @@ def code(): hud = read("source/interface/hud.c") return "\n".join([ + function(read("port/linux/game/custom_edition_hud_scale.h"), "custom_edition_hud_scale"), + function(read("port/linux/game/custom_edition_hud_draw.c"), "custom_edition_hud_bitmap_scale"), function(read("port/linux/game/mcc_hud_draw.c"), "mcc_hud_bitmap_scale"), function(hud, "hud_draw_friendly_indicator"), function(hud, "hud_draw_player_name"), @@ -25,13 +27,10 @@ def test_indicator_and_name_units(case): @pytest.mark.parametrize("fault", ["arrow", "name"]) def test_missing_scaling_is_detected(fault): source = code() - if fault == "arrow": - source = mutated(source, - "mcc_hud_bitmap_scale(interface_get_tag_index(_interface_bitmap_multiplayer_hud)), /* port: MCC bitmap units */", - "1.0f,") - else: - source = mutated(source, - "y -= (short)(bitmap->registration_point.y *\n\t\t\t\tmcc_hud_bitmap_scale(interface_get_tag_index(_interface_bitmap_multiplayer_hud)));", - "y -= bitmap->registration_point.y;") - status, output = execute(source, "half") + name = "hud_draw_friendly_indicator" if fault == "arrow" else "hud_draw_player_name" + original = function(source, name) + changed = mutated(original, + "mcc_hud_bitmap_scale(interface_get_tag_index(_interface_bitmap_multiplayer_hud))", + "1.0f") + status, output = execute(mutated(source, original, changed), "half") assert status == 1 and "check failed" in output, output diff --git a/tools/harness/tests/test_mcc_script_threads.py b/tools/harness/tests/test_mcc_script_threads.py new file mode 100644 index 0000000000..f1921b0f83 --- /dev/null +++ b/tools/harness/tests/test_mcc_script_threads.py @@ -0,0 +1,78 @@ +"""Real MCC thread storage, frame validation and old checkpoint migration.""" +import re +import os +import struct +import subprocess +import sys +import zlib +from pathlib import Path +import pytest +from tools.harness import read, run, structure, enum_with, function + +ROOT = Path(__file__).resolve().parents[3] + + +@pytest.fixture(scope="module") +def thread_tool(tmp_path_factory): + runtime = read("source/hs/hs_runtime.c") + types = "\n".join(structure(runtime, name) for name in ("hs_stack_frame", "hs_thread_datum")) + types += "\n" + structure(read("source/memory/data.h"), "data_array") + types += "\n" + enum_with(runtime, "_hs_thread_type_script =") + types += "\n" + enum_with(runtime, "HS_THREAD_STACK_SIZE =") + types += "\n" + enum_with(runtime, "_hs_thread_in_function_call_bit =") + checkpoint = read("port/linux/game/mcc_checkpoint.c") + definitions = "\n".join(line for line in checkpoint.splitlines() if line.startswith("#define MCC_CHECKPOINT_")) + definitions += "\n" + read("port/linux/game/mcc_campaign.h") + definitions += "\n" + read("port/linux/game/mcc_object_names.h") + # Headers only contribute the capacity constants; no private implementation is copied. + definitions = "\n".join(line for line in definitions.splitlines() if line.startswith("#define MCC_")) + implementation = re.sub(r'^#include .*$', '', read("port/linux/game/mcc_script_threads.inl"), flags=re.M) + code = definitions + "\n" + function(checkpoint, "mcc_checkpoint_script_storage") + "\n" + implementation + code += "\n" + function(runtime, "hs_stack_push") + "\n" + function(runtime, "hs_stack_allocate") + generated = (("types.inc", types), ("under_test.inc", code)) + work = tmp_path_factory.mktemp("mcc-threads") + for name, text in generated: + (work / name).write_text(text) + binary = work / ("threads.exe" if sys.platform == "win32" else "threads") + zlib_dir = ROOT / "port/third_party/zlib" + result = subprocess.run([os.environ.get("CC", "clang"), "-m32", "-std=gnu89", "-O2", "-Wall", "-Werror", + "-Wno-unused-function", "-D_CRT_SECURE_NO_WARNINGS", "-DZ_PREFIX", "-Dz_errmsg=z_port_errmsg", "-I" + str(work), + "-I" + str(zlib_dir), str(Path(__file__).with_name("mcc_script_threads.c")), + str(zlib_dir / "crc32.c"), "-o", str(binary)], capture_output=True, text=True) + assert result.returncode == 0, result.stderr + return binary + + +@pytest.mark.parametrize("case", ["lifecycle", "capacity", "roundtrip", "migration", "checksum", + "stride", "count", "pointer", "stack", "cycle", "overlap", "result", "size", "root", "other_thread", "bounds", + "unactivated", "missing", "flags", "type", "sleep", "unused_slot"]) +def test_thread_storage(thread_tool, case): + status, output = run(thread_tool, case) + assert status == 0, output + + +@pytest.mark.parametrize("size", ["null", "known", 0, 1, 7, 8, 9, 15, 16, 17, 255, 256, 257, + 32767, 32768, 32769, 1048576, 1054775, 1054776]) +def test_thread_checksum_matches_independent_oracle(thread_tool, size): + data = b"" if size == "null" else b"123456789" if size == "known" else bytes( + (i * 37 + (i >> 8) + 19) & 255 for i in range(size)) + result = subprocess.run([str(thread_tool), "crc", str(size)], capture_output=True, text=True) + assert result.returncode == 0, result.stdout + result.stderr + assert int(result.stdout, 16) == zlib.crc32(data) + + +def test_thread_persisted_checksum_bytes(thread_tool, tmp_path): + output = tmp_path / "image.bin" + result = subprocess.run([str(thread_tool), "snapshot", str(output)], capture_output=True, text=True) + assert result.returncode == 0, result.stdout + result.stderr + image = output.read_bytes() + assert len(image) == 2 * 1024 * 1024 + offset = image.index(b"MCST") + assert image.count(b"MCST") == 1 + magic, version, size, checksum = struct.unpack_from("<4s3I", image, offset) + assert magic == b"MCST" and version == 1 + # The complete 256-thread array is protected, including unused stack bytes. + assert size == 16 + 56 + 256 * (24 + 4096) + assert checksum == zlib.crc32(image[offset + 16:offset + size]) + assert offset == (len(image) - (65544 + 768 + 96 + 131068 + 16) - size) & ~15 + assert image[offset + size:] == b"\xa5" * (len(image) - offset - size) diff --git a/tools/harness/tests/test_muzzle_lighting.py b/tools/harness/tests/test_muzzle_lighting.py new file mode 100644 index 0000000000..ee96b6a7be --- /dev/null +++ b/tools/harness/tests/test_muzzle_lighting.py @@ -0,0 +1,37 @@ +"""Real pulse ownership and render-time fade, without game assets.""" +import re +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import CHECK_FAILED, build, function, mutated, read, run + + +def generated(fault=None): + code = re.sub(r'^#include.*$', '', read('port/linux/game/muzzle_lighting.c'), flags=re.M) + code += function(read('source/objects/object_lights.c'), 'light_port_glow_move') + if fault: + code = mutated(code, *fault) + return (('under_test.inc', code),) + + +@pytest.mark.parametrize('case', ['pulse', 'profiles', 'off', 'capacity', 'lifecycle', 'failures', 'world', 'move', 'warthog', 'scorpion']) +def test_case(case): + status, output = run(build('muzzle_lighting', generated()), case) + assert status == 0, output + + +@pytest.mark.parametrize('before,after,case', [ + ('real now = render_interpolation_game_time_sec(game_time_get());', 'real now = (real)game_time_get() / 30.0f;', 'pulse'), + ('pulse->connected = FALSE;', 'pulse->connected = TRUE;', 'off'), + ('light->position = *position;', '(void)position;', 'move'), +]) +def test_negative_control(before, after, case): + # The connected assignment has two legitimate sites; mutate cleanup only. + if before == 'pulse->connected = FALSE;': + before = 'light_disconnect_from_map(pulse->light);\n\t\t\tpulse->connected = FALSE;' + after = 'light_disconnect_from_map(pulse->light);\n\t\t\tpulse->connected = TRUE;' + status, output = run(build('muzzle_lighting', generated((before, after))), case) + assert status == CHECK_FAILED, output diff --git a/tools/harness/tests/test_plasma_collision.py b/tools/harness/tests/test_plasma_collision.py new file mode 100644 index 0000000000..0efeed2589 --- /dev/null +++ b/tools/harness/tests/test_plasma_collision.py @@ -0,0 +1,49 @@ +"""Exercise batch ownership, exact eligibility and safe fallback using real code.""" +import re +import sys +import pytest +from pathlib import Path +sys.path.insert(0,str(Path(__file__).resolve().parents[2])) +from harness import build,read,run,CHECK_FAILED,function,structure + +def code(): + return ('enum { COLLISION_VECTOR_CACHE_NODES = 512 };\n' + + structure(read('source/physics/collision_bsp.h'),'collision_bsp_vector_cache') + '\n' + + function(read('source/math/real_math.c'), 'fast_vector_intersects_sphere') + '\n' + + re.sub(r'^#include.*$','',read('port/linux/game/plasma_collision.c'),flags=re.M)) + +def test_depth_batch(): + status,output=run(build('plasma_collision',(('under_test.inc',code()),)),'batch') + assert status==0,output + +def test_child_gating_regression(): + broken=code().replace('object->eligible && trace_sphere(object, vector)', 'object->eligible') + status,output=run(build('plasma_collision',(('under_test.inc',broken),)),'batch') + assert status==CHECK_FAILED,output + + +def test_shared_vector_entry_preserves_stock_contract(): + source=read('source/physics/collision_bsp.c') + functions='\n'.join(function(source,name) for name in ( + 'collision_bsp_test_vector_at_node','collision_bsp_test_vector','collision_bsp_test_vector_from_node')) + context=structure(source,'collision_bsp_test_vector_context') + status,output=run(build('collision_vector_entry',(('context.inc',context),('under_test.inc',functions))),'entry') + assert status==0,output + + +@pytest.mark.parametrize('fault', [None, 'budget', 'bounds', 'eviction']) +def test_vector_cache_preserves_traversal_results(fault): + source=read('source/physics/collision_bsp.c') + traversal=function(source,'collision_bsp_test_vector_recursive') + prepare='\n'.join(function(read('port/linux/game/plasma_collision.c'),name) for name in ('trace_side','trace_prepare')) + if fault == 'budget': + traversal=traversal.replace('data->nodes_left -= data->cache->nodes[cache_slot].skip_count - 1;', '') + if fault == 'bounds': + prepare=prepare.replace('low > margin', '(low-low+distance) > margin') + if fault == 'eviction': + traversal=traversal.replace('data->cache->nodes[cache_slot].skip_count = 0;', '') + includes=(('context.inc',structure(source,'collision_bsp_test_vector_context')), + ('cache.inc',structure(read('source/physics/collision_bsp.h'),'collision_bsp_vector_cache')), + ('prepare.inc',prepare), ('under_test.inc',traversal)) + status,output=run(build('collision_vector_cache',includes),'cache') + assert status==(CHECK_FAILED if fault else 0),output diff --git a/tools/harness/tests/test_plasma_collision_models.py b/tools/harness/tests/test_plasma_collision_models.py new file mode 100644 index 0000000000..a24eb86592 --- /dev/null +++ b/tools/harness/tests/test_plasma_collision_models.py @@ -0,0 +1,18 @@ +"""Compare model-major batches with the original model query and matrix maths.""" +import re +from tools.harness import build, read, run, function, structure + + +def test_model_major_batch_matches_original_queries(): + code = structure(read('source/math/real_math.h'), 'real_matrix4x3') + '\ntypedef struct real_matrix4x3 real_matrix4x3;\n' + code += structure(read('source/physics/collision_models.h'), 'collision_model_instance') + '\n' + maths = read('source/math/matrix_math.c') + inverse = function(maths, 'matrix4x3_inverse').replace('matrix4x3_inverse(', 'original_matrix4x3_inverse(', 1) + code += inverse + '\nstatic void matrix4x3_inverse(const real_matrix4x3 *m,real_matrix4x3 *r) { inversions++;original_matrix4x3_inverse(m,r); }\n' + code += '\n'.join(function(maths, name) for name in ('matrix4x3_transform_point', 'matrix4x3_transform_vector')) + original = read('source/physics/collision_models.c') + code += '\n'+function(original, 'collision_node_region_valid')+'\nstatic LARGE_INTEGER collision_model_test_vector_time;\n' + code += function(original, 'collision_model_test_vector') + '\n' + code += re.sub(r'^#include.*$', '', read('port/linux/game/plasma_collision_models.c'), flags=re.M) + status, output = run(build('plasma_collision_models', (('under_test.inc', code),)), 'batch') + assert status == 0, output diff --git a/tools/harness/tests/test_plasma_collision_scene.py b/tools/harness/tests/test_plasma_collision_scene.py new file mode 100644 index 0000000000..69c97176e1 --- /dev/null +++ b/tools/harness/tests/test_plasma_collision_scene.py @@ -0,0 +1,13 @@ +"""Stationary reuse must notice every collision input, without hash collisions.""" +import re +import sys +from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import build, read, run, structure + + +def test_scene_snapshot(): + source = re.sub(r'^#include.*$', '', read('port/linux/game/plasma_collision_scene.c'), flags=re.M) + source = 'enum { PLASMA_COLLISION_SCENE_BYTES = 65536 };\n' + structure(read('port/linux/include/plasma_collision.h'), 'plasma_collision_scene') + '\n' + source + status, output = run(build('plasma_collision_scene', (('under_test.inc', source),)), 'scene') + assert status == 0, output diff --git a/tools/harness/tests/test_plasma_falloff.py b/tools/harness/tests/test_plasma_falloff.py new file mode 100644 index 0000000000..eed6b199e2 --- /dev/null +++ b/tools/harness/tests/test_plasma_falloff.py @@ -0,0 +1,35 @@ +"""Exercise the real attenuation texture generation and scoped binding.""" +import re +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import CHECK_FAILED, build, mutated, read, run + + +def generated(fault=None): + code = re.sub(r'^#include.*$', '', read('port/linux/game/plasma_falloff.c'), flags=re.M) + if fault: + code = mutated(code, *fault) + return (('under_test.inc', code),) + + +@pytest.mark.parametrize('case', ['curve', 'scope', 'specular', 'failure', 'tint']) +def test_case(case): + status, output = run(build('plasma_falloff', generated()), case) + assert status == 0, output + + +def test_edge_negative_control(): + status, output = run(build('plasma_falloff', generated( + ('return remaining * remaining;', 'return remaining;'))), 'curve') + assert status == CHECK_FAILED, output + + +def test_tint_negative_control(): + status, output = run(build('plasma_falloff', generated( + ('plasma_specular_tint = real_rgb_color_to_pixel32(&tint);', + 'plasma_specular_tint = 0x00FFFFFFUL;'))), 'tint') + assert status == CHECK_FAILED, output diff --git a/tools/harness/tests/test_plasma_lighting.py b/tools/harness/tests/test_plasma_lighting.py new file mode 100644 index 0000000000..c2f40c0570 --- /dev/null +++ b/tools/harness/tests/test_plasma_lighting.py @@ -0,0 +1,52 @@ +"""Render-only attachment refresh must not survive a frame or map boundary.""" +import re +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import CHECK_FAILED, build, function, mutated, read, run + + +def generated(fault=None): + code = function(read('source/objects/object_lights.c'), 'light_port_refresh_attachment') + code += function(read('source/objects/object_lights.c'), 'light_port_dynamic_set') + code += function(read('source/objects/object_lights.c'), 'light_port_attachment_radius') + policy = read('port/linux/game/covenant_lighting.c') + policy = policy[policy.index('static const struct covenant_profile'):policy.index('static const real_rgb_color covenant_black')] + code += 'typedef struct { real red, green, blue; } real_rgb_color;\n' + policy + code += re.sub(r'^#include.*$', '', read('port/linux/game/plasma_lighting.c'), flags=re.M) + code += function(read('source/objects/object_lights.c'), 'light_compute_bounding_sphere') + code += function(read('port/linux/game/render_interpolation.c'), 'render_interpolation_frame_end') + if fault: + code = mutated(code, *fault) + return (('under_test.inc', code),) + + +@pytest.mark.parametrize('case', ['shield', 'counter_cache', 'covenant', 'muzzle', 'radius', 'rocket', 'pistol', 'model', 'off', 'filter', 'restore', 'split', 'capacity', 'unload', 'missing', 'stale', 'selection', 'disconnected', 'existing']) +def test_case(case): + status, output = run(build('plasma_lighting', generated()), case) + assert status == 0, output + + +@pytest.mark.parametrize('before,after,case', [ + ('strcmp(name, "weapons\\\\rocket launcher\\\\rocket")', '1', 'rocket'), + ('strcmp(name, "weapons\\\\plasma pistol\\\\bolt") &&', '1 &&', 'pistol'), + ('return radius * plasma_lighting_attachments[index].radius_scale;', 'return radius;', 'radius'), + ('interpolation_rendering = FALSE;', 'interpolation_rendering = TRUE;', 'restore'), + ('plasma_lighting_count = 0;', '(void)0;', 'unload'), +]) +def test_negative_control(before, after, case): + status, output = run(build('plasma_lighting', generated((before, after))), case) + assert status == CHECK_FAILED, output + + +def test_disabled_projectile_policy_is_required(): + # Authored emitters add a second category gate. Removing only the early + # return is no longer a fault: the second gate still preserves stock. + name, code = generated()[0] + assert code.count('lighting_config_boolean("display.plasma_lighting")') > 1 + code = code.replace('lighting_config_boolean("display.plasma_lighting")', 'TRUE') + status, output = run(build('plasma_lighting', ((name, code),)), 'off') + assert status == CHECK_FAILED, output diff --git a/tools/harness/tests/test_plasma_model_shader.py b/tools/harness/tests/test_plasma_model_shader.py new file mode 100644 index 0000000000..dfeafe3b3e --- /dev/null +++ b/tools/harness/tests/test_plasma_model_shader.py @@ -0,0 +1,44 @@ +"""Translate the real stock programs with the feature's shader additions.""" +import re +import sys +from pathlib import Path +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import build, function, read, run, structure + + +def shader_source(platform): + header = read('port/linux/src/xgpu.h') + code = '' if platform == 'desktop' else '#define HALO_GLES 1\n' + if platform == 'android': + code += '#define HALO_ANDROID 1\n' + elif platform == 'web': + code += '#define HALO_WEB 1\n' + code += 'static struct { const char *shading_language; } xgpu_capabilities = {"300 es"};\n' + code += '#define XGPU_MODEL_LIGHT_COUNT 12\n' + code += structure(header, 'xgpu_text') + '\n' + code += structure(header, 'nv2a_vertex_lighting') + '\n' + code += read('port/linux/include/plasma_model_shader.h') + sources = ['port/linux/src/nv2a_vsh.c'] + if platform != 'android': + sources.insert(0, 'port/linux/src/plasma_model_shader.c') + for path in sources: + code += re.sub(r'^#include.*$', '', read(path), flags=re.M) + code += function(read('port/linux/src/nv2a_psh.c'), 'model_lighting') + words = [int(v, 16) for v in re.findall(r'0x[0-9A-Fa-f]+', + re.sub(r'/\*.*?\*/', '', read('source/rasterizer/xbox/rasterizer_xbox_vertex_shaders_data.inc'), flags=re.S))] + programs = [] + for index, word in enumerate(words): + if word & 0xffff == 0x2078 and 0 < word >> 16 <= 136: + programs.append(words[index+1:index+1+4*(word >> 16)]) + code += '\nstatic const unsigned long programs[][544] = {\n' + ',\n'.join( + '{' + ','.join(str(w)+'UL' for w in p) + '}' for p in programs) + '};\n' + code += 'static const unsigned long lengths[] = {' + ','.join(str(len(p)//4) for p in programs) + '};\n' + return code + + +@pytest.mark.parametrize('platform', ['desktop', 'android', 'web']) +def test_stock_programs(platform): + status, output = run(build('plasma_model_shader', (('under_test.inc', shader_source(platform)),)), 'programs') + assert status == 0, output diff --git a/tools/harness/tests/test_plasma_occlusion.py b/tools/harness/tests/test_plasma_occlusion.py new file mode 100644 index 0000000000..100768868c --- /dev/null +++ b/tools/harness/tests/test_plasma_occlusion.py @@ -0,0 +1,213 @@ +"""Exercise the actual visibility field with synthetic collision geometry.""" +import re +import sys +import pytest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import CHECK_FAILED, build, read, run + + +def test_packed_texture_rows_match_scalar_conversion(): + from harness import function + masks=read('port/linux/game/ammo_counter_falloff.c') + code='\n'.join(function(masks,name) for name in ('ammo_counter_falloff_factor','needler_falloff_factor','plasma_prong_falloff_factor')) + row=function(read('port/linux/game/plasma_occlusion.c'),'texture_row') + reference=row.replace('texture_row(', 'reference_texture_row(', 1).replace('#if defined(__SSE2__)', '#if 0') + status,output=run(build('plasma_texture_rows',(('under_test.inc',code+'\n'+row+'\n'+reference),)),'rows') + assert status==0,output + + +def test_visibility_field(): + code = re.sub(r'^#include.*$', '', read('port/linux/game/ammo_counter_falloff.c') + '\n' + read('port/linux/game/plasma_occlusion.c'), flags=re.M) + status, output = run(build('plasma_occlusion', (('under_test.inc', code),)), 'visibility') + assert status == 0, output + + +def test_fade_underflow_guard_is_required(): + code = re.sub(r'^#include.*$', '', read('port/linux/game/ammo_counter_falloff.c') + '\n' + read('port/linux/game/plasma_occlusion.c'), flags=re.M) + guard = 'if (value < 1.0e-20f) value = 0;' + assert code.count(guard) == 1 + status, output = run(build('plasma_occlusion', (('under_test.inc', code.replace(guard, '')),)), 'visibility') + assert status == CHECK_FAILED and 'blocked history settles' in output, output + + +def test_clear_depth_shortcut_is_exact(): + from harness import function + code = re.sub(r'^#include.*$', '', read('port/linux/game/ammo_counter_falloff.c') + '\n' + read('port/linux/game/plasma_occlusion.c'), flags=re.M) + body = function(code, 'depth_visibility') + reference = body.replace('depth_visibility(', 'reference_depth_visibility(', 1).replace('if (clear)', 'if (clear && FALSE)') + fast = body.replace('depth_visibility(', 'fast_depth_visibility(', 1) + wrapper = r''' +static real depth_visibility(real depths[6][OCC_SIZE * OCC_SIZE], real_vector3d const *ray, real extent, int resolution) +{ + real result = fast_depth_visibility(depths, ray, extent, resolution); + CHECK(result == reference_depth_visibility(depths, ray, extent, resolution), "clear depth shortcut retains float result"); + return result; +} +''' + code = code.replace(body, reference + '\n' + fast + wrapper).replace('#if defined(__SSE2__)', '#if 0') + status, output = run(build('plasma_occlusion', (('under_test.inc', code),)), 'visibility') + assert status == 0, output + + +def test_stale_pass_upload_is_detected(): + code = re.sub(r'^#include.*$', '', read('port/linux/game/ammo_counter_falloff.c') + '\n' + read('port/linux/game/plasma_occlusion.c'), flags=re.M) + assert code.count('field->texture_mask = 0;') == 2 + code = code.replace('field->texture_mask = 0;', '(void)0;') + status, output = run(build('plasma_occlusion', (('under_test.inc', code),)), 'visibility') + assert status == CHECK_FAILED, output + + +def test_directional_mask_is_required(): + code = re.sub(r'^#include.*$', '', read('port/linux/game/ammo_counter_falloff.c') + '\n' + read('port/linux/game/plasma_occlusion.c'), flags=re.M) + code = code.replace('return t*t*(3.0f - 2.0f*t);', '(void)t; return 1.0f;') + status, output = run(build('plasma_occlusion', (('under_test.inc', code),)), 'visibility') + assert status == CHECK_FAILED, output + + +def test_needler_filtered_foot_pool_is_detected(): + code = re.sub(r'^#include.*$', '', read('port/linux/game/ammo_counter_falloff.c') + '\n' + read('port/linux/game/plasma_occlusion.c'), flags=re.M) + # The previous long fade must no longer satisfy the lower-spill contract. + old = code.replace('(-height - 0.06f) / 0.06f', '(-height - 0.06f) / 0.18f') + status, output = run(build('plasma_occlusion', (('under_test.inc', old),)), 'visibility') + assert status == CHECK_FAILED, output + + +def test_stationary_history_matches_reprojection(): + code = re.sub(r'^#include.*$', '', read('port/linux/game/ammo_counter_falloff.c') + '\n' + read('port/linux/game/plasma_occlusion.c'), flags=re.M) + # Compare every updated cell, including moving lights, door changes, changed + # extents and the 30/60/120 Hz sequences exercised by the fixture. + marker = '\tfield->valid = 1;' + assert code.count(marker) == 1 + code = code.replace(marker, marker + '\n\tfor (i = 0; i < OCC_COUNT; i++) printf("CELL %.9g\\n", field->visibility[i]);') + samples = [] + reference = code.replace('if (stationary)', 'if (stationary && FALSE)') + reference = reference.replace('if (stationary && !retraced)', 'if (stationary && !retraced && FALSE)') + # The reference also needs coordinates for stationary fields now that + # reprojection prepares its separable axes before visiting the cells. + reference = reference.replace('if (!stationary && field->valid', 'if (field->valid') + for version in (code, reference): + status, output = run(build('plasma_occlusion', (('under_test.inc', version),)), 'visibility') + assert status == 0, output[-2000:] + samples.append([float(x) for x in re.findall(r'CELL (\S+)', output)]) + assert len(samples[0]) > 4096 + assert samples[0] == pytest.approx(samples[1], abs=0.00001) + + +def test_precomputed_history_matches_cell_coordinates(): + code = re.sub(r'^#include.*$', '', read('port/linux/game/ammo_counter_falloff.c') + '\n' + read('port/linux/game/plasma_occlusion.c'), flags=re.M) + fast = 'history = sample_history_rows(projected, x, y, &history_axes[2][z]);' + assert code.count(fast) == 1 + # Check the actual fast result against the original per-cell coordinate + # arithmetic throughout movement, extent changes and all three rates. + reference = '''sample_field(previous, + 0.5f + (light->position.x + ((2.0f * (x + 0.5f) / OCC_SIZE - 1) * extent) - field->center[0]) / (2 * field->extent), + 0.5f + (light->position.y + ((2.0f * (y + 0.5f) / OCC_SIZE - 1) * extent) - field->center[1]) / (2 * field->extent), + 0.5f + (light->position.z + ((2.0f * (z + 0.5f) / OCC_SIZE - 1) * extent) - field->center[2]) / (2 * field->extent))''' + code = code.replace(fast, '{ ' + fast + '\nCHECK(history == ' + reference + ', "precomputed coordinates preserve every sample"); }') + status, output = run(build('plasma_occlusion', (('under_test.inc', code),)), 'visibility') + assert status == 0, output + + +def test_interpolation_matches_weighted_visibility(): + from harness import function + code = re.sub(r'^#include.*$', '', read('port/linux/game/ammo_counter_falloff.c') + '\n' + read('port/linux/game/plasma_occlusion.c'), flags=re.M) + body = function(code, 'sample_axes') + wrapper = r''' +static real sample_axes(const real *values, const struct sample_axis *x, + const struct sample_axis *y, const struct sample_axis *z) +{ + int i,j,k; + double expected=0; + real result=fast_sample_axes(values,x,y,z); + for(k=0;k<2;k++) for(j=0;j<2;j++) for(i=0;i<2;i++) + expected += (double)values[((k?z->b:z->a)*OCC_SIZE+(j?y->b:y->a))*OCC_SIZE+(i?x->b:x->a)] * + (i?x->t:1-x->t)*(j?y->t:1-y->t)*(k?z->t:1-z->t); + CHECK(fabs(result-expected)<0.000001, "seven interpolations agree with weighted visibility"); + return result; +} +''' + code = code.replace(body, body.replace('sample_axes(', 'fast_sample_axes(', 1) + wrapper) + status, output = run(build('plasma_occlusion', (('under_test.inc', code),)), 'visibility') + assert status == 0, output + +def test_half_scale_resampling_is_exact(): + code = re.sub(r'^#include.*$', '', read('port/linux/game/ammo_counter_falloff.c') + '\n' + read('port/linux/game/plasma_occlusion.c'), flags=re.M) + anchor = '\t\t\t\t\tvalue = 1 - field->admission + field->admission * value;\n\t\t\t\t\tif (directional)' + assert code.count(anchor) == 1 + check = r''' + if (pass && remaining > 0 && scale == 0.5f) { + real expected=sample_field(field->visibility, 0.5f+(2.0f*(x+0.5f)/16-1)*0.25f, + 0.5f+(2.0f*(y+0.5f)/16-1)*0.25f, 0.5f+(2.0f*(z+0.5f)/16-1)*0.25f); + CHECK(value==expected, "half-scale resampling preserves the original float result"); + } +''' + code = code.replace(anchor, check + anchor) + status, output = run(build('plasma_occlusion', (('under_test.inc', code),)), 'visibility') + assert status == 0, output + + +def test_specialized_masks_match_generic_pixels(): + code = re.sub(r'^#include.*$', '', read('port/linux/game/ammo_counter_falloff.c') + '\n' + read('port/linux/game/plasma_occlusion.c'), flags=re.M) + start = code.index('\telse\n\t{', code.index('The ordinary model mask needs')) + opening = code.index('{', start) + end, depth = opening + 1, 1 + while depth: + depth += (code[end] == '{') - (code[end] == '}') + end += 1 + # Execute the actual generic conversion beside the flat path, comparing + # all uploaded cells rather than only representative sample positions. + generic = code[opening + 1:end - 1].replace('pixels[i]', 'reference_pixels[i]') + check = ('\nif (!directional && (!pass || scale == 0.5f || scale == 1.0f)) { unsigned long reference_pixels[OCC_COUNT];\n' + + generic + '\nCHECK(!memcmp(pixels, reference_pixels, sizeof(pixels)), "specialized mask matches every generic pixel");\n}\n') + marker = '\tif (!(field->uploaded_mask & (1 << pass))' + assert code.count(marker) == 1 + code = code.replace(marker, check + marker) + status, output = run(build('plasma_occlusion', (('under_test.inc', code),)), 'visibility') + assert status == 0, output + + +def test_runtime_texture_comparison_preserves_uploads(tmp_path, monkeypatch): + from lighting_texture_check import instrument + code = read('port/linux/game/ammo_counter_falloff.c') + '\n' + read('port/linux/game/plasma_occlusion.c') + code = instrument(code).replace('if (memcmp(fast, generic, sizeof(fast))) mismatches++;', + 'CHECK(!memcmp(fast, generic, sizeof(fast)), "runtime comparison preserves every texture byte");') + clocks = ''' +typedef struct { long long QuadPart; } LARGE_INTEGER; +static void QueryPerformanceCounter(LARGE_INTEGER *v) { static long long tick; v->QuadPart=++tick; } +static void QueryPerformanceFrequency(LARGE_INTEGER *v) { v->QuadPart=1000000; } +''' + code = clocks + re.sub(r'^#include.*$', '', code, flags=re.M) + monkeypatch.chdir(tmp_path) + status, output = run(build('plasma_occlusion', (('under_test.inc', code),)), 'visibility') + assert status == 0, output + + +def test_packed_visibility_matches_scalar_fields(): + code = re.sub(r'^#include.*$', '', read('port/linux/game/ammo_counter_falloff.c') + '\n' + read('port/linux/game/plasma_occlusion.c'), flags=re.M) + samples = [] + marker = '\tfield->valid = 1;' + code = code.replace(marker, marker + '\n\tfor (i = 0; i < OCC_COUNT; i++) printf("CELL %.9g\\n", field->visibility[i]);') + for version in (code, code.replace('#if defined(__SSE2__)', '#if 0')): + status, output = run(build('plasma_occlusion', (('under_test.inc', version),)), 'visibility') + assert status == 0, output[-2000:] + samples.append(re.findall(r'CELL (\S+)', output)) + assert len(samples[0]) > 4096 + assert samples[0] == samples[1] + + +def test_runtime_visibility_comparison_preserves_fields(tmp_path, monkeypatch): + from lighting_visibility_check import instrument + code = read('port/linux/game/ammo_counter_falloff.c') + '\n' + read('port/linux/game/plasma_occlusion.c') + code = instrument(code).replace('if (memcmp(output, reference, sizeof(reference))) mismatches++;', + 'CHECK(!memcmp(output, reference, sizeof(reference)), "runtime comparison preserves every visibility byte");') + clocks = ''' +typedef struct { long long QuadPart; } LARGE_INTEGER; +static void QueryPerformanceCounter(LARGE_INTEGER *v) { static long long tick; v->QuadPart=++tick; } +static void QueryPerformanceFrequency(LARGE_INTEGER *v) { v->QuadPart=1000000; } +''' + code = clocks + re.sub(r'^#include.*$', '', code, flags=re.M) + monkeypatch.chdir(tmp_path) + status, output = run(build('plasma_occlusion', (('under_test.inc', code),)), 'visibility') + assert status == 0, output diff --git a/tools/harness/tests/test_plasma_occlusion_gl.py b/tools/harness/tests/test_plasma_occlusion_gl.py new file mode 100644 index 0000000000..fe872053a4 --- /dev/null +++ b/tools/harness/tests/test_plasma_occlusion_gl.py @@ -0,0 +1,17 @@ +"""Validate program-owned locations and unchanged sampling without a GL driver.""" +import re +import sys +import pytest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import build, read, run + + +@pytest.mark.parametrize('gles', [False, True]) +def test_model_occlusion_binding_ownership(gles): + header = read('port/linux/include/plasma_occlusion.h') + uniforms = re.search(r'struct plasma_occlusion_uniforms\s*\{[^}]+\};', header)[0] + code = re.sub(r'^#include.*$', '', read('port/linux/src/plasma_occlusion_gl.c'), flags=re.M) + status, output = run(build('plasma_occlusion_gl', (('under_test.inc', ('#define HALO_GLES\n' if gles else '')+uniforms+'\n'+code),)), 'binding') + assert status == 0, output diff --git a/tools/harness/tests/test_plasma_visibility.py b/tools/harness/tests/test_plasma_visibility.py new file mode 100644 index 0000000000..20cca79bd1 --- /dev/null +++ b/tools/harness/tests/test_plasma_visibility.py @@ -0,0 +1,13 @@ +"""Compare actual packed reconstruction against scalar at cell boundaries.""" +import re +from tools.harness import build, read, run, function + + +def test_packed_visibility_preserves_every_cell(): + source = read('port/linux/game/plasma_occlusion.c') + start = source.index('/* Four receiver cells') + end = source.index('static real filter_visibility', start) + code = 'enum { OCC_SIZE=16 };\n' + function(source, 'depth_visibility') + '\n' + source[start:end] + for variant in (code, code.replace('#if defined(__SSE2__)', '#if 0')): + status, output = run(build('plasma_visibility', (('under_test.inc', variant),)), 'compare') + assert status == 0, output diff --git a/tools/harness/tests/test_polygon_clip.py b/tools/harness/tests/test_polygon_clip.py index 932c081207..e4cbff5655 100644 --- a/tools/harness/tests/test_polygon_clip.py +++ b/tools/harness/tests/test_polygon_clip.py @@ -10,12 +10,13 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[2])) from harness import CHECK_FAILED, build, constant, function, inline, mutated, read, run # noqa: E402 -CASES = ["shared-corners-a", "shared-corners-b", "ordinary-clip"] +CASES = ["shared-corners-a", "shared-corners-b", "ordinary-clip", "successive-portals", "clip-contract"] # a fault and the case that must catch it NEGATIVE_CONTROLS = { "nan-crossing": (("if (scale != scale) scale = 0.f;\n", ""), "shared-corners-a"), "nan-crossing-b": (("if (scale != scale) scale = 0.f;\n", ""), "shared-corners-b"), + "nan-later-portal": (("if (scale != scale) scale = 0.f;\n", ""), "successive-portals"), "no-clip": (("result_count = convex_polygon2d_clip_to_plane(", "result_count = 0 * convex_polygon2d_clip_to_plane("), "shared-corners-a"), } diff --git a/tools/harness/tests/test_render_effect_lifecycle.py b/tools/harness/tests/test_render_effect_lifecycle.py new file mode 100644 index 0000000000..02b7221bc0 --- /dev/null +++ b/tools/harness/tests/test_render_effect_lifecycle.py @@ -0,0 +1,43 @@ +"""Real camera/cloth updates and saved-state dispatcher over a minimal render world.""" +import re +import sys +from pathlib import Path +import pytest +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import CHECK_FAILED, build, enum_with, function, mutated, read, run, structure + + +def generated(missing=None): + camera = read('source/effects/player_effects.c') + damage = read('source/objects/damage_effect_definitions.h') + flags = read('source/objects/widgets/flags.c') + config = '\n'.join(structure(damage, n) for n in ('screen_flash_definition', 'camera_impulse_definition', 'camera_shake_definition')) + config += '\n' + '\n'.join(structure(camera, n) for n in ('continuous_player_effect_datum', 'player_effect_datum', 'screen_fade_definition', 'scripted_player_effect_definition', 'player_effect_globals_definition')) + config += '\n' + enum_with(camera, '_scripted_player_effect_active_bit') + config += '\n' + enum_with(camera, '_player_effect_screen_flash_just_started_bit') + cache = re.search(r'^static struct\s*\{[^}]*\} camera_effect_of_tick\[[^;]*;', camera, re.M).group(0) + clocks = flags.split('/* ---------- globals */')[1].split('/* ---------- public code */')[0] + code = cache + '\n' + clocks + '\n' + code += '\n'.join(function(camera, n) for n in ('player_effect_get', 'player_effect_reset_render_state', 'player_effect_initialize_for_new_map', 'player_effect_dispose_from_old_map', 'player_effect_get_camera_effect_matrix')) + code += '\n' + '\n'.join(function(flags, n) for n in ('flags_reset_render_state', 'flags_initialize_for_new_map', 'flags_dispose_from_old_map', 'flags_update')) + state = read('source/saved games/game_state.c') + callbacks = re.search(r'static game_state_after_load_proc after_load_procs\[\] =\s*\{.*?\};', state, re.S).group(0) + names = re.findall(r'^\s*(\w+)\s*,?\s*$', callbacks, re.M) + code += '\ntypedef void (*game_state_after_load_proc)(void);\n' + code += '\n'.join(f'static void {name}(void) {{ }}' for name in names if name not in ('player_effect_reset_render_state', 'flags_reset_render_state')) + if missing: + callbacks = mutated(callbacks, '\t' + missing + ',', '') + code += '\n' + callbacks + '\n' + function(state, 'game_state_call_after_load_procs') + return (('config.inc', config), ('under_test.inc', code)) + + +@pytest.mark.parametrize('case', ['camera-checkpoint', 'camera-maps', 'camera-windows', 'cloth-checkpoint', 'cloth-maps', 'cloth-frames']) +def test_lifecycle(case): + status, output = run(build('render_effect_lifecycle', generated()), case) + assert status == 0, output + + +@pytest.mark.parametrize('hook,case', [('player_effect_reset_render_state', 'camera-checkpoint'), ('flags_reset_render_state', 'cloth-checkpoint')]) +def test_missing_hook(hook, case): + status, output = run(build('render_effect_lifecycle', generated(hook)), case) + assert status == CHECK_FAILED, output diff --git a/tools/harness/tests/test_reported_hit_sight.py b/tools/harness/tests/test_reported_hit_sight.py new file mode 100644 index 0000000000..d509bf77cd --- /dev/null +++ b/tools/harness/tests/test_reported_hit_sight.py @@ -0,0 +1,70 @@ +"""Host line-of-sight admission, hand fallback and attached-hit consumption, from production code.""" +import re +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import CHECK_FAILED, build, constant, enum_with, function, mutated, read, run, structure + +CASES = ['clear', 'blocked', 'impact', 'mounted', 'missing', 'window', 'budget', 'attached', + 'hand', 'hand_shape', 'eye_priority'] +CONTROLS = [ + ('return !collision_test_line(flags, from, centre, NONE, &collision) ||', + 'return TRUE ||', 'blocked'), + ('!collision_test_line(flags, impact, centre, NONE, &collision)', + 'TRUE', 'impact'), + ('!collision_test_line(flags, &eye, &trail_point->muzzle, NONE, &collision)', + 'TRUE', 'mounted'), + ('stuck->spent = TRUE;', 'stuck->spent = FALSE;', 'attached'), + ('pass == 1 && !distributed_fire_origins_accepted()', 'FALSE', 'hand'), + ('pass == 0 || distributed_fire_origin_shape(&eye, &trail_point->muzzle, centre)', + 'TRUE', 'hand_shape'), + ('damage_hand_reports++;', 'damage_hand_reports += 0;', 'hand'), + ('for (pass = 0; pass < 2; pass++)', 'for (pass = 1; pass >= 0; pass--)', 'eye_priority'), +] + + +def generated(fault=None): + source = read('port/linux/game/network_damage.c') + config = '#define TICKS_PER_SECOND %d\n' % constant(read('source/cseries/cseries.h'), 'TICKS_PER_SECOND') + config += enum_with(source, 'REPORT_LINE_OF_SIGHT_TICKS =') + '\n' + config += '\n'.join(re.findall(r'^#define FIRE_ORIGIN_\w+ [^\n]+', source, re.M)) + '\n' + for name in ['damage_reach', 'damage_trail_point', 'damage_stuck_projectile']: + config += structure(source.replace('static struct ', 'struct '), name).rsplit('}', 1)[0] + '};\n' + code = '\n'.join(function(source, name) for name in [ + 'distributed_distance_squared', 'distributed_report_sight_clear', + 'distributed_fire_origins_accepted', 'distributed_fire_origin_shape', + 'distributed_report_line_of_sight', 'distributed_stuck_detonation']) + if fault: + code = mutated(code, *fault) + return (('config.inc', config), ('under_test.inc', code)) + + +@pytest.mark.parametrize('case', CASES) +def test_case(case): + status, output = run(build('reported_hit_sight', generated()), case) + assert status == 0, output + + +@pytest.mark.parametrize('before,after,case', CONTROLS) +def test_negative_control(before, after, case): + status, output = run(build('reported_hit_sight', generated((before, after))), case) + assert status == CHECK_FAILED, output + + +def test_host_wiring_and_cleanup(): + source = read('port/linux/game/network_damage.c') + valid = function(source, 'distributed_report_valid') + assert valid.index('distributed_report_paid(') < valid.index('distributed_report_line_of_sight(') + assert '!melee && !collision && !area' in valid + assert 'distributed_stuck_detonation(' in valid + assert 'distributed_note_stuck_projectiles();' in function(source, 'network_damage_host_tick') + reset = function(source, 'network_damage_new_game') + assert 'stuck[index].time = NONE;' in reset + assert 'damage_trails[player_index][index].time = NONE;' in reset + targets = function(source, 'distributed_note_targets') + assert targets.index('distributed_vehicle_muzzle(') < targets.index('third_person_muzzle_history(') + assert targets.index('third_person_muzzle_history(') < targets.index('else if (damage_fire_origins[') + assert 'else if (third_person_muzzle_history(unit_index, &point->muzzle))\n\t\t\t\t\t\tpoint->mounted = TRUE;' in targets diff --git a/tools/harness/tests/test_rocket_lighting.py b/tools/harness/tests/test_rocket_lighting.py new file mode 100644 index 0000000000..b43320f0aa --- /dev/null +++ b/tools/harness/tests/test_rocket_lighting.py @@ -0,0 +1,20 @@ +"""Flight-light ownership uses the real feature module with fake engine services.""" +import re +import sys +from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import CHECK_FAILED, build, read, run + + +def test_owned_lights(): + code = re.sub(r'^#include.*$', '', read('port/linux/game/rocket_lighting.c'), flags=re.M) + status, output = run(build('rocket_lighting', (('under_test.inc', code),)), 'ownership') + assert status == 0, output + + +def test_missing_reconnection_is_detected(): + code = re.sub(r'^#include.*$', '', read('port/linux/game/rocket_lighting.c'), flags=re.M) + assert code.count('light_reconnect_to_map(light->light_index);') == 1 + code = code.replace('light_reconnect_to_map(light->light_index);', '(void)0;') + status, output = run(build('rocket_lighting', (('under_test.inc', code),)), 'ownership') + assert status == CHECK_FAILED, output diff --git a/tools/harness/tests/test_server_teardown.py b/tools/harness/tests/test_server_teardown.py index 875d0bd218..6ac53411b7 100644 --- a/tools/harness/tests/test_server_teardown.py +++ b/tools/harness/tests/test_server_teardown.py @@ -21,6 +21,8 @@ CASES += [('xbox', case) for case in ('postgame', 'ingame')] GUARD = '#if !defined(HALO_WINDOWS) && !defined(HALO_ANDROID) && !defined(HALO_WEB) && !defined(__linux__)' CONTROLS = { + 'bot-policy-not-cleared': ('bots_network_session_end();', ';', 'windows', 'back'), + 'bot-cooldown-not-cleared': ('bots_management_reset();', ';', 'windows', 'back'), 'native-sleeps': (GUARD, '#if 1', 'windows', 'back'), 'xbox-loses-grace': ('SleepEx(MILLISECONDS_PER_SECOND, FALSE);', ';', 'xbox', 'back'), 'transport-not-terminated': ('transport_server_terminate();', ';', 'windows', 'back'), @@ -31,7 +33,13 @@ def generated(platform, control=None): server = read('source/networking/network_server_manager.c') - code = function(server, 'network_game_server_dispose') + population = read('port/linux/game/bots_population.inl') + code = '\n'.join(re.findall(r'^static (?:unsigned )?long (?:population_|bots_population_).*;', + read('port/linux/game/bots_network.c') + population, re.M)) + '\n' + code += function(population, 'bots_population_map_reset') + '\n' + code += function(read('port/linux/game/bots_management.inl'), 'bots_management_reset') + code += '\n' + function(read('port/linux/game/bots_network.c'), 'bots_network_session_end') + code += '\n' + function(server, 'network_game_server_dispose') if control: before, after, _, _ = CONTROLS[control] code = mutated(code, before, after) @@ -44,6 +52,7 @@ def generated(platform, control=None): defines, sleep = PLATFORMS[platform] # The harness runs on Linux; each compiled variant selects its own target. config = '#undef __linux__\n#define xbox 1\n' + defines + f'\n#define EXPECTED_SLEEP {sleep}\n' + config += f'#define BOTS_MAXIMUM {constant(read("port/linux/game/bots.h"), "BOTS_MAXIMUM")}\n' config += f'#define MILLISECONDS_PER_SECOND {constant(read("source/cseries/cseries.h"), "MILLISECONDS_PER_SECOND")}\n' for member in ('_network_game_server_state_pregame', '_network_game_server_game_open_bit'): config += enum_with(server, member) + '\n' diff --git a/tools/harness/tests/test_settings_focus.py b/tools/harness/tests/test_settings_focus.py new file mode 100644 index 0000000000..9256d7dd4a --- /dev/null +++ b/tools/harness/tests/test_settings_focus.py @@ -0,0 +1,16 @@ +"""Generated setting rows remain operable after pointer/controller focus changes.""" +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import CHECK_FAILED, build, function, read, run + + +def test_setting_focus(): + code = function(read('port/linux/game/menu_functions.c'), 'settings_help') + status, output = run(build('settings_focus', (('under_test.inc', code),)), 'focus') + assert status == 0, output + # The missing input route reproduced by the real-menu acceptance run. + broken = code.replace('row->focused_child = child;', '(void)child;') + status, output = run(build('settings_focus', (('under_test.inc', broken),)), 'focus') + assert status == CHECK_FAILED, output diff --git a/tools/harness/tests/test_shield_effects.py b/tools/harness/tests/test_shield_effects.py index f19a2db40f..70ba7bd652 100644 --- a/tools/harness/tests/test_shield_effects.py +++ b/tools/harness/tests/test_shield_effects.py @@ -25,7 +25,8 @@ def generated(fault=None): function(source, 'network_shield_effects_handle_message')]) if fault: code = mutated(code, *fault) - return (('enums.inc', enums), ('under_test.inc', code)) + return (('enums.inc', enums), ('under_test.inc', code), + ('message_header.inc', structure(read('port/linux/game/network_distributed.h'), 'distributed_message_header'))) @pytest.mark.parametrize('case', ['offline', 'host', 'client', 'client_untrusted', 'coop']) diff --git a/tools/harness/tests/test_shield_lighting.py b/tools/harness/tests/test_shield_lighting.py new file mode 100644 index 0000000000..ae2fac26e0 --- /dev/null +++ b/tools/harness/tests/test_shield_lighting.py @@ -0,0 +1,57 @@ +"""Real shield lighting in a synthetic world: colour, ownership and timing.""" +from pathlib import Path +import re +import shutil +import sys +import pytest +import subprocess +import xml.etree.ElementTree as ET +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import enum_with + + +ROOT = Path(__file__).resolve().parents[3] + +def test_render_owned_shield_lighting(tmp_path): + source = (ROOT / 'port/linux/game/shield_glow.c').read_text() + source = re.sub(r'^#include.*$', '', source, flags=re.M) + policy = enum_with((ROOT / 'port/linux/game/network_shield_effects.h').read_text(), '_shield_effects_stock') + (tmp_path / 'shield_under_test.inc').write_text(policy + '\n' + source) + fixture = tmp_path / 'shield.c' + fixture.write_text((ROOT / 'tools/fixtures/shield_glow_test.c').read_text()) + compiler = shutil.which('clang') + if not compiler: + pytest.skip('clang required') + executable = tmp_path / ('shield.exe' if sys.platform == 'win32' else 'shield') + flags = ['--target=i686-pc-windows-msvc', '-fuse-ld=lld'] if sys.platform == 'win32' else ['-lm'] + subprocess.run([compiler, '-std=gnu89', '-Wall', '-Wextra', '-Werror', str(fixture), *flags, '-o', str(executable)], check=True) + result = subprocess.run([str(executable)], capture_output=True, text=True, timeout=10) + assert result.returncode == 0, result.stdout + result.stderr + + +def test_menu_ownership_and_generated_layout(): + import port_settings + spec = port_settings.SCREENS['video_settings/dynamic_lighting'] + rows = spec['rows'] + assert len(rows) == 10 + assert [row[1] for row in rows[2:7]] == [ + 'lighting.weapon_glow', 'display.plasma_prong_lighting', 'lighting.shield_emitters', + 'display.vehicle_lighting', 'display.world_lighting'] + assert rows[-2][1] == 'display.shield_glow' + assert rows[-1][1] == 'display.shield_glow_intensity' + extra = {row[1] for row in port_settings.SCREENS['video_settings/extra_effects']['rows']} + assert 'display.overshield_effect' in extra + assert not {'display.shield_glow', 'display.shield_glow_intensity'} & extra + assert 73 + (len(rows)-1)*spec['spacing'] + 28 < spec['help_top'] + assert spec['help_top'] + spec['help_height'] <= 414 + for name, lines in port_settings.settings_files().items(): + assert (ROOT/'port/assets/menus/ce'/name).read_text() == '\n'.join(lines) + if name.endswith(('dynamic_lighting.xml', 'controller_remapping.xml')): + widgets = ET.fromstring('\n'.join(lines)).iter('widget') + help_widget = next(w for w in widgets if w.get('name', '').endswith('/help')) + if name.endswith('dynamic_lighting.xml'): + assert help_widget.get('height') == str(spec['help_height']) + assert help_widget.get('string_list', '').endswith('/help_strings') + else: + assert help_widget.get('height') == str(port_settings.SCREENS['controller_remapping']['help_height']) + assert 'string_list' not in help_widget.attrib diff --git a/tools/harness/tests/test_touch_gyro.py b/tools/harness/tests/test_touch_gyro.py new file mode 100644 index 0000000000..2dc10382c2 --- /dev/null +++ b/tools/harness/tests/test_touch_gyro.py @@ -0,0 +1,34 @@ +"""Android gyro modes preserve saved input and discard unzoomed samples.""" +import re +import sys +import xml.etree.ElementTree as ET +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import build, read, run + + +@pytest.mark.parametrize("case", ["legacy", "modes", "axes"]) +def test_gyro(case): + source = read("port/linux/src/touch_gyro.h") + read("port/linux/src/touch_gyro.c") + source = re.sub(r'^#include.*\n', '', source, flags=re.M) + status, output = run(build("touch_gyro", (("under_test.inc", source),)), case) + assert status == 0, output + + +def test_android_menu(): + import port_settings + spec = port_settings.SCREENS["gamepad_setup/gyro"] + assert [value for _, value in spec["rows"][0][2]] == ["legacy", "false", "true", "zoom"] + assert all(row[4] == "android" for row in spec["rows"]) + setup = port_settings.SCREENS["gamepad_setup"] + xml = ET.fromstring("" + "\n".join(port_settings._setting_screen("gamepad_setup", setup)) + "") + children = next(w for w in xml if w.get("name", "").endswith("/options_menu")).findall("child") + for platform, count, spacing in [("desktop", 11, 25), ("web", 11, 25), ("android", 12, 23)]: + rows = [c for c in children if "/op_" in c.get("widget", "") and + (not c.get("platform") or platform in c.get("platform").split())] + assert len(rows) == count + assert [int(c.get("y")) for c in rows] == [73 + i * spacing for i in range(count)] + assert int(rows[-1].get("y")) + 28 <= setup["help_top"] diff --git a/tools/harness/tests/test_transparent_enclosure.py b/tools/harness/tests/test_transparent_enclosure.py index 93062525bd..ba92cf11a0 100644 --- a/tools/harness/tests/test_transparent_enclosure.py +++ b/tools/harness/tests/test_transparent_enclosure.py @@ -8,12 +8,15 @@ from harness import CHECK_FAILED, build, constant, enum_with, function, mutated, read, run, structure from harness.render_types import transparent_types -CASES = ["closed", "open", "outside", "reversed", "invalid", "strips", "uncompressed", +CASES = ["legs-on", "legs-off", "legs-shadow", "legs-empty", "legs-stripped", + "closed", "open", "outside", "reversed", "invalid", "strips", "uncompressed", "materials", "authored-links", "part-zero", "glass-zero", "opaque-part", "skinned", "additional-transparent", "frame-cost", "map-reload", "render-links", "lod-regions", "lod-shadows", "lod-off", "lod-empty", "lod-invalid", "lod-interior-inside", "lod-interior-outside", "lod-interior-inside-shadow", "lod-interior-outside-shadow"] CONTROLS = { + "legs-in-shadow": (("&& !TEST_FLAG(flags, _render_model_shadow_bit)", "&& TRUE"), "legs-shadow"), + "legs-always": (("(flags & FIRST_PERSON_LEGS_RENDER_FLAG)", "TRUE"), "legs-off"), "lost-lod-fallback": (("if (rules==_model_detail_rules_stock)", "if (TRUE)"), "lod-regions"), "stock-lod-fallback": (("if (rules==_model_detail_rules_stock)", "if (FALSE)"), "lod-off"), "shown-interior": (("rules==_model_detail_rules_inside ||", "TRUE ||"), "lod-interior-outside-shadow"), @@ -42,6 +45,8 @@ def generated(control=None): types += "\n" + enum_with(read("source/models/model_definitions.h"), "MODELS_GROUP_TAG") types += "\n" + enum_with(read("port/linux/game/model_detail.h"), "_model_detail_rules_stock") types += "\n" + enum_with(read("port/linux/game/model_detail.c"), "MODEL_DETAIL_INTERIOR_CUTOFF_PIXELS") + types += "\n" + next(line for line in read("port/linux/game/first_person_legs.h").splitlines() + if line.startswith("#define FIRST_PERSON_LEGS_RENDER_FLAG ")) code = read("source/rasterizer/rasterizer_transparent_enclosure.h") code += "\n" + function(raster, "rasterizer_transparent_geometry_is_enclosure") code += "\n" + function(read("port/linux/game/model_detail.c"), "model_detail_geometry_index") diff --git a/tools/harness/tests/test_viewmodel_shield.py b/tools/harness/tests/test_viewmodel_shield.py new file mode 100644 index 0000000000..70d470e3d3 --- /dev/null +++ b/tools/harness/tests/test_viewmodel_shield.py @@ -0,0 +1,129 @@ +"""The shield's flare on the first-person arms (port/linux/game/viewmodel_shield.c, display.viewmodel_shield): the +unit's modifier on the hands only, its plasma offset kept to a share of the view at the arms' distance and the +viewmodel's angle, a copy per local player, and the overshield's arms copy (overshield_effect.c).""" +import re +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from harness import CHECK_FAILED, build, enum_with, function, mutated, read, run, structure + +CASES = ["off", "on", "others", "limit", "distance", "split", "overshield", + "rasterizer-limit", "rasterizer-stock", "toggle", "replace-player"] +CONTROLS = { + # the setting ignored: the hands always get the shield + "always-on": (("if (!viewmodel_shield_enabled() || local_player_index", "if (local_player_index"), "off"), + # every plasma clamped, the weapon's and the body's too (the old code's fault) + "clamps-everything": (("if (values == viewmodel_shields[index].values)", "if (TRUE)"), "others"), + # a fixed limit, whatever the viewmodel's angle + "fov-ignored": (("(real)tan(0.5 * (double)vertical_field_of_view)", "1.0f"), "limit"), + # the root, at the eye, counted in the arms' distance + "root-counted": (("if (node->parent_node_index == NONE)\n\t\t\tcontinue;", ""), "distance"), + # only the first local player's arms known again + "one-view": (("values && index < MAXIMUM_LOCAL_PLAYERS", "values && index < 1"), "split"), + # the body's height fade on the arms + "arms-faded": (("if (values == effect->body_values && effect->top", "if (effect->top"), "overshield"), + # an overshield that is gone still drawn on the arms + "stale-arms": (("overshield_effects[index].arms_values = NULL;", ";"), "overshield"), + # the renderer no longer calls the arm-only cap after calculating displacement + "missing-rasterizer-hook": (("offset = viewmodel_shield_offset_amount(runtime->exponents, offset);", ""), + "rasterizer-limit"), +} + + +def plasma_calculation(): + """The rasterizer's actual runtime-value calculation, before GPU submission.""" + source = read("source/rasterizer/xbox/rasterizer_xbox_plasma_energy.c") + draw = function(source, "rasterizer_plasma_energy_draw") + start = draw.index("tint = global_real_rgb_white;") + end = draw.index("/* port: the selected recharge envelope", start) + return "\n".join([ + structure(source, "plasma_runtime_parameters"), + structure(source, "shader_transparent_plasma_definition"), + """static real plasma_offset(real const *values, real amount, real exponent, short offset_source) +{ + struct shader_transparent_plasma_definition definition = {0}; + struct shader_transparent_plasma_definition const *plasma = &definition; + struct plasma_runtime_parameters parameters = {NULL, values}; + struct { struct plasma_runtime_parameters const *runtime_parameters; } packet = {¶meters}; + struct plasma_runtime_parameters const *runtime; + real_rgb_color const *global_real_rgb_white = NULL; + real_rgb_color const *tint; + real intensity, offset; + short source; + """, + " definition.offset_amount = amount; definition.offset_exponent = exponent;", + " definition.offset_exponent_source = offset_source;", + draw[start:end].replace("group->runtime_parameters", "packet.runtime_parameters"), + " (void)tint; (void)intensity; return offset;\n}", + ]) + + +def define(source, name): + match = re.search(r"^#define " + re.escape(name) + r" .*$", source, re.M) + if not match: + raise LookupError(f"#define not found in the sources: {name}") + return match.group(0) + + +def per_player_state(source): + """The local players' copies, as the module declares them.""" + end = source.index("} viewmodel_shields[MAXIMUM_LOCAL_PLAYERS];") + start = source.rindex("static struct\n{", 0, end) + return source[start:end] + "} viewmodel_shields[MAXIMUM_LOCAL_PLAYERS];" + + +def generated(control=None): + shield = read("port/linux/game/viewmodel_shield.c") + overshield = read("port/linux/game/overshield_effect.c") + types = "\n".join([enum_with(overshield, "OVERSHIELD_EFFECT_MAXIMUM")] + + [define(overshield, name) for name in ["OVERSHIELD_EFFECT_ENERGY_SPEED", "OVERSHIELD_EFFECT_EDGE", + "OVERSHIELD_EFFECT_ARMS_START", + "OVERSHIELD_EFFECT_ARMS_LENGTH"]] + + [structure(overshield, "overshield_effect")]) + code = "\n".join([define(shield, "VIEWMODEL_SHIELD_STAND_OFF"), per_player_state(shield)] + + [function(overshield, name) for name in ["overshield_effect_arms_values", + "overshield_effect_find_values", "overshield_effect_draw"]] + + [function(shield, name) for name in ["viewmodel_shield_enabled", "viewmodel_shield_arms_distance", + "viewmodel_shield_maximum_offset", "viewmodel_shield_apply", + "viewmodel_shield_offset_amount"]] + + [plasma_calculation()]) + if control: + code = mutated(code, *CONTROLS[control][0]) + return (("overshield_types.inc", types), ("under_test.inc", code)) + + +@pytest.mark.parametrize("case", CASES) +def test_case(case): + status, output = run(build("viewmodel_shield", generated()), case) + assert status == 0, output + + +@pytest.mark.parametrize("control", CONTROLS) +def test_negative_control(control): + status, output = run(build("viewmodel_shield", generated(control)), CONTROLS[control][1]) + assert status == CHECK_FAILED, f"{control} escaped its check: {output}" + + +def hands_hook(source): + """Keep the actual hook between the weapon draw and the hands draw.""" + draw = function(source, "first_person_weapon_draw") + weapon, hands = list(re.finditer(r"\brender_model\(", draw)) + call = re.search(r"viewmodel_shield_apply\(\s*render\.local_player_index,\s*unit_index,\s*" + r"first_person_interface->hands\.index,\s*model_node_matrices,\s*unit_functions,\s*&model_effect\);", draw) + assert call and weapon.start() < call.start() < hands.start() + assert "viewmodel_shield_apply" not in draw[:weapon.start()] + assert "&model_effect" in draw[hands.start():] + + +def test_hands_hook(): + hands_hook(read("source/interface/first_person_weapons.c")) + + +def test_missing_hands_hook_is_detected(): + source = read("source/interface/first_person_weapons.c") + source = source.replace("viewmodel_shield_apply(", "removed_shield_apply(") + with pytest.raises(AssertionError): + hands_hook(source) diff --git a/tools/harness/tests/touch_gyro.c b/tools/harness/tests/touch_gyro.c new file mode 100644 index 0000000000..499f17225e --- /dev/null +++ b/tools/harness/tests/touch_gyro.c @@ -0,0 +1,66 @@ +#include "harness.h" +#include + +static const char *mode = "legacy"; +static double horizontal = 2.0, vertical = 0.5; +static int invert_horizontal, invert_vertical; +static const char *config_string(const char *name) { return mode; } +static double config_real(const char *name) +{ + return strstr(name, "horizontal") ? horizontal : vertical; +} +static int config_boolean(const char *name) +{ + return strstr(name, "horizontal") ? invert_horizontal : invert_vertical; +} +#define HALO_ANDROID +#include "under_test.inc" + +int main(int argc, char **argv) +{ + float yaw = 0.25f, pitch = -0.5f; + const char *test = argc > 1 ? argv[1] : ""; + if (!strcmp(test, "legacy")) + { + invert_horizontal = invert_vertical = 1; + touch_gyro_apply(&yaw, &pitch); + halo_linux_gyro_filter(0, &yaw, &pitch); + CHECK(yaw == 0.25f && pitch == -0.5f, "saved touch behavior changed"); + mode = "invalid"; + CHECK(touch_gyro_mode() == _touch_gyro_legacy, "unknown mode changed the default"); + } + else if (!strcmp(test, "modes")) + { + mode = "false"; + touch_gyro_apply(&yaw, &pitch); + CHECK(yaw == 0 && pitch == 0, "off mode passed gyro input"); + mode = "zoom"; + yaw = pitch = 1; + touch_gyro_apply(&yaw, &pitch); + halo_linux_gyro_filter(0, &yaw, &pitch); + CHECK(yaw == 0 && pitch == 0, "unzoomed motion retained"); + halo_linux_gyro_filter(1, &yaw, &pitch); + CHECK(yaw == 0 && pitch == 0, "zoom resurrected a dropped sample"); + yaw = pitch = 1; + touch_gyro_apply(&yaw, &pitch); + halo_linux_gyro_filter(1, &yaw, &pitch); + CHECK(yaw == 2 && pitch == 0.5f, "zoomed sensitivity"); + mode = "true"; + halo_linux_gyro_filter(0, &yaw, &pitch); + CHECK(yaw == 2 && pitch == 0.5f, "always mode requires zoom"); + } + else if (!strcmp(test, "axes")) + { + mode = "true"; + invert_horizontal = 1; + touch_gyro_apply(&yaw, &pitch); + CHECK(yaw == -0.5f && pitch == -0.25f, "independent axes"); + horizontal = NAN; + vertical = 11; + yaw = pitch = 1; + touch_gyro_apply(&yaw, &pitch); + CHECK(yaw == -1 && pitch == 1, "invalid sensitivity was not bounded"); + } + else CHECK(0, "unknown case"); + return 0; +} diff --git a/tools/harness/tests/transparent_enclosure.c b/tools/harness/tests/transparent_enclosure.c index b87837fee7..bd2f7efd1e 100644 --- a/tools/harness/tests/transparent_enclosure.c +++ b/tools/harness/tests/transparent_enclosure.c @@ -25,6 +25,29 @@ static struct model_region_permutation permutation; static int locks, submissions, iterator_position; static short previous[32], next[32]; static int solid_draws, shadow_draws, selected_geometry[8]; +static int legs_calls, legs_expected, legs_empty; +/* These enclosure fixtures use CLASSIC; shield override eligibility is + exercised separately by the shield-look harness. */ +static boolean shield_look_skip_shell(long object_index, struct model const *m, struct shader const *shader, boolean first_person) +{ + return FALSE; +} +static struct triangle_buffer legs_triangles; +static struct triangle_buffer const *first_person_legs_triangles(long object_index, + struct model const *m, struct vertex_buffer const *vertices, struct triangle_buffer const *triangles) +{ + legs_calls++; + CHECK(object_index == 1 && m == &model, "local object identity"); + return legs_empty ? NULL : &legs_triangles; +} +static void check_triangles(struct triangle_buffer const *triangles, long count) +{ + if (legs_expected) + CHECK(triangles == &legs_triangles && count == legs_triangles.count, + "private triangle buffer and count reach every material pass"); + else + CHECK(triangles != &legs_triangles, "stock/shadow indices unchanged"); +} static real shell[5][8] = {{-1,-1,0},{1,-1,0},{1,1,0},{-1,1,0},{0,0,2}}; static word indices[64] = {0,1,2,0,2,3,0,4,1,1,4,2,2,4,3,3,4,0}; static real sphere[6][8] = {{-.22f,0,.7f},{.22f,0,.7f},{0,-.22f,.7f},{0,.22f,.7f},{0,0,.48f},{0,0,.92f}}; @@ -38,8 +61,8 @@ static real sphere[6][8] = {{-.22f,0,.7f},{.22f,0,.7f},{0,-.22f,.7f},{0,.22f,.7f #define model_data_error(m,e) ((void)0) #define render_model_no_geometry FALSE #define matrix4x3_transform_point(m,p,o) (*(o)=*(p)) -#define rasterizer_model_draw(s,p,t,ti,tc,v,vi) (selected_geometry[solid_draws++] = (v)->count) -#define rasterizer_environment_shadow_model_draw(s,p,t,v) (selected_geometry[shadow_draws++] = (v)->count) +#define rasterizer_model_draw(s,p,t,ti,tc,v,vi) (check_triangles(t,tc), selected_geometry[solid_draws++] = (v)->count) +#define rasterizer_environment_shadow_model_draw(s,p,t,v) (check_triangles(t,(t)->count), selected_geometry[shadow_draws++] = (v)->count) #define rasterizer_debug_model_vertices(...) ((void)0) #define D3DLOCK_READONLY 128 @@ -73,6 +96,7 @@ static void rasterizer_model_transparent_geometry_submit(struct shader *shader, struct render_sort_filth *sort) { int i = submissions++; + check_triangles(triangles, triangle_count); previous[i] = next[i] = NONE; if (sort) { @@ -139,6 +163,28 @@ int main(int argc, char **argv) const char *case_name = argc > 1 ? argv[1] : "closed"; int i; initialize(); + if (!strncmp(case_name, "legs-", 5)) { + struct render_skinning skinning = {NULL, 1}; + char choices[1] = {0}; + boolean shadow = !strcmp(case_name, "legs-shadow"); + boolean disabled = !strcmp(case_name, "legs-off"); + legs_expected = !shadow && !disabled; + legs_empty = !strcmp(case_name, "legs-empty"); + legs_triangles.count = 1; + geometry.parts.count = 3; + if (!strcmp(case_name, "legs-stripped")) + for (i = 0; i < 3; i++) parts[i].flags |= FLAG(_model_geometry_part_stripped_bit); + render_model_parts(&model, choices, 1, &skinning, 1, 0, _model_detail_rules_stock, 0, + (disabled ? 0 : FIRST_PERSON_LEGS_RENDER_FLAG) | (shadow ? FLAG(_render_model_shadow_bit) : 0)); + if (!strcmp(case_name, "legs-stripped")) { + CHECK(!legs_calls && !submissions && !solid_draws, "stripped geometry never enters feature cache"); + return 0; + } + CHECK((legs_calls > 0) == legs_expected, "selection only for marked non-shadow body"); + if (legs_empty) CHECK(!submissions && !solid_draws, "omitted parts never submitted"); + else if (!shadow) CHECK(submissions == 2 && solid_draws == 1, "transparent and solid surfaces"); + return 0; + } /* display.model_detail's levels for each permutation (model_detail.c), as render_model_parts draws them: from eltanschauung's #282 */ if (!strncmp(case_name, "lod-", 4)) { diff --git a/tools/harness/tests/viewmodel_shield.c b/tools/harness/tests/viewmodel_shield.c new file mode 100644 index 0000000000..3daf881dbe --- /dev/null +++ b/tools/harness/tests/viewmodel_shield.c @@ -0,0 +1,267 @@ +/* The shield's flare on the first-person arms (port/linux/game/viewmodel_shield.c) and the +overshield's arms copy (port/linux/game/overshield_effect.c) */ +#include "harness.h" +#include +#define NUMBEROF(a) (sizeof(a) / sizeof((a)[0])) +#define MIN(a, b) ((a) < (b) ? (a) : (b)) +#define MAX(a, b) ((a) > (b) ? (a) : (b)) +#define PIN(x, lo, hi) MIN(MAX((x), (lo)), (hi)) +#define csmemcpy memcpy +#define MAXIMUM_LOCAL_PLAYERS 4 +#define MAXIMUM_NODES_PER_ANIMATION 64 +#define NUMBER_OF_OUTGOING_OBJECT_FUNCTIONS 4 +#define TAG_BLOCK_GET_ELEMENT(block, index, type) (&((type *)(block)->address)[index]) +typedef struct { real red, green, blue; } real_rgb_color; +typedef struct { real scale; real_vector3d forward, left, up; real_point3d position; } real_matrix4x3; +struct tag_block { long count; void *address; }; +struct model_node { short parent_node_index; }; +struct model { struct tag_block nodes; }; +struct shader { struct { short type; } base; }; +struct render_animation { real_rgb_color const *colors; real const *values; }; +struct render_model_effect { struct shader *modifier_shader; struct render_animation modifier_animation; }; +struct object_definition { struct { struct { long index; } modifier_shader; } object; }; +struct unit_datum +{ + long definition_index; + struct { real outgoing_function_values[4]; real_rgb_color outgoing_change_colors[4]; } object; +}; + +static struct { struct { real_point3d position; } camera; } render; +static struct { struct { real vertical_field_of_view; } camera; } global_window_parameters; +static struct { real first_person_weapon_near_clip_distance; } rasterizer_globals = {0.01f}; +static int setting; +static int config_boolean(const char *name) { (void)name; return setting; } +static unsigned long config_changes(void) { static unsigned long changes; return ++changes; } + +static struct unit_datum units[2]; +static struct object_definition definition = {{{7}}}; +static struct shader plasma = {{10}}; +static int valid_modifier = 1; +static struct model hands; +static struct unit_datum *unit_get(long index) { return &units[index]; } +static struct object_definition *object_definition_get(long index) { (void)index; return &definition; } +static struct shader *shader_definition_get(long index) { (void)index; return &plasma; } +static boolean shader_type_is_valid_for_modifier(short type) { (void)type; return valid_modifier; } +static struct model *model_definition_get(long index) { (void)index; return &hands; } +static real distance3d(real_point3d const *a, real_point3d const *b) +{ + return sqrtf((a->x - b->x) * (a->x - b->x) + (a->y - b->y) * (a->y - b->y) + (a->z - b->z) * (a->z - b->z)); +} + +/* the overshield's state, as overshield_effect_get would leave it */ +#include "overshield_types.inc" +static struct overshield_effect overshield_effects[OVERSHIELD_EFFECT_MAXIMUM]; +static struct overshield_effect *overshield_unit[2]; +static int overshield_setting = 1; +static boolean overshield_effect_enabled(void) { return overshield_setting; } +static struct overshield_effect *overshield_effect_get(long unit_index) { return overshield_unit[unit_index]; } +static short overshield_effect_intensity_source(long unit_index) { (void)unit_index; return 1; } +#include "under_test.inc" + +static struct model_node hand_nodes[3] = {{NONE}, {0}, {1}}; +static real_matrix4x3 matrices[3]; + +static void arms_at(real distance) +{ + hands.nodes.count = 3; + hands.nodes.address = hand_nodes; + matrices[0].position.x = 0; /* (the root, at the eye) */ + matrices[1].position.x = distance; + matrices[2].position.x = distance; +} + +static struct render_model_effect drawn(short local, long unit) +{ + struct render_model_effect effect = {0}; + viewmodel_shield_apply(local, unit, 3, matrices, units[unit].object.outgoing_function_values, &effect); + return effect; +} + +int main(int argc, char **argv) +{ + char const *case_name = argc > 1 ? argv[1] : ""; + real const half_tan_60 = 0.57735027f; /* tan(30 degrees) */ + units[0].object.outgoing_function_values[1] = 0.5f; + global_window_parameters.camera.vertical_field_of_view = 1.0471976f; /* 60 degrees */ + arms_at(0.2f); + CASE("off") { + struct render_model_effect effect; + setting = 0; + effect = drawn(0, 0); + CHECK(!effect.modifier_shader && !effect.modifier_animation.values, "off, the hands' effect is untouched"); + CHECK(viewmodel_shield_offset_amount(units[0].object.outgoing_function_values, 0.5f) == 0.5f, + "anything's offset is its own"); + CHECK(viewmodel_shield_offset_amount(NULL, 0.25f) == 0.25f, "no values, its own"); + } + CASE("on") { + struct render_model_effect effect; + setting = 1; + effect = drawn(0, 0); + CHECK(effect.modifier_shader == &plasma, "the unit's modifier shader on the hands"); + CHECK(effect.modifier_animation.colors == units[0].object.outgoing_change_colors, "the unit's colors"); + CHECK(effect.modifier_animation.values != units[0].object.outgoing_function_values, "a copy of its values"); + CHECK(effect.modifier_animation.values[1] == 0.5f, "the unit's values, copied"); + { + real picture_values[4] = {0.f, 0.75f, 0.f, 0.f}; + viewmodel_shield_apply(0, 0, 3, matrices, picture_values, &effect); + picture_values[1] = 0.f; + CHECK(effect.modifier_animation.values[1] == 0.75f, "queued arms keep picture values, not tick values or temporary storage"); + } + valid_modifier = 0; + effect = drawn(1, 0); + CHECK(!effect.modifier_shader, "a shader that can't modify is not used"); + valid_modifier = 1; + definition.object.modifier_shader.index = NONE; + effect = drawn(1, 0); + CHECK(!effect.modifier_shader, "a unit without a modifier shader has none on its hands"); + definition.object.modifier_shader.index = 7; + effect = drawn(-1, 0); + CHECK(!effect.modifier_shader, "no local player"); + effect = drawn(MAXIMUM_LOCAL_PLAYERS, 0); + CHECK(!effect.modifier_shader, "a local player out of range"); + } + CASE("others") { + real body[4] = {0}; + setting = 1; + (void)drawn(0, 0); + CHECK(viewmodel_shield_offset_amount(units[0].object.outgoing_function_values, 0.5f) == 0.5f, + "the body's flare keeps its offset"); + CHECK(viewmodel_shield_offset_amount(body, 0.5f) == 0.5f, "a weapon's plasma keeps its offset"); + } + CASE("limit") { + struct render_model_effect effect; + real limit; + setting = 1; + effect = drawn(0, 0); + limit = VIEWMODEL_SHIELD_STAND_OFF * 0.2f * half_tan_60; + CHECK(fabsf(viewmodel_shield_offset_amount(effect.modifier_animation.values, 0.5f) - limit) < 1e-6f, + "at most the share of half the view at the arms' distance (%g)", limit); + CHECK(viewmodel_shield_offset_amount(effect.modifier_animation.values, limit / 2) == limit / 2, + "a smaller offset is its own"); + global_window_parameters.camera.vertical_field_of_view = 0.5f; + CHECK(viewmodel_shield_offset_amount(effect.modifier_animation.values, 0.5f) < limit, + "a narrower viewmodel angle, a smaller offset"); + global_window_parameters.camera.vertical_field_of_view = 2.0f; + CHECK(viewmodel_shield_offset_amount(effect.modifier_animation.values, 0.5f) > limit, + "a wider one, a larger offset"); + } + CASE("distance") { + struct render_model_effect effect; + real limit; + setting = 1; + arms_at(0.4f); + effect = drawn(0, 0); + limit = VIEWMODEL_SHIELD_STAND_OFF * 0.4f * half_tan_60; + CHECK(fabsf(viewmodel_shield_offset_amount(effect.modifier_animation.values, 0.5f) - limit) < 1e-6f, + "the arms' distance, past the root at the eye"); + arms_at(0.f); + effect = drawn(0, 0); + limit = VIEWMODEL_SHIELD_STAND_OFF * 0.01f * half_tan_60; + CHECK(fabsf(viewmodel_shield_offset_amount(effect.modifier_animation.values, 0.5f) - limit) < 1e-7f, + "no nearer than the first-person near clip"); + } + CASE("split") { + struct render_model_effect first, second; + setting = 1; + arms_at(0.2f); + first = drawn(0, 0); + arms_at(0.4f); + second = drawn(1, 1); + CHECK(first.modifier_animation.values != second.modifier_animation.values, "each local player's own copy"); + CHECK(fabsf(viewmodel_shield_offset_amount(first.modifier_animation.values, 0.5f) - + VIEWMODEL_SHIELD_STAND_OFF * 0.2f * half_tan_60) < 1e-6f, "the first view's arms at their distance"); + CHECK(fabsf(viewmodel_shield_offset_amount(second.modifier_animation.values, 0.5f) - + VIEWMODEL_SHIELD_STAND_OFF * 0.4f * half_tan_60) < 1e-6f, "the second view's at theirs"); + } + CASE("overshield") { + struct render_model_effect effect; + real speed, softness, height; + setting = 1; + overshield_effects[0].unit_index = 0; + overshield_effects[0].progress = 0.f; + overshield_effects[0].bottom = 0.f; + overshield_effects[0].top = 2.f; + overshield_unit[0] = &overshield_effects[0]; + effect = drawn(0, 0); + CHECK(effect.modifier_animation.values[1] == 0.f, "the rise has not reached the arms"); + CHECK(overshield_effect_draw(effect.modifier_animation.values, &speed, &softness, &height), + "the overshield knows the arms' copy"); + CHECK(softness == 0.f && height == 0.f, "the arms come up whole, without the body's fade"); + CHECK(speed == OVERSHIELD_EFFECT_ENERGY_SPEED, "its energy's speed"); + overshield_effects[0].progress = 1.f; + effect = drawn(0, 0); + CHECK(effect.modifier_animation.values[1] == 1.f, "risen, the arms are lit whole"); + CHECK(fabsf(viewmodel_shield_offset_amount(effect.modifier_animation.values, 0.5f) - + VIEWMODEL_SHIELD_STAND_OFF * 0.2f * half_tan_60) < 1e-6f, "and still kept close"); + /* (the unit's overshield gone: the copy is the unit's again, not the overshield's) */ + overshield_unit[0] = NULL; + effect = drawn(0, 0); + CHECK(effect.modifier_animation.values[1] == 0.5f, "without an overshield, the unit's own values"); + CHECK(!overshield_effect_draw(effect.modifier_animation.values, &speed, &softness, &height), + "the overshield no longer draws on these arms"); + overshield_unit[0] = &overshield_effects[0]; + overshield_setting = 0; + effect = drawn(0, 0); + CHECK(!overshield_effect_draw(effect.modifier_animation.values, &speed, &softness, &height), + "nor with display.overshield_effect off"); + } + CASE("rasterizer-limit") { + struct render_model_effect effect; + real maximum = VIEWMODEL_SHIELD_STAND_OFF * 0.2f * half_tan_60; + setting = 1; + units[0].object.outgoing_function_values[0] = 2.f; + effect = drawn(0, 0); + CHECK(fabsf(plasma_offset(effect.modifier_animation.values, 0.5f, 1.f, 1) - maximum) < 1e-7f, + "the final displacement is capped after a function value above one"); + CHECK(fabsf(plasma_offset(effect.modifier_animation.values, 0.5f, 2.f, 1) - maximum) < 1e-7f, + "the exponent cannot multiply the displacement past the cap"); + units[0].object.outgoing_function_values[0] = 0.25f; + effect = drawn(0, 0); + CHECK(fabsf(plasma_offset(effect.modifier_animation.values, maximum * 2.f, 1.f, 1) - + maximum * 0.5f) < 1e-7f, "a final displacement below the cap retains its authored size"); + CHECK(plasma_offset(effect.modifier_animation.values, 0.5f, 1.f, 0) == 0.f, + "an absent offset source keeps the stock zero displacement"); + } + CASE("rasterizer-stock") { + real body[4] = {2.f, 0.f, 0.f, 0.f}; + setting = 1; + (void)drawn(0, 0); + CHECK(plasma_offset(body, 0.5f, 2.f, 1) == 2.f, "body and weapon plasma keep their final displacement"); + CHECK(plasma_offset(NULL, 0.5f, 2.f, 1) == 0.f, "no runtime values keep the stock displacement"); + setting = 0; + CHECK(plasma_offset(body, 0.5f, 2.f, 1) == 2.f, "disabled, the stock calculation is unchanged"); + } + CASE("toggle") { + struct render_model_effect effect; + setting = 1; + effect = drawn(0, 0); + CHECK(effect.modifier_shader == &plasma, "enabled"); + setting = 0; + effect = drawn(0, 0); + CHECK(!effect.modifier_shader && !effect.modifier_animation.values, "disabling stops submission"); + units[0].object.outgoing_function_values[1] = 0.75f; + setting = 1; + effect = drawn(0, 0); + CHECK(effect.modifier_animation.values[1] == 0.75f, "reenabling copies the current values"); + } + CASE("replace-player") { + struct render_model_effect previous, current; + real speed, softness, height; + setting = 1; + overshield_effects[0].unit_index = 0; + overshield_effects[0].progress = 1.f; + overshield_unit[0] = &overshield_effects[0]; + previous = drawn(0, 0); + CHECK(overshield_effect_draw(previous.modifier_animation.values, &speed, &softness, &height), + "the previous player's overshield owns this view's values"); + units[1].object.outgoing_function_values[1] = 0.25f; + arms_at(0.4f); + current = drawn(0, 1); + CHECK(current.modifier_animation.values[1] == 0.25f, "a replacement unit supplies its own values"); + CHECK(!overshield_effect_draw(current.modifier_animation.values, &speed, &softness, &height), + "reusing a local slot cannot retain the previous unit's overshield"); + CHECK(fabsf(viewmodel_shield_offset_amount(current.modifier_animation.values, 0.5f) - + VIEWMODEL_SHIELD_STAND_OFF * 0.4f * half_tan_60) < 1e-6f, "the replacement's pose supplies its distance"); + } + return 0; +} diff --git a/tools/hud_assets.py b/tools/hud_assets.py index daffef18b4..0a946c2f49 100644 --- a/tools/hud_assets.py +++ b/tools/hud_assets.py @@ -336,6 +336,13 @@ def hek_bitmap_group(path: Path) -> dict: def render_svg(svg: Path, zoom: float = 1) -> np.ndarray: + if not shutil.which("rsvg-convert"): + # Windows asset builds can use the same standalone SVG renderer + # without installing GTK. Both paths rasterize authored SVG only. + import io + import resvg_py + return np.asarray(Image.open(io.BytesIO(resvg_py.svg_to_bytes( + svg_path=str(svg), zoom=zoom))).convert("RGBA")).copy() with tempfile.TemporaryDirectory() as directory: output = Path(directory) / "render.png" subprocess.run(["rsvg-convert", "-z", str(zoom), "-o", str(output), str(svg)], check=True) diff --git a/tools/hud_corrections.py b/tools/hud_corrections.py index acb232023b..a9bfc26a6f 100644 --- a/tools/hud_corrections.py +++ b/tools/hud_corrections.py @@ -5,6 +5,7 @@ """ import json from PIL import Image +import button_assets import hud_assets ASSETS = hud_assets.ASSETS diff --git a/tools/lighting_compatibility_build.py b/tools/lighting_compatibility_build.py new file mode 100644 index 0000000000..f604019e9d --- /dev/null +++ b/tools/lighting_compatibility_build.py @@ -0,0 +1,50 @@ +"""Build a passive Windows multiplayer policy probe, then restore the normal build.""" +import hashlib +import json +from pathlib import Path +import re +import shlex +import shutil +import subprocess +import sys + +ROOT = Path(__file__).resolve().parents[1] + + +def main(): + output = ROOT/'build/lighting-compatibility-build' + output.mkdir(exist_ok=True) + fixture = ROOT/'port/linux/game/lighting_compatibility_fixture.c' + assert not fixture.exists() + target = ROOT/'port/linux/game/plasma_lighting.c' + original = target.read_bytes() + args = shlex.split(re.search(r'^configure_args = (.*)$', (ROOT/'build.ninja').read_text(), re.M)[1]) + manifest = dict(revision=subprocess.check_output(['git','rev-parse','HEAD'],text=True,cwd=ROOT).strip(), + configure_args=args, source_sha256=hashlib.sha256(original).hexdigest(), + fixture_sha256=hashlib.sha256((ROOT/'tools/fixtures/lighting_compatibility.c').read_bytes()).hexdigest()) + manifest['emitter_hashes'] = {name: hashlib.sha256((ROOT/'port/linux/game'/name).read_bytes()).hexdigest() + for name in ('authored_emitter_lighting.c', 'ambient_emitter_lighting.c', + 'covenant_emitter_lighting.c', 'lighting_menu.c', 'lighting_config.c', + 'plasma_collision.c', 'plasma_occlusion.c')} + manifest['collision_hashes'] = {name: hashlib.sha256((ROOT/'source/physics'/name).read_bytes()).hexdigest() + for name in ('collision_bsp.c', 'collision_bsp.h')} + try: + text = original.decode().replace('\r\n','\n') + anchor = '\tshield_glow_frame_end();' + assert text.count(anchor)==1 + target.write_text('void lighting_compatibility_sample(void);\n'+text.replace(anchor,'\tlighting_compatibility_sample();\n'+anchor)) + shutil.copyfile(ROOT/'tools/fixtures/lighting_compatibility.c',fixture) + subprocess.run([sys.executable,'configure.py',*args],cwd=ROOT,check=True) + subprocess.run(['ninja','windows'],cwd=ROOT,check=True) + shutil.copy2(ROOT/'build/windows/halo.exe',output/'halo-compatibility.exe') + manifest['executable_sha256']=hashlib.sha256((output/'halo-compatibility.exe').read_bytes()).hexdigest() + (output/'manifest.json').write_text(json.dumps(manifest,indent=2)) + finally: + target.write_bytes(original) + fixture.unlink(missing_ok=True) + subprocess.run([sys.executable,'configure.py',*args],cwd=ROOT,check=True) + subprocess.run(['ninja','windows'],cwd=ROOT,check=True) + + +if __name__=='__main__': + main() diff --git a/tools/lighting_compatibility_run.py b/tools/lighting_compatibility_run.py new file mode 100644 index 0000000000..a5e06f8cce --- /dev/null +++ b/tools/lighting_compatibility_run.py @@ -0,0 +1,157 @@ +"""Rendered, isolated two-peer Windows lighting compatibility scenarios. + +Uses the engine's existing join, damage, pickup and respawn test controls. +Retail maps stay local; the runner removes staged maps and archives test saves. +""" +import argparse +import csv +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import time +from types import SimpleNamespace +from lighting_performance_run import cleanup, LIGHTS +from net_compare import parse_log, judge_run, TOLERANCES + +ROOT=Path(__file__).resolve().parents[1] +CASES={ + 'xbox': ('bloodgulch',1,'glow_overshield',1), + 'ce': ('custom_maps\\deathisland',0,'stock',1), + 'mcc': ('mcc_maps\\DigsiteMP\\1',1,'players',1), + 'late': ('bloodgulch',0,'players',32), +} +# A combat/death cue can remove the unit before the scripted cue executes. +# The health query safely returns -1 for NONE; unit_kill requires a live unit. +DEATH_CUE = 'if (> (unit_get_health (unit (list_get (players) 1))) 0) (unit_kill (unit (list_get (players) 1)))' + + +def report_passed(result): + peers=result['peers'] + if set(peers)!= {'host','client'}:return False + for peer in peers.values(): + if not (peer['exit']==0 and not peer['forced_stop'] and peer['two_player_samples']>10 and + sum(peer['respawns'].values())>0 and any(len(v)>1 for v in peer['inventories'].values()) and + peer['policy_samples']>5 and peer['correct_policy_samples']==peer['policy_samples'] and + peer['config_verified'] and not peer['failures']):return False + # HSC's players-list order is not the network log's player index order. + # Require both peers to observe a respawn of the same network player. + respawned=[{str(k) for k,v in p['respawns'].items() if v>0} for p in peers.values()] + if not respawned[0].intersection(respawned[1]):return False + if result['agreement']['problems'] or result['agreement']['divergences']:return False + if result['case']=='late': + # Late join can phase-shift the once-a-second snapshots beyond the + # comparator's two-tick window. This case covers joining/lifecycle and + # host-measured synchronous drift, not paired snapshot equivalence. + return peers['host']['one_player_samples']>5 and (peers['host']['first_two_player_tick'] or 0)>300 + return result['agreement']['figures']['seconds']>10 + + +def main(): + parser=argparse.ArgumentParser(description=__doc__) + parser.add_argument('--data-root',type=Path,required=True) + parser.add_argument('--case',choices=CASES,required=True) + parser.add_argument('--label',help='Unique evidence folder for a revised scenario') + args=parser.parse_args() + level,host_enabled,policy,delay=CASES[args.case] + label=args.label or args.case + assert re.fullmatch(r'[A-Za-z0-9_-]+',label) + base=(ROOT/'build/lighting-compatibility'/label).resolve() + assert base.is_relative_to((ROOT/'build').resolve()) + base.mkdir(parents=True,exist_ok=False) + build=ROOT/'build/lighting-compatibility-build' + manifest=json.loads((build/'manifest.json').read_text()) + assert hashlib.sha256((build/'halo-compatibility.exe').read_bytes()).hexdigest()==manifest['executable_sha256'] + assert hashlib.sha256((ROOT/'port/linux/game/plasma_lighting.c').read_bytes()).hexdigest()==manifest['source_sha256'] + copies=['maps/ui.map','maps/bloodgulch.map','maps/carousel.map'] + if args.case=='ce':copies += ['custom_maps/'+n+'.map' for n in ('deathisland','bitmaps','sounds','loc')] + if args.case=='mcc':copies += ['mcc_maps/DigsiteMP/'+n+'.map' for n in ('1','bitmaps','sounds')] + children={};handles=[];settings={};forced={};outputs=[] + # Stage both peers before starting the host; copy time must not consume its join window. + try: + for role in ('host','client'): + out=base/role;out.mkdir();outputs.append(out) + for name in copies: + target=out/name;target.parent.mkdir(parents=True,exist_ok=True) + shutil.copy2(args.data_root/name,target) + (out/'screenshots').mkdir() + shutil.copy2(build/'halo-compatibility.exe',out/'halo-performance.exe') + shutil.copy2(ROOT/'build/windows/SDL3.dll',out/'SDL3.dll') + shutil.copy2(build/'manifest.json',out/'build-manifest.json') + enabled=host_enabled if role=='host' else 1-host_enabled + display={key:bool(enabled) for key in LIGHTS} + display.update(overshield_effect=bool(enabled),per_pixel_lighting=True,shield_glow_intensity='default') + settings[role]=display + (out/'config.toml').write_text('[display]\n'+''.join(f'{k} = {json.dumps(v)}\n' for k,v in display.items())) + started=time.monotonic() + for role,address,peer in (('host','127.0.0.232','127.0.0.233'),('client','127.0.0.233','127.0.0.232')): + if role=='client':time.sleep(delay) + out=base/role + env={k:v for k,v in os.environ.items() if not k.startswith('HALO_')} + env.update(HALO_DATA_ROOT=str(out),HALO_SAVE_ROOT=str(out/'saves'),HALO_HIDDEN_WINDOW='1', + HALO_WINDOW_SIZE='1280x720',HALO_NO_AUDIO='1',HALO_MAX_FPS='60',HALO_NO_VSYNC='1', + HALO_EXIT_AFTER=str(110 if role=='host' else 106-delay),HALO_NET_ONLINE='0', + HALO_NET_PUBLIC_LOBBY='0',HALO_NET_ALLOW_UPNP='0',HALO_NET_JOIN_FROM_CLIPBOARD='0', + HALO_NET_ADDRESS=address,HALO_NET_BROADCAST=peer, + HALO_NETWORK_TEST='host:'+level if role=='host' else 'join',HALO_NETWORK_TEST_START='12', + HALO_NETWORK_TEST_SCORE='10000',HALO_NETWORK_TEST_SHOOT='7',HALO_NETWORK_TEST_KILL='25', + HALO_NETWORK_TEST_PICKUP='12',HALO_NETWORK_TEST_PICKUP_WEAPON='', + HALO_NETWORK_TEST_CUE_PLAYERS='2', + HALO_NETWORK_TEST_CUES=f'30 {DEATH_CUE}|60 {DEATH_CUE}' if role=='host' else '', + HALO_NETWORK_TEST_NAME='LightingHost' if role=='host' else 'LightingPeer', + HALO_TEST_INPUT='look:1' if role=='host' else 'look:2', + HALO_NET_SHIELD_EFFECTS=policy if role=='host' else ('stock' if policy!='stock' else 'glow_overshield'), + HALO_UPDATE_ANSWER='never',HALO_CRASH_REPORTS='no', + HALO_SCREENSHOT_DIR=str(out/'screenshots'),HALO_SCREENSHOT_EVERY='1800') + (out/'test-settings.json').write_text(json.dumps(dict(display=settings[role],environment={k:v for k,v in env.items() if k.startswith('HALO_')}),indent=2)) + stdout=(out/'stdout.log').open('wb');stderr=(out/'stderr.log').open('wb');handles += [stdout,stderr] + children[role]=subprocess.Popen([str(out/'halo-performance.exe')],cwd=out,env=env, + stdout=stdout,stderr=stderr,creationflags=subprocess.CREATE_NO_WINDOW) + while any(p.poll() is None for p in children.values()) and time.monotonic()-started<150:time.sleep(.25) + finally: + for role,p in children.items(): + forced[role]=p.poll() is None + if forced[role]:p.terminate();p.wait(timeout=10) + for handle in handles:handle.close() + for out in outputs:cleanup(out) + result=dict(case=args.case,level=level,policy=policy,join_delay=delay,peers={}) + for role,p in children.items(): + out=base/role;log=(out/'stderr.log').read_text(errors='replace') + samples,names,errors=parse_log(out/'stderr.log') + rows=list(samples.values());both=[r for r in rows if len(r['players'])==2] + inventories={};respawns={} + for player in (0,1): + states=[r['players'][player] for r in rows if player in r['players']] + inventories[player]=sorted(set(tuple(w[0] for w in s.get('weapons',[])) for s in states if s['alive'])) + respawns[player]=sum(not a['alive'] and b['alive'] for a,b in zip(states,states[1:])) + policy_rows=[] + if (out/'lighting-policy.csv').exists(): + with (out/'lighting-policy.csv').open() as f:policy_rows=[{k:int(v) for k,v in r.items()} for r in csv.DictReader(f)] + stable=[r for r in policy_rows if r['tick']>600] + expected_policy={'stock':0,'glow_overshield':4,'players':-1}[policy] + expected_shield=int(settings[role]['shield_glow']) if policy=='players' else int(policy!='stock') + correct=[r for r in stable if r['policy']==expected_policy and r['shield_enabled']==expected_shield] + failures=errors+re.findall(r'(?im)^.*(?:crash: exception|exception halt|assertion failed|shader.*(?:error|failed)|GL_INVALID).*$',log) + debug=(out/'debug.txt').read_text(errors='replace') if (out/'debug.txt').exists() else '' + failures += re.findall(r'(?im)^.*(?:i expected a function name|not while playing in another).*$',debug) + config_paths=re.findall(r'^halo-linux: settings: ([^\r\n]*config\.toml)\s*$',log,re.M) + config_ok=bool(config_paths) and all(Path(v.strip()).resolve()==(out/'config.toml').resolve() for v in config_paths) + result['peers'][role]=dict(exit=p.returncode,forced_stop=forced[role],two_player_samples=len(both), + one_player_samples=sum(len(r['players'])==1 for r in rows), + first_two_player_tick=both[0]['tick'] if both else None,respawns=respawns,inventories=inventories, + shoot_events=log.count('shoots player'),kill_events=log.count('first player kills'), + pickup_events=log.count('stands on weapon'),policy_samples=len(stable),correct_policy_samples=len(correct), + policy_values=sorted(set(r['policy'] for r in stable)),config_verified=config_ok,failures=failures) + result['agreement']=judge_run(base/'host/stderr.log',base/'client/stderr.log',SimpleNamespace(seconds=45,skip=8),TOLERANCES) + result['paired_snapshot_seconds']=result['agreement'].get('figures',{}).get('seconds',0) + result['passed']=report_passed(result) + (base/'report.json').write_text(json.dumps(result,indent=2)) + print(json.dumps(result,indent=2),flush=True) + return 0 if result['passed'] else 1 + + +if __name__=='__main__': + raise SystemExit(main()) diff --git a/tools/lighting_compatibility_transitions.py b/tools/lighting_compatibility_transitions.py new file mode 100644 index 0000000000..54ef62f338 --- /dev/null +++ b/tools/lighting_compatibility_transitions.py @@ -0,0 +1,117 @@ +"""Exercise Xbox -> MCC -> CE -> Xbox in one isolated Windows process. + +Requires local retail data and an existing profile folder; neither is committed. +Build the passive probe with lighting_compatibility_build.py first. +""" +import argparse +import csv +import hashlib +import json +import os +from pathlib import Path +import shutil +import socket +import subprocess +import time + +from lighting_compatibility_run import ROOT +from lighting_performance_run import cleanup, LIGHTS + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--data-root', type=Path, required=True) + parser.add_argument('--profile-root', type=Path, required=True) + parser.add_argument('--enabled', type=int, choices=(0, 1), required=True) + args = parser.parse_args() + enabled = args.enabled + out = (ROOT/'build/lighting-compatibility'/f'transitions-{enabled}').resolve() + assert out.is_relative_to((ROOT/'build').resolve()) + out.mkdir(parents=True, exist_ok=False) + build = ROOT/'build/lighting-compatibility-build' + manifest = json.loads((build/'manifest.json').read_text()) + assert hashlib.sha256((build/'halo-compatibility.exe').read_bytes()).hexdigest() == manifest['executable_sha256'] + process = connection = None + transcript = '' + sent = [] + commands = [(30, '(map_name "mcc_maps\\Mercury 1 & 2\\mercury_falling")'), + (64, '(map_name custom_maps\\deathisland)'), + (90, '(map_name levels\\test\\bloodgulch\\bloodgulch)')] + try: + for folder, names in [('maps', ['ui', 'c40', 'bloodgulch']), + ('custom_maps', ['deathisland', 'bitmaps', 'sounds', 'loc']), + ('mcc_maps/Mercury 1 & 2', ['mercury_falling', 'bitmaps', 'sounds'])]: + for name in names: + target = out/folder/(name+'.map') + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(args.data_root/folder/(name+'.map'), target) + assert args.profile_root.is_dir() + for src in args.profile_root.rglob('*'): + if src.is_file() and src.suffix != '.map': + target = out/'saves'/src.relative_to(args.profile_root) + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(src, target) + (out/'screenshots').mkdir() + shutil.copy2(build/'halo-compatibility.exe', out/'halo-performance.exe') + shutil.copy2(build/'manifest.json', out/'build-manifest.json') + shutil.copy2(ROOT/'build/windows/SDL3.dll', out/'SDL3.dll') + settings = {key: bool(enabled) for key in LIGHTS} + settings.update(overshield_effect=bool(enabled), per_pixel_lighting=True, shield_glow_intensity='default') + (out/'config.toml').write_text('[display]\n'+''.join(f'{k} = {json.dumps(v)}\n' for k, v in settings.items())) + (out/'init.txt').write_text('map_name levels\\c40\\c40\n') + port = 24041+enabled + env = {k: v for k, v in os.environ.items() if not k.startswith('HALO_')} + env.update(HALO_DATA_ROOT=str(out), HALO_SAVE_ROOT=str(out/'saves'), HALO_HIDDEN_WINDOW='1', + HALO_NO_AUDIO='1', HALO_MAX_FPS='60', HALO_NO_VSYNC='1', HALO_EXIT_AFTER='118', + HALO_NET_ONLINE='0', HALO_NET_PUBLIC_LOBBY='0', HALO_NET_JOIN_FROM_CLIPBOARD='0', + HALO_NET_ALLOW_UPNP='0', HALO_UPDATE_ANSWER='never', HALO_CRASH_REPORTS='no', + HALO_TELNET_CONSOLE='1', HALO_TELNET_CONSOLE_PORT=str(port), HALO_WINDOW_SIZE='1280x720', + HALO_SCREENSHOT_DIR=str(out/'screenshots'), HALO_SCREENSHOT_EVERY='900', HALO_NETWORK_TEST='log') + (out/'test-settings.json').write_text(json.dumps(dict(display=settings, + environment={k: v for k, v in env.items() if k.startswith('HALO_')}), indent=2)) + start = time.monotonic() + with (out/'stdout.log').open('wb') as stdout, (out/'stderr.log').open('wb') as stderr: + process = subprocess.Popen([str(out/'halo-performance.exe')], cwd=out, env=env, + stdout=stdout, stderr=stderr, creationflags=subprocess.CREATE_NO_WINDOW) + while process.poll() is None and time.monotonic()-start < 150: + try: + if connection is None: + connection = socket.create_connection(('127.0.0.1', port), .1) + connection.settimeout(.01) + transcript += connection.recv(65536).decode('latin1') + except OSError: + pass + if connection: + for at, command in commands: + if time.monotonic()-start >= at and at not in sent: + connection.sendall((command+'\r\n').encode()) + sent.append(at) + time.sleep(.15) + finally: + if connection: + connection.close() + forced = process is not None and process.poll() is None + if forced: + process.terminate() + process.wait(10) + (out/'console.log').write_text(transcript) + cleanup(out) + log = (out/'debug.txt').read_text(errors='replace') + with (out/'lighting-policy.csv').open() as stream: + rows = [{k: int(v) for k, v in row.items()} for row in csv.DictReader(stream)] + report = dict(enabled=enabled, exit=process.returncode, forced=forced, commands=sent, + mcc_loads=log.count('mcc: loaded'), ce_loads=log.count('custom edition: loading'), + tick_resets=sum(b['tick'] < a['tick'] for a, b in zip(rows, rows[1:])), + policy_values=sorted({r['policy'] for r in rows}), + shield_values=sorted({r['shield_enabled'] for r in rows}), + screenshots=len(list((out/'screenshots').glob('*.png'))), exceptions=log.count('EXCEPTION')) + report['passed'] = (report['exit'] == 0 and not forced and len(sent) == 3 and + report['mcc_loads'] == 1 and report['ce_loads'] == 1 and + report['tick_resets'] >= 3 and report['shield_values'] == [enabled] and not report['exceptions']) + (out/'report.json').write_text(json.dumps(report, indent=2)) + print(json.dumps(report), flush=True) + return 0 if report['passed'] else 1 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tools/lighting_performance_build.py b/tools/lighting_performance_build.py new file mode 100644 index 0000000000..0048f93dab --- /dev/null +++ b/tools/lighting_performance_build.py @@ -0,0 +1,273 @@ +"""Build passive timing instrumentation; restore every production source afterwards.""" +import argparse +import hashlib +import json +from pathlib import Path +import re +import shlex +import shutil +import subprocess +import sys +from lighting_trace_check import instrument, instrument_collision +from harness import function + +ROOT = Path(__file__).resolve().parents[1] + + +def instrument_renderer_profile(text): + # Time unchanged bodies, including early returns. These inclusive timers + # overlap lighting's field/binding phases; do not add them together. + for name, phase, signature, call, result in [ + ('prepare_draw', 4, 'BOOL immediate', 'immediate', 'struct program_entry *'), + ('buffer_upload', 6, 'GLenum target, unsigned long offset, unsigned long size, const void *data', + 'target, offset, size, data', 'void'), + ]: + body = function(text, name) + renamed = body.replace(name+'(', 'lighting_timed_'+name+'(', 1) + wrapper = f'\nstatic {result} {name}({signature})\n{{\n' + if result != 'void': wrapper += f'\t{result} value;\n' + wrapper += f'\tlighting_profile_begin({phase});\n' + wrapper += '\t' + ('value = ' if result != 'void' else '') + f'lighting_timed_{name}({call});\n' + wrapper += f'\tlighting_profile_end({phase});\n' + if result != 'void': wrapper += '\treturn value;\n' + text = text.replace(body, renamed+wrapper+'}\n', 1) + return text + + +def instrument_shader_stalls(text): + # Desktop program_get links directly when its binary cache misses; + # xgpu_link_program alone no longer covers gameplay shader links. + for kind, call, status in [ + (0, 'glCompileShader(shader);', 'glGetShaderiv(shader, GL_COMPILE_STATUS, &status);'), + (1, 'glLinkProgram(program);', 'glGetProgramiv(program, GL_LINK_STATUS, &status);'), + (1, 'glLinkProgram(entry->program);', 'glGetProgramiv(entry->program, GL_LINK_STATUS, &status);'), + ]: + assert text.count(call) == 1 + start = text.index(call) + # The binary-cache loader also checks GL_LINK_STATUS. Time only + # the status query following this compile/link operation. + end = text.index(status, start) + len(status) + text = (text[:start] + f'lighting_stall_shader_begin({kind});\n\t' + + text[start:end] + f'\n\tlighting_stall_shader_end({kind});' + text[end:]) + return text + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--output-dir', type=Path, default=ROOT/'build/lighting-performance-build') + parser.add_argument('--profile', action='store_true', help='CPU phase timers and asynchronous sampled GPU draw queries') + parser.add_argument('--diagnose', action='store_true', help='Collision phase timings and retained resource counts (not acceptance timings)') + parser.add_argument('--resources', action='store_true', help='Retained resource counts without per-ray diagnostic clocks') + parser.add_argument('--stalls', action='store_true', help='Windows thread CPU and shader compile/link timings; diagnostic only') + parser.add_argument('--verify-traces', action='store_true', help='Compare every lighting ray with the stock collision query; not a timing build') + parser.add_argument('--verify-visibility', action='store_true', help='Compare packed and scalar CPU visibility reconstruction on identical fields') + parser.add_argument('--verify-textures', action='store_true', help='Compare specialized visibility pixels against the generic loop; diagnostic only') + parser.add_argument('--without-prongs', action='store_true', help='Diagnostic A/B: leave plasma prong flare attachments stock, retaining charge/projectile lighting') + args = parser.parse_args() + if (args.verify_textures or args.verify_visibility) and (args.profile or args.verify_traces): + parser.error('--verify-textures is a separate comparison from --profile and --verify-traces') + output = args.output_dir.resolve() + assert output.is_relative_to((ROOT/'build').resolve()) + output.mkdir(parents=True, exist_ok=True) + fixture = ROOT/'port/linux/game/lighting_performance_fixture.c' + assert not fixture.exists() + paths = ['source/main/main.c', 'port/linux/src/d3d8_gl.c', + 'port/linux/game/plasma_lighting.c', 'port/linux/game/plasma_occlusion.c', + 'port/linux/game/plasma_falloff.c', 'port/linux/game/plasma_collision.c', + 'port/linux/game/authored_emitter_lighting.c', 'port/linux/src/xinput_sdl.c'] + paths += ['port/linux/game/plasma_collision_models.c'] + if args.profile: + paths += ['source/objects/object_lights.c', 'port/linux/src/plasma_occlusion_gl.c'] + if args.diagnose or args.resources: + paths += ['source/physics/collision_usage.c', 'port/linux/src/xbox_textures.c'] + originals = {p: (ROOT/p).read_bytes() for p in paths} + saved = shlex.split(re.search(r'^configure_args = (.*)$', (ROOT/'build.ninja').read_text(), re.M)[1]) + manifest = dict(commit=subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip(), + configure_args=saved, production_hashes={p: hashlib.sha256(b).hexdigest() for p, b in originals.items()}, + fixture_sha256=hashlib.sha256((ROOT/'tools/fixtures/lighting_performance.c').read_bytes()).hexdigest(), + profile=args.profile, diagnose=args.diagnose, resources=args.resources, stalls=args.stalls, verify_traces=args.verify_traces, + verify_textures=args.verify_textures, verify_visibility=args.verify_visibility, + without_prongs=args.without_prongs) + for path in ['port/linux/game/authored_emitter_lighting.c', 'port/linux/game/ambient_emitter_lighting.c', + 'port/linux/game/covenant_emitter_lighting.c', 'port/linux/src/plasma_occlusion_gl.c', 'port/linux/include/plasma_occlusion.h', + 'port/linux/include/plasma_collision.h', 'source/physics/collision_bsp.c', + 'source/physics/collision_bsp.h', 'source/physics/collision_models.c', + 'source/physics/collision_models.h', 'port/linux/game/lighting_config.c']: + manifest['production_hashes'][path]=hashlib.sha256((ROOT/path).read_bytes()).hexdigest() + for path in ['port/linux/game/plasma_collision_scene.c', 'port/linux/game/ammo_counter_falloff.c']: + manifest['production_hashes'][path]=hashlib.sha256((ROOT/path).read_bytes()).hexdigest() + diagnostic_sources=[] + if args.diagnose or args.resources: + diagnostic_sources += ['tools/fixtures/'+name for name in ('lighting_diagnostics.inc', + 'lighting_resource_diagnostics.inc','lighting_texture_diagnostics.inc')] + if args.verify_traces: + diagnostic_sources += ['tools/lighting_trace_check.py','tools/fixtures/lighting_trace_check.inc'] + if args.verify_textures: + diagnostic_sources += ['tools/lighting_texture_check.py'] + if args.verify_visibility: + diagnostic_sources += ['tools/lighting_visibility_check.py'] + if args.stalls: + diagnostic_sources += ['tools/fixtures/lighting_stall_diagnostics.inc'] + manifest['diagnostic_hashes']={p:hashlib.sha256((ROOT/p).read_bytes()).hexdigest() for p in diagnostic_sources} + + def edit(path, before, after, declaration): + text = originals[path].decode().replace('\r\n', '\n') + assert text.count(before) == 1, (path, before) + (ROOT/path).write_text(declaration+'\n'+text.replace(before, after)) + + try: + if args.without_prongs: + authored = ROOT/'port/linux/game/authored_emitter_lighting.c' + rows = authored.read_text().splitlines(keepends=True) + kept = [row for row in rows if 'plasma pistol flare' not in row and 'plasma rifle flare' not in row] + assert len(rows)-len(kept) == 2 + authored.write_text(''.join(kept)) + # A previous diagnostic variant may have a newer object file. Preserve + # contents, not timestamps, so Ninja recompiles the selected fixture. + shutil.copyfile(ROOT/'tools/fixtures/lighting_performance.c', fixture) + input_source = ROOT/'port/linux/src/xinput_sdl.c' + text = input_source.read_text() + marker = 'static void test_input_gamepad(XINPUT_GAMEPAD *pad)' + assert text.count(marker) == 1 + text = text.replace(marker, 'int lighting_performance_input(XINPUT_GAMEPAD *pad);\n'+marker) + marker = '\tif (test_input_menu[0])' + assert text.count(marker) == 1 + input_source.write_text(text.replace(marker, '\tif (lighting_performance_input(pad)) return;\n'+marker)) + edit(paths[0], '\t\tmain_frame_rate_debug();', + '\t\tmain_frame_rate_debug();\n\t\tif (render_frame && game_in_progress() && !game_time_menu_scene()) lighting_performance_frame();', + 'void lighting_performance_frame(void); /* port: test-build-only timing */') + edit(paths[1], 'if (screenshot_every > 0 && device.frame % (unsigned long)screenshot_every == 0)', + 'if (*config_string("debug.screenshot_directory") && lighting_performance_capture())', 'int lighting_performance_capture(void);') + edit(paths[2], '\tshield_glow_frame_end();', + '\tlighting_performance_lights();\n\tshield_glow_frame_end();', 'void lighting_performance_lights(void);') + edit(paths[3], '\tupdates_this_window = 0;', + '\tlighting_performance_occlusion(updates_this_window);\n\tupdates_this_window = 0;', + 'void lighting_performance_occlusion(int updates);') + occlusion=ROOT/paths[3] + text=occlusion.read_text() + assert text.count('\tupdates_this_window++;')==1 and text.count('\tfield->valid = 1;')==1 + text=text.replace('\tupdates_this_window++;','\tupdates_this_window++;\n\tlighting_performance_occlusion_begin();') + text=text.replace('\tfield->valid = 1;','\tfield->valid = 1;\n\tlighting_performance_occlusion_end();') + occlusion.write_text('void lighting_performance_occlusion_begin(void);\nvoid lighting_performance_occlusion_end(void);\n'+text) + if args.diagnose or args.resources: + fixture.write_text(fixture.read_text()+'\n'+(ROOT/'tools/fixtures/lighting_diagnostics.inc').read_text()) + if args.diagnose: + text=occlusion.read_text() + anchor='\tfor (face = 0; face < 6; face++)' + assert text.count(anchor)==2 + text=text.replace(anchor,'\tlighting_trace_active = 1;\n'+anchor,1) + anchor='\n}\nstatic real depth_visibility' + assert text.count(anchor)==1 + text=text.replace(anchor,'\n\tlighting_trace_active = 0;'+anchor) + occlusion.write_text('extern int lighting_trace_active;\n'+text) + usage=ROOT/'source/physics/collision_usage.c' + text=usage.read_text().replace('if (!collision_log_time)', 'if (!collision_log_time && !lighting_trace_active)') + anchor='\tuser = collision_log_get_current_user(collision_function);' + # Only the end-time function has start_time in scope. + start=text.index('void collision_log_end_time(') + text=text[:start]+text[start:].replace(anchor,'\tlighting_trace_time(collision_function, start_time);\n'+anchor,1) + usage.write_text('extern int lighting_trace_active;\nvoid lighting_trace_time(int, __int64); /* port: diagnostic build only */\n'+text) + for path,inc in [('port/linux/src/d3d8_gl.c','lighting_resource_diagnostics.inc'), + ('port/linux/src/xbox_textures.c','lighting_texture_diagnostics.inc')]: + target=ROOT/path + data=(ROOT/'tools/fixtures'/inc).read_text() + target.write_text(target.read_text()+'\n'+data) + text=fixture.read_text() + text='void lighting_diagnostics_frame(double);\n'+text + text=text.replace('\t\t\tfflush(timings);','\t\t\tlighting_diagnostics_frame(now - origin);\n\t\t\tfflush(timings);') + fixture.write_text(text) + if args.stalls: + backend = ROOT/paths[1] + text = instrument_shader_stalls(backend.read_text()) + backend.write_text('void lighting_stall_shader_begin(int);\nvoid lighting_stall_shader_end(int);\n'+text+'\n'+ + (ROOT/'tools/fixtures/lighting_stall_diagnostics.inc').read_text()) + text = fixture.read_text() + anchor = '\tprevious = now;\n\tocclusion_seconds = 0;' + assert text.count(anchor) == 1 + fixture.write_text('void lighting_stall_frame(double, double);\n'+text.replace(anchor, + '\tlighting_stall_frame(now-origin, (now-previous)*1000.0);\n'+anchor)) + if args.verify_visibility: + from lighting_visibility_check import instrument as instrument_visibility + occlusion.write_text(instrument_visibility(occlusion.read_text())) + if args.verify_textures: + from lighting_texture_check import instrument as instrument_textures + occlusion.write_text(instrument_textures(occlusion.read_text())) + if args.profile: + def replace(path, before, after): + text=path.read_text() + assert text.count(before)==1, (path,before) + path.write_text(text.replace(before,after)) + declarations='void lighting_profile_begin(int);\nvoid lighting_profile_end(int);\n' + occlusion.write_text(declarations+occlusion.read_text()) + replace(occlusion, '\t\ttrace_depths(extent,', '\t\tlighting_profile_begin(0);\n\t\ttrace_depths(extent,') + replace(occlusion, '\t\tfield->traced = now;', '\t\tlighting_profile_end(0);\n\t\tfield->traced = now;') + replace(occlusion, '\tmemcpy(previous,', '\tlighting_profile_begin(1);\n\tmemcpy(previous,') + replace(occlusion, '\tfield->center[0] = light->position.x;', '\tlighting_profile_end(1);\n\tfield->center[0] = light->position.x;') + replace(occlusion, '\tscale = (pass == 2', '\tlighting_profile_begin(2);\n\tscale = (pass == 2') + replace(occlusion, '\tfield->texture_mask |= 1 << pass;', '\tlighting_profile_end(2);\n\tfield->texture_mask |= 1 << pass;') + scene_call = '\tscene_revision = plasma_collision_scene_revision(&field->scene, &light->position, extent, vehicles);' + replace(occlusion, scene_call, '\tlighting_profile_begin(10);\n'+scene_call+'\n\tlighting_profile_end(10);') + model = ROOT/'port/linux/src/plasma_occlusion_gl.c' + model.write_text(declarations+model.read_text()) + call = '\t\tresource = plasma_occlusion_model_texture(slot, transform);' + replace(model, call, '\t\tlighting_profile_begin(8);\n'+call+'\n\t\tlighting_profile_end(8);') + call = '\ttexture = xgpu_texture_get(resource, NULL, &target, &description);' + replace(model, call, '\tlighting_profile_begin(9);\n'+call+'\n\tlighting_profile_end(9);') + text = occlusion.read_text() + body = function(text, 'upload') + wrapper = ('\nstatic int upload(IDirect3DVolumeTexture8 **texture, unsigned long const *pixels)\n{\n' + '\tint result;\n\tlighting_profile_begin(11);\n' + '\tresult = lighting_timed_mask_upload(texture, pixels);\n' + '\tlighting_profile_end(11);\n\treturn result;\n}\n') + occlusion.write_text(text.replace(body, body.replace('upload(', 'lighting_timed_mask_upload(', 1)+wrapper, 1)) + backend=ROOT/paths[1] + backend.write_text(declarations+'int lighting_profile_model, lighting_profile_world;\n'+backend.read_text()) + backend.write_text(instrument_renderer_profile(backend.read_text())) + scene = ROOT/'source/objects/object_lights.c' + text = scene.read_text() + anchor = 'void lights_preprocess_scene(\n\tvoid)' + assert text.count(anchor) == 1 + text = text.replace(anchor, 'static void lighting_timed_preprocess_scene(void)', 1) + scene.write_text(declarations+text+'\n/* port: test-build-only inclusive scene timing. */\n' + 'void lights_preprocess_scene(void) { lighting_profile_begin(5); ' + 'lighting_timed_preprocess_scene(); lighting_profile_end(5); }\n') + main = ROOT/paths[0] + main.write_text(declarations+main.read_text()) + render = 'main_game_render((double)main_globals.seconds_elapsed);' + replace(main, render, 'lighting_profile_begin(7);\n\t\t\t\t\t'+render+'\n\t\t\t\t\tlighting_profile_end(7);') + replace(backend, '\tif (plasma_mask && entry->plasma_model_slots >= 0)\n\t{', '\tlighting_profile_model = plasma_mask && entry->plasma_model_slots >= 0 ? 1 : 0;\n\tif (plasma_mask && entry->plasma_model_slots >= 0)\n\t{') + bind='\t\tplasma_occlusion_bind_model(&entry->plasma_occlusion);' + replace(backend, bind, '\t\tlighting_profile_begin(3);\n'+bind+'\n\t\tlighting_profile_end(3);') + gpu=(ROOT/'tools/fixtures/lighting_gpu_profile.inc').read_text() + manifest['gpu_fixture_sha256']=hashlib.sha256(gpu.encode()).hexdigest() + replace(backend, 'static GLenum primitive_mode(', gpu+'\nstatic GLenum primitive_mode(') + text=backend.read_text() + text,count=re.subn(r'(\bglDraw(?:ElementsBaseVertex|Elements|Arrays)\([^;]+;)',r'lighting_gpu_begin();\n\t\t\1\n\t\tlighting_gpu_end();',text) + assert count==9, count + backend.write_text(text) + replace(backend, '\tdevice.frame++;', '\tlighting_gpu_frame(device.frame);\n\tdevice.frame++;') + falloff=ROOT/paths[4] + falloff.write_text('extern int lighting_profile_world;\n'+falloff.read_text()) + replace(falloff, '\tplasma_falloff_bound = TRUE;', '\tlighting_profile_world = stage == 1 ? 3 : 2;\n\tplasma_falloff_bound = TRUE;') + replace(falloff, '\tplasma_specular_tint = 0x00FFFFFFUL;\n\tif (!plasma_falloff_bound)', '\tlighting_profile_world = 0;\n\tplasma_specular_tint = 0x00FFFFFFUL;\n\tif (!plasma_falloff_bound)') + if args.verify_traces: + occlusion.write_text(instrument(occlusion.read_text())) + collision = ROOT/'port/linux/game/plasma_collision.c' + collision.write_text(instrument_collision(collision.read_text())) + collision = ROOT/'port/linux/game/plasma_collision_models.c' + collision.write_text(instrument_collision(collision.read_text())) + subprocess.run([sys.executable, 'configure.py', *saved], cwd=ROOT, check=True) + subprocess.run(['ninja', 'windows'], cwd=ROOT, check=True) + shutil.copy2(ROOT/'build/windows/halo.exe', output/'halo-performance.exe') + manifest['executable_sha256'] = hashlib.sha256((output/'halo-performance.exe').read_bytes()).hexdigest() + (output/'manifest.json').write_text(json.dumps(manifest, indent=2)) + finally: + for path, content in originals.items(): + (ROOT/path).write_bytes(content) + fixture.unlink(missing_ok=True) + subprocess.run([sys.executable, 'configure.py', *saved], cwd=ROOT, check=True) + subprocess.run(['ninja', 'windows'], cwd=ROOT, check=True) + + +if __name__ == '__main__': + main() diff --git a/tools/lighting_performance_run.py b/tools/lighting_performance_run.py new file mode 100644 index 0000000000..18a0e8f2b3 --- /dev/null +++ b/tools/lighting_performance_run.py @@ -0,0 +1,275 @@ +"""Run a sustained, isolated Windows bot battle and summarize frame pacing. + +One instance per invocation. Use sequential invocations for comparable timings. +Only the dedicated performance executable contains passive measurement hooks. +""" +import argparse +import csv +import ctypes +from ctypes import wintypes +import hashlib +import json +import math +import os +from pathlib import Path +import re +import shutil +import statistics +import subprocess +import time +import tomllib +from zipfile import ZipFile, ZIP_DEFLATED + +ROOT = Path(__file__).resolve().parents[1] +LIGHTS = ['plasma_lighting', 'muzzle_lighting', 'jackal_shield_lighting', + 'covenant_shield_lighting', 'fuel_rod_lighting', 'ammo_counter_lighting', + 'needler_lighting', 'plasma_occlusion', 'shield_glow', + 'weapon_glow', 'plasma_prong_lighting', 'vehicle_lighting', 'world_lighting'] +QUALITY = ['anti_aliasing', 'anisotropic_filtering', 'shadow_resolution', + 'per_pixel_lighting', 'model_detail', 'hdr', 'hdr_output', + 'viewmodel_shield', 'shield_look', 'fov', 'viewmodel_fov'] + + +def distribution(values, cap): + ordered = sorted(values) + if not ordered: + raise ValueError('No frame samples') + percentile = lambda p: ordered[max(0, math.ceil(len(ordered)*p)-1)] + return dict(frames=len(values), average_fps=1000/statistics.mean(values), + p50_ms=percentile(.5), p95_ms=percentile(.95), p99_ms=percentile(.99), + worst_ms=ordered[-1], low_1pct_fps=1000/statistics.mean(ordered[-max(1, math.ceil(len(ordered)*.01)):]), + budget_ms=1000/cap, + over_budget_percent=100*sum(v>1000/cap for v in values)/len(values), + over_1_5_budget_percent=100*sum(v>1500/cap for v in values)/len(values), + over_50ms=sum(v>50 for v in values), over_100ms=sum(v>100 for v in values)) + + +def summarize(rows, warmup, seconds, cap, captures=True): + measured = [r for r in rows if warmup <= r['seconds'] < warmup+seconds and r['frame_ms']>0] + # Older diagnostic binaries still mark capture slots when readback is off. + # Such frames must remain in pacing results; there was no capture overhead. + clean = [r for r in measured if not captures or not r['capture_excluded']] + result = dict(raw=distribution([r['frame_ms'] for r in measured], cap), + pacing=distribution([r['frame_ms'] for r in clean], cap), + excluded_capture_frames=len(measured)-len(clean), + measured_span=measured[-1]['seconds']-measured[0]['seconds'], + selected_max=max(r['selected'] for r in measured), + selected_mean=statistics.mean(r['selected'] for r in measured), + selected_frame_percent=100*sum(r['selected']>0 for r in measured)/len(measured), + scene_lights_max=max(r['scene_lights'] for r in measured), + occlusion_updates_max=max(r['occlusion_updates'] for r in measured), + occlusion_mean_ms=statistics.mean(r.get('occlusion_ms',0) for r in clean), + occlusion_max_ms=max(r.get('occlusion_ms',0) for r in clean), + minutes=[]) + for start in range(0, seconds, 60): + block=[r['frame_ms'] for r in clean if warmup+start <= r['seconds'] < warmup+min(start+60, seconds)] + if block: result['minutes'].append(dict(start=start, **distribution(block, cap))) + return result + + +def process_memory(handle): + class Counters(ctypes.Structure): + _fields_ = [('cb', wintypes.DWORD), ('faults', wintypes.DWORD)] + [ + (name, ctypes.c_size_t) for name in ('peak_rss','rss','peak_paged','paged','peak_nonpaged','nonpaged','pagefile','peak_pagefile','private')] + counters= Counters(); counters.cb=ctypes.sizeof(counters) + get=ctypes.WinDLL('psapi').GetProcessMemoryInfo + get.argtypes=[wintypes.HANDLE, ctypes.c_void_p, wintypes.DWORD] + if not get(wintypes.HANDLE(handle), ctypes.byref(counters), counters.cb): + raise ctypes.WinError() + return dict(rss=counters.rss, private=counters.private, faults=counters.faults) + + +def memory_window_mib(samples, start, end=float('inf')): + values = [m['private'] for m in samples if start <= m['seconds'] < end] + return statistics.mean(values)/2**20 if values else None + + +def safe(path, out): + assert path.resolve().is_relative_to(out) and path.resolve()!=out + for parent in [path, *path.parents]: + if parent==out: break + assert not parent.is_symlink() and not parent.is_junction(), parent + return path + + +def cleanup(out): + for path in out.rglob('*.map'): safe(path, out).unlink() + saves=[p for p in (out/'saves').rglob('*') if p.is_file()] + if saves: + manifest=[dict(path=p.relative_to(out).as_posix(), sha256=hashlib.sha256(p.read_bytes()).hexdigest()) for p in saves] + with ZipFile(out/'test-saves.zip', 'x', ZIP_DEFLATED, compresslevel=9) as archive: + for path, info in zip(saves, manifest): archive.write(path, info['path']) + archive.writestr('manifest.json', json.dumps(manifest, indent=2)) + with ZipFile(out/'test-saves.zip') as archive: + for info in manifest: assert hashlib.sha256(archive.read(info['path'])).hexdigest()==info['sha256'] + for path in saves: safe(path, out).unlink() + from PIL import Image + for path in (out/'screenshots').glob('*.bmp'): + target=path.with_suffix('.png') + with Image.open(path) as source: + source.save(target) + with Image.open(target) as saved: assert saved.size==source.size + safe(path, out).unlink() + for name in ['halo-performance.exe', 'SDL3.dll']: + path=out/name + if path.exists(): safe(path, out).unlink() + + +def main(): + parser=argparse.ArgumentParser(description=__doc__) + parser.add_argument('--data-root', type=Path, required=True) + parser.add_argument('--settings', type=Path) + parser.add_argument('--fps', type=int, choices=[30,60,120,240], required=True) + parser.add_argument('--uncapped', action='store_true', help='Measure headroom without the limiter; --fps remains the reporting budget') + parser.add_argument('--enabled', type=int, choices=[0,1], required=True) + parser.add_argument('--seconds', type=int, default=300) + parser.add_argument('--warmup', type=int, default=30) + parser.add_argument('--resolution', default='2560x1440') + parser.add_argument('--map', default='carousel', choices=['carousel','bloodgulch','c40']) + parser.add_argument('--checkpoint-root', type=Path, help='Copy an existing campaign profile/save root; never run against the original') + parser.add_argument('--stationary-shield', action='store_true', help='Isolated stationary emitter, no bots or other enhanced lights') + parser.add_argument('--advance-seconds', type=float, default=0, help='Walk forward in the copied campaign checkpoint with normal controller input') + parser.add_argument('--turn-seconds', type=float, default=0, help='Route inspection: turn right after walking, using normal controller input') + parser.add_argument('--route-captures', action='store_true', help='Route inspection only: capture every two seconds instead of once a minute') + parser.add_argument('--bots', type=int, default=15) + parser.add_argument('--label', required=True) + parser.add_argument('--build-dir', type=Path, default=ROOT/'build/lighting-performance-build') + parser.add_argument('--dump-shaders', action='store_true', help='Retain GLSL instead of screenshots for cache diagnosis; not an FPS acceptance run') + parser.add_argument('--no-captures', action='store_true', help='Disable screenshot allocations/readback for memory and stall diagnostics') + args=parser.parse_args() + if (args.map == 'c40') != bool(args.checkpoint_root): + parser.error('c40 requires --checkpoint-root; bot maps do not use a campaign save') + if args.stationary_shield and args.map != 'c40': + parser.error('--stationary-shield requires c40, which contains the shield tag') + if args.advance_seconds and (args.map != 'c40' or not 0 < args.advance_seconds <= 30): + parser.error('--advance-seconds requires c40 and a duration up to 30 seconds') + if args.turn_seconds and (not args.advance_seconds or not 0 < args.turn_seconds <= 3): + parser.error('--turn-seconds requires --advance-seconds and a duration up to three seconds') + assert re.fullmatch(r'[A-Za-z0-9_-]+', args.label) + assert re.fullmatch(r'[1-9][0-9]*x[1-9][0-9]*', args.resolution) + assert args.seconds>=30 and args.warmup>=0 and 1<=args.bots<=15 + out=(ROOT/'build/lighting-performance'/args.label).resolve() + assert out.is_relative_to((ROOT/'build').resolve()) + out.mkdir(parents=True, exist_ok=False) + (out/'maps').mkdir(); (out/'screenshots').mkdir() + env={k:v for k,v in os.environ.items() if not k.startswith('HALO_')} + env['PATH']=str(ROOT/'build/windows')+os.pathsep+env.get('PATH','') + settings={} + if args.settings: + display=tomllib.loads(args.settings.read_text())['display'] + settings={k:display[k] for k in QUALITY if k in display} + settings.update({k:bool(args.enabled) for k in LIGHTS}) + # These are deliberate test settings, not a player's legacy preferences. + settings.update(dynamic_lighting_reset=True, overshield_effect=bool(args.enabled), shield_glow_intensity='default') + if args.stationary_shield: + settings.update({k:False for k in LIGHTS}) + settings.update(covenant_shield_lighting=bool(args.enabled), plasma_occlusion=bool(args.enabled), overshield_effect=False) + (out/'config.toml').write_text('[display]\n'+''.join(f'{k} = {json.dumps(v)}\n' for k,v in settings.items())) + env.update(HALO_DATA_ROOT=str(out), HALO_SAVE_ROOT=str(out/'saves'), HALO_HIDDEN_WINDOW='1', + HALO_WINDOW_SIZE=args.resolution, HALO_RESOLUTION_SCALING='native', HALO_NO_AUDIO='1', + HALO_MAX_FPS='-1' if args.uncapped else str(args.fps), HALO_NO_VSYNC='1', HALO_EXIT_AFTER=str(args.warmup+args.seconds+25), + HALO_NET_ONLINE='0', HALO_NET_PUBLIC_LOBBY='0', HALO_NET_ALLOW_UPNP='0', + HALO_NET_JOIN_FROM_CLIPBOARD='0', + HALO_NET_ADDRESS=f'127.0.0.{81+args.enabled}', HALO_NET_BROADCAST=f'127.0.0.{81+args.enabled}', + HALO_UPDATE_ANSWER='never', HALO_CRASH_REPORTS='no', HALO_NETWORK_TEST=f'local:{args.map}:slayer', + HALO_NETWORK_TEST_START='5', HALO_NETWORK_TEST_SCORE='10000', HALO_BOTS=str(args.bots), + HALO_BOT_SKILL='heroic', HALO_TEST_INPUT='bot:1', HALO_SCREENSHOT_DIR=str(out/'screenshots')) + if args.checkpoint_root: + for key in ['HALO_NETWORK_TEST', 'HALO_NETWORK_TEST_START', 'HALO_NETWORK_TEST_SCORE', 'HALO_BOTS', 'HALO_BOT_SKILL']: + env.pop(key, None) + env.update(HALO_MENU_OPEN='main_menu/campaign_select/campaign_menu', + HALO_TEST_INPUT='menu:'+','.join(['wait']*8+['a']), + HALO_EXIT_AFTER=str(args.warmup+args.seconds+25)) + if args.stationary_shield: + env.update(HALO_BOTS='0', HALO_LIGHTING_BENCH_SHIELD='1') + if args.advance_seconds: + env['HALO_LIGHTING_BENCH_ADVANCE'] = str(args.advance_seconds) + if args.turn_seconds: + env['HALO_LIGHTING_BENCH_TURN'] = str(args.turn_seconds) + if args.route_captures: + env['HALO_LIGHTING_BENCH_ROUTE_CAPTURES'] = '1' + if args.dump_shaders: + (out/'shaders').mkdir() + env['HALO_GPU_DUMP_SHADERS']=str(out/'shaders') + # Diagnose cache growth without periodic readback/large image allocations. + env['HALO_SCREENSHOT_DIR']='' + if args.no_captures: + env['HALO_SCREENSHOT_DIR']='' + build=args.build_dir.resolve() + assert build.is_relative_to((ROOT/'build').resolve()) + shutil.copy2(build/'manifest.json', out/'build-manifest.json') + (out/'settings.json').write_text(json.dumps(dict(resolution=args.resolution, fps=args.fps, uncapped=args.uncapped, + frame_limit=int(env['HALO_MAX_FPS']), + warmup=args.warmup, seconds=args.seconds, bots=0 if args.stationary_shield else args.bots, map=args.map, + stationary_shield=args.stationary_shield, + campaign_advance_seconds=args.advance_seconds, campaign_turn_seconds=args.turn_seconds, route_captures=args.route_captures, + shader_dump=args.dump_shaders, captures=not (args.dump_shaders or args.no_captures), display=settings),indent=2)) + memory=[]; start=time.monotonic(); process=None + try: + if args.checkpoint_root: + source = args.checkpoint_root.resolve() + manifest = [] + for path in (source/'u').rglob('*'): + if not path.is_file(): continue + relative = path.relative_to(source) + target = safe(out/'saves'/relative, out) + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(path, target) + manifest.append(dict(path=relative.as_posix(), sha256=hashlib.sha256(target.read_bytes()).hexdigest())) + assert any(item['path'].endswith('/savegame.bin') for item in manifest), 'No campaign checkpoint found' + (out/'checkpoint-source.json').write_text(json.dumps(dict(source=str(source), files=manifest), indent=2)) + for name in ['ui.map', args.map+'.map']: + shutil.copy2(args.data_root/'maps'/name, out/'maps'/name) + # Desktop configuration is next to the executable, not the data root. + shutil.copy2(build/'halo-performance.exe', out/'halo-performance.exe') + shutil.copy2(ROOT/'build/windows/SDL3.dll', out/'SDL3.dll') + with (out/'stdout.log').open('wb') as stdout, (out/'stderr.log').open('wb') as stderr: + process=subprocess.Popen([str(out/'halo-performance.exe')], cwd=out, env=env, + stdout=stdout, stderr=stderr, creationflags=subprocess.CREATE_NO_WINDOW) + (out/'process.json').write_text(json.dumps(dict(pid=process.pid, executable=str(out/'halo-performance.exe')))) + try: + while process.poll() is None: + if time.monotonic()-start>args.warmup+args.seconds+120: + raise TimeoutError('Game did not exit') + memory.append(dict(seconds=time.monotonic()-start, **process_memory(process._handle))) + (out/'memory.json').write_text(json.dumps(memory,indent=2)) + time.sleep(5) + finally: + if process.poll() is None: process.terminate(); process.wait(10) + rows=[] + if (out/'frames.csv').exists(): + with (out/'frames.csv').open() as frames: + rows=[{k:float(v) for k,v in row.items()} for row in csv.DictReader(frames)] + report={} + try: + report=summarize(rows,args.warmup,args.seconds,args.fps, + captures=not (args.dump_shaders or args.no_captures)) + except ValueError as error: + report['measurement_error']=str(error) + log=(out/'stderr.log').read_text(errors='replace') + report.update(exit=process.returncode, fps=args.fps, uncapped=args.uncapped, frame_limit=int(env['HALO_MAX_FPS']), enabled=args.enabled, shader_dump=args.dump_shaders, + captures=not (args.dump_shaders or args.no_captures), + unexpected_players=bool(re.search(r'\bplayer '+str(args.bots+1)+r':', log)), + bots_lines=[line for line in log.splitlines() if 'bots: tick' in line], + errors=re.findall(r'(?im)^.*(?:crash: exception|exception halt|assertion failed|GL_INVALID|shader.*(?:error|failed)).*$',log), + peak_private_mib=max((m['private']/2**20 for m in memory),default=None), + peak_rss_mib=max((m['rss']/2**20 for m in memory),default=None), + # Memory uses the runner clock. Bound both windows before + # the exit deadline; shutdown deallocation is not a plateau. + first_minute_private_mib=memory_window_mib(memory,args.warmup+15,min(args.warmup+75,args.warmup+args.seconds)), + last_minute_private_mib=memory_window_mib(memory,max(args.warmup+15,args.warmup+args.seconds-60),args.warmup+args.seconds)) + (out/'report.json').write_text(json.dumps(report,indent=2)) + print(json.dumps(dict(label=args.label, **report)),flush=True) + assert report['exit']==0 and not report['errors'], 'Game failed; retained report and logs describe the failure' + assert not report.get('measurement_error') and report['measured_span']>=args.seconds-.2, 'Incomplete measurement' + assert not report['unexpected_players'], 'Unexpected player joined the isolated workload' + assert bool(report['selected_max'])==bool(args.enabled), 'Light activation mismatch' + if args.stationary_shield: + assert re.search(r'BENCH shield created (?!-1\b)-?\d+', log), 'Stationary emitter was not created' + if args.seconds>=120 and not args.checkpoint_root and not args.stationary_shield: assert len(report['bots_lines'])>=args.seconds//60-1, 'Insufficient combat telemetry' + finally: + cleanup(out) + + +if __name__=='__main__': + main() diff --git a/tools/lighting_texture_check.py b/tools/lighting_texture_check.py new file mode 100644 index 0000000000..a82e707e64 --- /dev/null +++ b/tools/lighting_texture_check.py @@ -0,0 +1,61 @@ +"""Compare specialized visibility conversion with its generic loop in one pose.""" +def instrument(text): + declaration = 'static __attribute__((noinline)) void *prepare_field_texture(' + assert text.count(declaration) == 1 + first = text.index(declaration) + end = text.index('{', first) + 1 + depth = 1 + while depth: + depth += (text[end] == '{') - (text[end] == '}') + end += 1 + body = text[first:end] + boundary = '\tif (!(field->uploaded_mask & (1 << pass))' + start = body.index(boundary) + calculation = body[:start] + assert calculation.count(declaration) == 1 + calculation = calculation.replace(declaration, 'static __attribute__((noinline)) void check_texture_pixels(unsigned long *output, ') + calculation = calculation.replace('\tunsigned long pixels[OCC_COUNT];', '\tunsigned long *pixels = output;') + calculation += '}\n' + generic = calculation.replace('check_texture_pixels(', 'check_texture_generic(', 1) + generic = generic.replace('if (!pass && !directional)', 'if (FALSE)').replace('else if (!pass || scale == 0.5f || scale == 1.0f)', 'else if (FALSE)') + wrapper = r''' +static void check_texture(struct occlusion_field *field, int pass, int directional, real const axis[3]) +{ + static FILE *file; + static unsigned long calls, mismatches, last; + static double fast_ticks, generic_ticks; + unsigned long fast[OCC_COUNT], generic[OCC_COUNT], now; + LARGE_INTEGER a, b, c, frequency; + /* Alternate ordering to balance instruction/data cache warming. No + uploads or field changes occur inside either timed calculation. */ + QueryPerformanceCounter(&a); + if (calls & 1) check_texture_pixels(fast, field, pass, directional, axis); + else check_texture_generic(generic, field, pass, directional, axis); + QueryPerformanceCounter(&b); + if (calls & 1) check_texture_generic(generic, field, pass, directional, axis); + else check_texture_pixels(fast, field, pass, directional, axis); + QueryPerformanceCounter(&c); + fast_ticks += (double)((calls & 1) ? b.QuadPart-a.QuadPart : c.QuadPart-b.QuadPart); + generic_ticks += (double)((calls & 1) ? c.QuadPart-b.QuadPart : b.QuadPart-a.QuadPart); + calls++; + if (memcmp(fast, generic, sizeof(fast))) mismatches++; + if (!file) + { + file = fopen("texture-check.csv", "w"); + if (file) fprintf(file, "milliseconds,calls,mismatches,fast_ms,generic_ms\n"); + } + now = GetTickCount(); + if (file && now-last >= 1000) + { + QueryPerformanceFrequency(&frequency); + fprintf(file, "%lu,%lu,%lu,%.6f,%.6f\n", now, calls, mismatches, + fast_ticks*1000/(double)frequency.QuadPart, generic_ticks*1000/(double)frequency.QuadPart); + fflush(file); + last = now; + } +} +''' + # Run the comparison only on cache misses. Production remains the only + # writer/uploader and its return/failure handling is unchanged. + checked = body.replace('\tscale = (pass == 2', '\tcheck_texture(field, pass, directional, axis);\n\tscale = (pass == 2', 1) + return text.replace(body, '#include \n'+calculation+generic+wrapper+checked, 1) diff --git a/tools/lighting_trace_check.py b/tools/lighting_trace_check.py new file mode 100644 index 0000000000..a56a1c4f01 --- /dev/null +++ b/tools/lighting_trace_check.py @@ -0,0 +1,36 @@ +"""Compare and time complete ray batches against the original query in one pose.""" +from pathlib import Path + +def instrument_collision(text): + marker = '&batch.cache[octant]);' if '&batch.cache[octant]);' in text else '&cache))' + assert text.count(marker) == 1 + replacement = marker.replace('[octant]', '[lighting_trace_unprepared ? 0 : octant]') + text = text.replace(marker, 'lighting_trace_uncached ? NULL : '+replacement) + call = 'trace_prepare(batch.prefixes[octant].node, batch.prefixes[octant].depth, octant, &work, &target, &skipped);' + if '[octant]' in marker: + assert text.count(call) == 1 + text = text.replace(call, 'if (!lighting_trace_unprepared) '+call) + return 'extern int lighting_trace_uncached, lighting_trace_unprepared; /* test build only */\n'+text + + +def instrument(text): + marker='static void trace_depths(' + assert text.count(marker)==1 + start=text.index(marker) + opening=text.index('{',start) + depth=1 + end=opening+1 + while depth: + depth += (text[end]=='{')-(text[end]=='}') + end+=1 + original=text[start:end] + call = 'plasma_collision_depths(flags, from, vectors, count, ignore, hits);' + assert original.count(call) == 1 + reference=original.replace('trace_depths(', 'trace_depths_reference(',1) + reference=reference.replace(call, '''for (axis = 0; axis < count; axis++) + { + struct collision_result hit; + hits[axis] = collision_test_vector(flags, from, &vectors[axis], ignore, &hit) ? hit.t : 2.0f; + }''') + wrapper=(Path(__file__).parent/'fixtures/lighting_trace_check.inc').read_text() + return text[:start]+original.replace('trace_depths(', 'trace_depths_actual(',1)+'\n'+reference+'\n'+wrapper+text[end:] diff --git a/tools/lighting_visibility_check.py b/tools/lighting_visibility_check.py new file mode 100644 index 0000000000..817031d834 --- /dev/null +++ b/tools/lighting_visibility_check.py @@ -0,0 +1,60 @@ +"""Compare packed and scalar reconstruction on the same live depth field.""" +from harness import function + + +def instrument(text): + body = function(text, 'reconstruct_visibility') + packed = body.replace('reconstruct_visibility(', 'reconstruct_packed(', 1) + scalar = body.replace('reconstruct_visibility(', 'reconstruct_scalar(', 1) + scalar = scalar.replace('depth_visibility_row(', 'depth_visibility_scalar_row(') + row = ''' +static void depth_visibility_scalar_row(real depths[6][OCC_SIZE * OCC_SIZE], const real xs[OCC_SIZE], + real y, real z, real extent, int resolution, real *output) +{ + int x; + for (x = 0; x < OCC_SIZE; x++) + { + real_vector3d ray; + ray.i = xs[x]; ray.j = y; ray.k = z; + output[x] = depth_visibility(depths, &ray, extent, resolution); + } +} +''' + wrapper = r''' +static void reconstruct_visibility(real depths[6][OCC_SIZE * OCC_SIZE], real extent, + int resolution, real dx, real dy, real dz, real *output) +{ + static FILE *file; + static unsigned long calls, mismatches, last; + static double packed_ticks, scalar_ticks; + real reference[OCC_COUNT]; + LARGE_INTEGER a, b, c, frequency; + unsigned long now; + QueryPerformanceCounter(&a); + if (calls & 1) reconstruct_packed(depths, extent, resolution, dx, dy, dz, output); + else reconstruct_scalar(depths, extent, resolution, dx, dy, dz, reference); + QueryPerformanceCounter(&b); + if (calls & 1) reconstruct_scalar(depths, extent, resolution, dx, dy, dz, reference); + else reconstruct_packed(depths, extent, resolution, dx, dy, dz, output); + QueryPerformanceCounter(&c); + packed_ticks += (double)((calls & 1) ? b.QuadPart-a.QuadPart : c.QuadPart-b.QuadPart); + scalar_ticks += (double)((calls & 1) ? c.QuadPart-b.QuadPart : b.QuadPart-a.QuadPart); + calls++; + if (memcmp(output, reference, sizeof(reference))) mismatches++; + if (!file) + { + file = fopen("visibility-check.csv", "w"); + if (file) fprintf(file, "milliseconds,fields,mismatches,packed_ms,scalar_ms\n"); + } + now = GetTickCount(); + if (file && now-last >= 1000) + { + QueryPerformanceFrequency(&frequency); + fprintf(file, "%lu,%lu,%lu,%.6f,%.6f\n", now, calls, mismatches, + packed_ticks*1000/(double)frequency.QuadPart, scalar_ticks*1000/(double)frequency.QuadPart); + fflush(file); + last = now; + } +} +''' + return text.replace(body, '#include \n'+row+packed+scalar+wrapper, 1) diff --git a/tools/linux_build.py b/tools/linux_build.py index 7bdb7843e0..b31eb37fea 100644 --- a/tools/linux_build.py +++ b/tools/linux_build.py @@ -585,7 +585,11 @@ def add_object(source: Path, cflags: str, posix: bool = False) -> None: # Port-specific units that must see the game exactly as its own # sources do (port/linux/game). for source in sorted(Path(config["game_sources"]).glob("*.c")): - add_object(source, game_cflags) + flags = game_cflags + # The main menu labels the executable with its release number. + if source.as_posix() == "port/linux/game/menu_functions.c": + flags += " " + updater_defines(getattr(sln, "port_release", False)) + add_object(source, flags) add_object(STB_VORBIS_SOURCE, game_cflags) platform_dir = Path(config["platform_sources"]) diff --git a/tools/mcc_native_smoke.py b/tools/mcc_native_smoke.py new file mode 100644 index 0000000000..b1b25290fa --- /dev/null +++ b/tools/mcc_native_smoke.py @@ -0,0 +1,322 @@ +"""Bounded Windows MCC startup checks using locally supplied, private test assets. + +Use a disposable data root containing maps/ui.map. Local levels use mcc_maps; +--workshop accepts installed numeric-package/map names without copying maps. +--steam-root selects a Steam library and --campaigns enables mission discovery. +Never commit assets or generated logs. The data root's init.txt is restored. +Each case retains isolated saves/logs; generated map caches are removed only +after child exit. Uncertain shutdown also retains the copied executable. +Only one hidden game runs at a time. Success requires a console expression to +finish after 150 simulation ticks, not just the tag-loader's 'loaded' message. +""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import socket +import stat +import subprocess +import tempfile +import time +import uuid + + +FAILURES = ("recompile scripts", "recompile.)", "error loading scripts", + "scripts won't run", "unsupported script", "invalid script", + "mcc: refused", "exception halt", "exception assert", "assertion failed", + "failed to allocate", "could not load", "invalid mcc script parameter", + "this is not a valid object name", "i expected a value of type", + "create_transport_endpoint() failed on telnet console endpoint", + "bind_endpoint() failed on telnet console endpoint", + "listen_endpoint() failed on telnet console endpoint") + + +def check_result(trace, console, marker, map_name, exit_code): + combined = (trace + "\n" + console).lower() + failures = [message for message in FAILURES if message in combined] + map_name = map_name.replace("/", "\\") + loaded = f"mcc: loaded mcc_maps\\{map_name.lower()} (" in trace.lower() + # The console echoes commands; an echoed print expression is not evidence + # it executed. Require the entire output line after the sleep has finished. + advanced = marker.lower() in {line.strip().lower() for line in console.splitlines()} + return dict(map=map_name, loaded=loaded, simulation_advanced=advanced, + failures=failures, exit_code=exit_code, + passed=loaded and advanced and exit_code == 0 and not failures) + + +def case_environment(args, output): + env = {key: value for key, value in os.environ.items() if not key.startswith("HALO_")} + env.update(HALO_DATA_ROOT=str(args.data_root), HALO_SAVE_ROOT=str(output / "saves"), + HALO_LOG_ROOT=str(output), + HALO_HIDDEN_WINDOW="1", HALO_EXIT_AFTER=str(args.seconds), + HALO_MAX_FPS="30", HALO_NO_VSYNC="1", HALO_NO_AUDIO="1", + HALO_DISPLAY_MODE="windowed", HALO_WINDOW_SIZE="640x480", HALO_FULLSCREEN="0", + HALO_NET_ONLINE="0", HALO_NET_PUBLIC_LOBBY="0", HALO_NET_ALLOW_UPNP="0", + HALO_NET_ADDRESS="127.0.0.236", HALO_NET_BROADCAST="127.0.0.237", + HALO_NET_JOIN_FROM_CLIPBOARD="0", HALO_UPDATE_AUTO="0", HALO_CRASH_REPORTS="no", + HALO_CONSOLE_LOG="all", HALO_TELNET_CONSOLE="1", HALO_TELNET_CONSOLE_PORT=str(args.port), + HALO_WORKSHOP_MAPS=str(int(args.workshop)), HALO_MCC_CAMPAIGNS=str(int(args.campaigns)), + HALO_STEAM_ROOT=str(args.steam_root) if args.steam_root else "") + # HALO_NULL_RENDERER is presence-only: even "0" disables rendering. + return env + + +def linked(status): + return stat.S_ISLNK(status.st_mode) or getattr(status, "st_file_attributes", 0) & 0x400 + + +def cleanup_map_caches(output): + """Only this fresh case's z/cacheNNN.map files; never traverse links.""" + report = dict(removed_files=0, removed_bytes=0, errors=[]) + root = output.resolve() + cache = output / "saves" / "z" + try: + for path in (output, output / "saves", cache): + try: + status = path.lstat() + except FileNotFoundError: + return report + if linked(status) or not stat.S_ISDIR(status.st_mode) or not path.resolve().is_relative_to(root): + raise OSError(f"Refusing linked or uncontained cache directory: {path}") + for path in cache.iterdir(): + if not re.fullmatch(r"cache[0-9]{3}\.map", path.name, re.IGNORECASE): + continue + status = path.lstat() + if linked(status) or not stat.S_ISREG(status.st_mode) or path.resolve().parent != cache.resolve(): + report["errors"].append(f"Refusing nonregular or linked cache file: {path}") + continue + path.unlink() + report["removed_files"] += 1 + report["removed_bytes"] += status.st_size + except OSError as error: + report["errors"].append(str(error)) + return report + + +def check_console_port(port): + """Refuse a busy or inaccessible console before touching the data root.""" + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe: + if hasattr(socket, "SO_EXCLUSIVEADDRUSE"): + probe.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1) + probe.bind(("127.0.0.1", port)) + + +def verify_console_owner(connection, pid): + # A successful preflight cannot reserve the port across process startup. + # Check the accepted connection's exact tuple before sending any command. + netstat = Path(os.environ.get("SystemRoot", "C:/Windows")) / "System32" / "netstat.exe" + try: + report = subprocess.run([str(netstat), "-ano", "-p", "TCP"], capture_output=True, + text=True, check=True, timeout=5, + creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0)) + except (OSError, subprocess.SubprocessError) as error: + raise OSError(f"Cannot inspect console ownership: {error}") from error + server = "{}:{}".format(*connection.getpeername()) + client = "{}:{}".format(*connection.getsockname()) + for line in report.stdout.splitlines(): + fields = line.split() + if len(fields) == 5 and fields[:3] == ["TCP", server, client] and fields[4] == str(pid): + return + raise OSError(f"Console connection does not belong to launched process {pid}") + + +def replace_init(path, content): + # Write beside init.txt, then replace atomically: a partial write must not + # truncate the user's original startup file. + descriptor, filename = tempfile.mkstemp(prefix=".mcc-smoke-", dir=path.parent) + temporary = Path(filename) + try: + with os.fdopen(descriptor, "wb") as stream: + stream.write(content) + os.replace(temporary, path) + finally: + temporary.unlink(missing_ok=True) + + +def run_case(args, name, binary): + name = name.replace("/", "\\") + started = time.monotonic() + args.output.mkdir(parents=True, exist_ok=True) + output = Path(tempfile.mkdtemp(prefix=name.replace("\\", "_") + "-", dir=args.output)) + data, init = args.data_root, args.data_root / "init.txt" + original = init.read_bytes() if init.exists() else None + debug = output / "debug.txt" + marker = "mcc_smoke_" + uuid.uuid4().hex + env = case_environment(args, output) + transcript = "" + launcher_errors = [] + process = connection = None + def trace(): + if not debug.exists(): + return "" + return debug.read_bytes().decode("latin1") + try: + check_console_port(args.port) + if original is not None: + (output / "init.original.txt").write_bytes(original) + replace_init(init, f"map_name mcc_maps\\{name}\n".encode("ascii")) + with (output / "stdout.log").open("wb") as stdout, (output / "stderr.log").open("wb") as stderr: + process = subprocess.Popen([str(binary)], cwd=data, env=env, stdout=stdout, stderr=stderr, + creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0)) + deadline = time.monotonic() + args.seconds + 60 + sent = False + while process.poll() is None and time.monotonic() < deadline: + current = trace() + if any(message in current.lower() for message in FAILURES): + break + if connection is None and f"mcc: loaded mcc_maps\\{name.lower()} (" in current.lower(): + try: + connection = socket.create_connection(("127.0.0.1", args.port), .2) + connection.settimeout(.1) + except PermissionError: + raise + except OSError: + connection = None + if connection is not None: + verify_console_owner(connection, process.pid) + if connection is not None: + try: + if not sent: + connection.sendall(f'(begin (sleep 150) (print "{marker}"))\r\n'.encode("ascii")) + sent = True + received = connection.recv(65536) + if received: + transcript += received.decode("latin1") + except socket.timeout: + pass + except PermissionError: + raise + except OSError: + connection.close() + connection = None + time.sleep(.1) + except OSError as error: + launcher_errors.append(str(error)) + finally: + if connection is not None: + try: + connection.close() + except OSError as error: + launcher_errors.append(f"Cannot close console: {error}") + try: + if process is not None and process.poll() is None: + process.kill() + process.wait(timeout=10) + except (OSError, subprocess.SubprocessError) as error: + launcher_errors.append(f"Cannot stop launched process: {error}") + finally: + try: + current = init.read_bytes() if init.exists() else None + if current != original: + if original is None: + init.unlink(missing_ok=True) + else: + replace_init(init, original) + except OSError as error: + launcher_errors.append(f"Cannot restore {init}: {error}") + (output / "debug.log").write_text(trace(), encoding="utf-8") + (output / "console.log").write_text(transcript, encoding="utf-8") + process_stopped = process is None or process.poll() is not None + if process_stopped: + cleanup = cleanup_map_caches(output) + else: + cleanup = dict(removed_files=0, removed_bytes=0, + errors=[f"Process {process.pid} is still running; preserving {output}"]) + diagnostics = trace() + for name_log in ("stdout.log", "stderr.log"): + path = output / name_log + if path.exists(): + diagnostics += "\n" + path.read_text(errors="replace") + result = check_result(diagnostics, transcript, marker, name, process.returncode if process else None) + result.update(output=str(output), launcher_error="; ".join(launcher_errors), cleanup=cleanup, + pid=process.pid if process else None, process_stopped=process_stopped, + settings={key: value for key, value in env.items() if key.startswith("HALO_")}) + result["passed"] = result["passed"] and not launcher_errors and not cleanup["errors"] + result["elapsed_seconds"] = round(time.monotonic() - started, 2) + result["executable_sha256"] = hashlib.sha256(binary.read_bytes()).hexdigest() + (output / "result.json").write_text(json.dumps(result, indent=2) + "\n") + return result + + +def parse_args(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--executable", type=Path, required=True) + parser.add_argument("--data-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--seconds", type=int, default=45) + parser.add_argument("--port", type=int, default=23251) + parser.add_argument("--workshop", action="store_true", help="enable installed Steam Workshop discovery") + parser.add_argument("--steam-root", type=Path, help="Steam install/library to check first; requires --workshop") + parser.add_argument("--campaigns", action="store_true", help="enable explicit MCC campaign mission discovery") + parser.add_argument("maps", nargs="+") + args = parser.parse_args(argv) + if args.seconds < 20 or args.seconds > 300: + parser.error("--seconds must be between 20 and 300") + if not 1 <= args.port <= 65535: + parser.error("--port must be between 1 and 65535") + if args.steam_root: + if not args.workshop or not args.steam_root.is_dir(): + parser.error("--steam-root requires --workshop and an existing directory") + args.steam_root = args.steam_root.resolve() + if not args.executable.is_file() or not (args.executable.parent / "SDL3.dll").is_file(): + parser.error("--executable must name a build with SDL3.dll beside it") + if not (args.data_root / "maps" / "ui.map").is_file(): + parser.error("--data-root must contain maps/ui.map") + init = args.data_root / "init.txt" + try: + status = init.lstat() + except FileNotFoundError: + pass + else: + if linked(status) or not stat.S_ISREG(status.st_mode): + parser.error("the disposable data root's init.txt must be a regular file") + for index, name in enumerate(args.maps): + name = name.replace("\\", "/") + if name.lower().startswith("mcc_maps/"): + name = name[9:] + if len("mcc_maps/" + name) > 63 or not re.fullmatch(r"[A-Za-z0-9_-]+(?:/[A-Za-z0-9_-]+)?", name): + parser.error("supply loose or package/map names fitting the 63-byte MCC level name") + if not (args.data_root / "mcc_maps" / (name + ".map")).is_file() and not ( + args.workshop and re.fullmatch(r"[0-9]{1,23}/[A-Za-z0-9_-]+", name)): + parser.error("missing local map: Workshop item/map names require --workshop") + args.maps[index] = name + args.executable = args.executable.resolve() + args.data_root, args.output = args.data_root.resolve(), args.output.resolve() + return args + + +def main(): + args = parse_args() + if os.name != "nt": + raise SystemExit("this launcher currently supports Windows only") + args.output.mkdir(parents=True, exist_ok=True) + binary = Path(tempfile.mkdtemp(prefix="bin-", dir=args.output)) / "halo.exe" + results = [] + process_stopped = True + try: + shutil.copy2(args.executable, binary) + shutil.copy2(args.executable.parent / "SDL3.dll", binary.parent / "SDL3.dll") + for name in args.maps: + print(f"{name}: hidden startup and simulation check", flush=True) + # An exception can prevent run_case from reporting child shutdown. + # Retain its executable until completion is positively established. + process_stopped = False + result = run_case(args, name, binary) + process_stopped = result.get("process_stopped", False) + results.append(result) + print(json.dumps(result), flush=True) + (args.output / "results.json").write_text(json.dumps(results, indent=2) + "\n") + if result.get("launcher_error") or not process_stopped: + break + finally: + if process_stopped: + binary.unlink(missing_ok=True) + (binary.parent / "SDL3.dll").unlink(missing_ok=True) + return 0 if process_stopped and all(result["passed"] for result in results) else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/mcc_xbox_menu.py b/tools/mcc_xbox_menu.py new file mode 100644 index 0000000000..6f76c5758e --- /dev/null +++ b/tools/mcc_xbox_menu.py @@ -0,0 +1,157 @@ +"""Additive Xbox-style MCC browser, using existing redraws and native services.""" +import xml.etree.ElementTree as ET +from pathlib import Path + +NATIVE = 'ui\\shell\\main_menu\\' + +BASE = 'mcc_xbox/' +ROUTES = ('campaign', 'connected', 'split', 'connected_postgame', 'split_postgame') + + +def append(doc): + def widget(name, **attrs): + return ET.SubElement(doc, 'widget', name=BASE+name, + **{k: str(v) for k, v in attrs.items()}) + + def child(parent, name, x=0, y=0): + ET.SubElement(parent, 'child', widget=BASE+name, x=str(x), y=str(y)) + + def on(parent, event, action): + ET.SubElement(parent, 'on', event=event, run='port mcc xbox '+action) + + def text(name, caption, x, y, width, height, small=False): + node = widget(name, type='text', left=x, top=y, + width=width, height=height, font='ui\\small_ui' if small else 'ui\\large_ui', + color='#FF2896FF', text_flags='no_focus_test') + if caption is not None: node.set('text', caption) + return node + + for route in ROUTES: + root = widget(route, width=640, height=480, bitmap='ui\\shell\\bitmaps\\gradient', + flags='pass_unhandled_to_focused_child') + on(root, 'created', 'init') + for event in ('a', 'start'): on(root, event, 'choose') + for event in ('b', 'back'): on(root, event, 'back') + for event in ('left', 'stick_left'): on(root, event, 'left') + for event in ('right', 'stick_right'): on(root, event, 'right') + for name in ('heading_campaigns', 'heading_levels', 'heading_maps', 'heading_difficulty'): + child(root, name) + for i in range(3): child(root, 'card_'+str(i)) + child(root, 'status') + child(root, 'previous') + child(root, 'next') + ET.SubElement(root, 'child', widget=NATIVE+'button_key') + child(root, 'difficulty_list') + widget('heading_campaigns', left=35, top=11, width=605, height=59, bitmap='mcc_xbox/heading_campaigns') + bitmap = ET.SubElement(doc, 'bitmap', name='mcc_xbox/heading_campaigns') + ET.SubElement(bitmap, 'frame', png='modern/mcc_campaigns.png', width='512', height='64') + for name, path, width in ( + ('heading_levels', 'solo_level_select\\header_load_level', 306), + ('heading_maps', 'multiplayer_type_select\\mp_map_select\\header_select_map', 605), + ('heading_difficulty', 'difficulty_select\\header_choose_difficulty', 390)): + widget(name, left=35, top=11, width=width, height=59, bitmap=NATIVE+path) + text('status', None, 64, 414, 280, 28, True) + for i in range(3): + x = 72+167*i + name = 'card_'+str(i) + card = widget(name, left=x, top=75, width=(165, 163, 162)[i], height=330 if i==0 else 326, flags='nifty_fx', + bitmap='ui\\shell\\bitmaps\\spinner_list_3_wide_item_background') + on(card, 'left_mouse', 'card') + for leaf in ('picture', 'mcc_folder_name', 'mcc_folder_help'): + child(card, name+'/'+leaf) + widget(name+'/picture', left=x+13, top=87, width=140, height=114, + bitmap='ui\\shell\\bitmaps\\mp_map_grafix') + text(name+'/mcc_folder_name', None, x+11, 204, 144+i, 43) + text(name+'/mcc_folder_help', None, x+11, 258, 144+i, 136, True) + for badge in range(3): + child(card, name+'/badge_'+str(badge)) + widget(name+'/badge_'+str(badge), left=x+10+50*badge, top=343, width=44, height=48, + bitmap=NATIVE+'difficulty_select\\difficulty_options_small') + for name, direction, x, width in (('previous', 'left', 50, 18), ('next', 'right', 575, 35)): + arrow = widget(name, left=x, top=174, width=width, height=170, + bitmap='ui\\shell\\bitmaps\\arrow_big_'+direction) + on(arrow, 'left_mouse', 'left' if name=='previous' else 'right') + # Appended instances only: original Xbox tag definitions are never edited. + entry = widget('campaign_entry', type='text', width=256, height=33, + bitmap='mcc_xbox/menu_campaigns', font='ui\\small_ui', color='#000080FF') + for event in ('a', 'start', 'left_mouse'): on(entry, event, 'open') + bitmap = ET.SubElement(doc, 'bitmap', name='mcc_xbox/menu_campaigns') + for frame in range(2): + ET.SubElement(bitmap, 'frame', png=f'modern/mcc_campaigns_entry_{frame}.png', width='256', height='64') + entry = text('multiplayer_entry', '=MCC MAPS', 64, 414, 280, 28) + entry.set('text_x', '22') + ET.SubElement(entry, 'child', widget='frontend_legacy/footer_glyph_x', x='64', y='414') + on(entry, 'left_mouse', 'open') + + # Profile and difficulty presentation borrow unchanged native UI components + # through their existing services. Only the MCC wrappers decide destinations. + profile = widget('profiles', width=640, height=480, bitmap='ui\\shell\\bitmaps\\gradient', + flags='pass_unhandled_to_focused_child') + ET.SubElement(profile, 'on', event='created', run='sp reset controller choices') + for event in ('a', 'start'): on(profile, event, 'profile') + for event in ('b', 'back'): ET.SubElement(profile, 'on', event=event, back='true') + for path in ('player_profiles_select\\player_profile_select_list', + 'player_profiles_select\\header_select_profile', 'button_key'): + ET.SubElement(profile, 'child', widget=NATIVE+path) + ET.SubElement(profile, 'on', event='y', run='create&edit player profile', + open=NATIVE+'settings_select\\player_setup\\create_and_edit_player_profile_screen') + ET.SubElement(profile, 'child', widget=NATIVE+'y_butn', x='78', y='414') + ET.SubElement(profile, 'child', widget=NATIVE+'=create_new', x='100', y='414') + + difficulty = widget('difficulty_list', type='column_list', width=640, height=480, + flags='pass_unhandled_to_focused_child up_down_tabs_items', + description=NATIVE+'difficulty_select\\difficulty_ext_desc') + ET.SubElement(difficulty, 'data', input='difficulty menu update desc') + ET.SubElement(difficulty, 'on', event='created', run='difficulty menu init') + for index in range(4): + name = 'difficulty_'+str(index) + child(difficulty, name) + row = widget(name, type='text', left=51, top=78+33*index, width=232, height=32, + bitmap='ui\\shell\\bitmaps\\list_item_bkd'+('_top' if index==0 else ''), + string_list=NATIVE+'difficulty_select\\difficulty_options', string_index=index, + font='ui\\large_ui', color='#FF0080FF', text_x=13, text_y=5) + for event in ('a', 'start'): on(row, event, 'choose') + ET.SubElement(row, 'on', event='left_mouse', run='mouse emit accept event') + + +def generate_art(target): + """The established OpenCE heading face in the native header's padded box.""" + from PIL import Image, ImageDraw, ImageFont + root = Path(__file__).resolve().parents[1] + font = ImageFont.truetype(str(root/'port/assets/fonts/OpenCE-Regular.ttf'), 128, + layout_engine=ImageFont.Layout.BASIC) + caption = 'MCC CAMPAIGNS' + box = font.getbbox(caption) + ink = Image.new('RGBA', (box[2]-box[0], box[3]-box[1])) + ImageDraw.Draw(ink).text((-box[0], -box[1]), caption, font=font, fill=(40, 150, 255, 255)) + ink = ink.resize((round(22*ink.width/ink.height)*4, 88), Image.Resampling.LANCZOS) + image = Image.new('RGBA', (512*4, 64*4)) + image.alpha_composite(ink, (29*4, 32*4)) + image.save(target/'mcc_campaigns.png') + generate_entry_art(target) + + +def generate_entry_art(target): + """Match the native main-menu title redraws: 19.5px capitals, two states.""" + from PIL import Image, ImageDraw, ImageFilter, ImageFont + root = Path(__file__).resolve().parents[1] + font = ImageFont.truetype(str(root/'port/assets/fonts/OpenCE-Regular.ttf'), 128, + layout_engine=ImageFont.Layout.BASIC) + caption = 'MCC CAMPAIGNS' + box = font.getbbox(caption) + ink = Image.new('L', (box[2]-box[0], box[3]-box[1])) + ImageDraw.Draw(ink).text((-box[0], -box[1]), caption, font=font, fill=255) + ink = ink.resize((round(78*ink.width/ink.height), 78), Image.Resampling.LANCZOS) + # Native titles are centered in 256x64 bitmaps, with their capitals at + # y=6.75. Widget hit boxes remain 256x33, matching the existing choices. + mask = Image.new('L', (1024, 256)) + mask.paste(ink, ((1024-ink.width)//2, 27)) + normal = Image.new('RGBA', mask.size, (35, 149, 255, 0)) + normal.putalpha(mask.point(lambda a: round(a*119/255))) + normal.save(target/'mcc_campaigns_entry_0.png') + selected = Image.new('RGBA', mask.size, (41, 149, 255, 0)) + selected.putalpha(mask.filter(ImageFilter.GaussianBlur(8)).point(lambda a: min(255, a*2))) + letters = Image.new('RGBA', mask.size, (255, 255, 255, 0)) + letters.putalpha(mask) + selected.alpha_composite(letters) + selected.save(target/'mcc_campaigns_entry_1.png') diff --git a/tools/net_compare.py b/tools/net_compare.py index 088acc5f09..8c636d758e 100644 --- a/tools/net_compare.py +++ b/tools/net_compare.py @@ -512,7 +512,9 @@ def latest_tick(path): # the copies running RUNNING = [] # the signals the tool stops on, and the one that stopped it -STOP_SIGNALS = (signal.SIGINT, signal.SIGTERM, signal.SIGHUP) +# Log parsing/judging is also used by Windows runners; the launcher below +# still uses POSIX process groups. Windows has no SIGHUP. +STOP_SIGNALS = (signal.SIGINT, signal.SIGTERM) + ((signal.SIGHUP,) if hasattr(signal, "SIGHUP") else ()) stopping = None diff --git a/tools/plasma_visual_build.py b/tools/plasma_visual_build.py new file mode 100644 index 0000000000..311e9e01a5 --- /dev/null +++ b/tools/plasma_visual_build.py @@ -0,0 +1,210 @@ +"""Build a capture-only executable, restoring normal source even on failure. + +Run from the repository with the Windows build environment configured. +Normal builds never include the fixture or its simulation hooks. +""" +from pathlib import Path +import shutil +import subprocess +import sys +import re +import shlex +import json +import hashlib +import argparse +from lighting_trace_check import instrument, instrument_collision + +ROOT = Path(__file__).resolve().parents[1] +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument('--output-dir', type=Path, default=ROOT/'build/plasma-visual') +parser.add_argument('--verify-traces', action='store_true') +args = parser.parse_args() +source = ROOT / 'port/linux/game/render_interpolation.c' +fixture = ROOT / 'port/linux/game/plasma_capture_fixture.c' +original = source.read_bytes() +main = ROOT / 'source/main/main.c' +backend = ROOT / 'port/linux/src/d3d8_gl.c' +main_original = main.read_bytes() +backend_original = backend.read_bytes() +plasma = ROOT / 'port/linux/game/plasma_lighting.c' +plasma_original = plasma.read_bytes() +environment = ROOT/'source/rasterizer/xbox/rasterizer_xbox_environment.c' +environment_original = environment.read_bytes() +projectiles = ROOT/'source/items/projectiles.c' +projectiles_original = projectiles.read_bytes() +occlusion = ROOT/'port/linux/game/plasma_occlusion.c' +occlusion_original = occlusion.read_bytes() +collision=ROOT/'port/linux/game/plasma_collision.c' +collision_original=collision.read_bytes() +collision_models=ROOT/'port/linux/game/plasma_collision_models.c' +collision_models_original=collision_models.read_bytes() +input_source=ROOT/'port/linux/src/xinput_sdl.c' +input_original=input_source.read_bytes() +rocket=ROOT/'port/linux/game/rocket_lighting.c' +rocket_original=rocket.read_bytes() +muzzle=ROOT/'port/linux/game/muzzle_lighting.c' +muzzle_original=muzzle.read_bytes() +covenant=ROOT/'port/linux/game/covenant_lighting.c' +covenant_original=covenant.read_bytes() +emitter=ROOT/'port/linux/game/covenant_emitter_lighting.c' +emitter_original=emitter.read_bytes() +shield=ROOT/'port/linux/game/shield_glow.c' +shield_original=shield.read_bytes() +assert not fixture.exists(), 'Refusing to overwrite an existing fixture' +out = args.output_dir.resolve() +assert out.is_relative_to((ROOT/'build').resolve()), 'Capture output must stay under build/' +out.mkdir(parents=True, exist_ok=True) +saved_args = shlex.split(re.search(r'^configure_args = (.*)$', + (ROOT / 'build.ninja').read_text(), re.M).group(1)) +manifest = dict(configure_args=saved_args, base_commit=subprocess.check_output( + ['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip(), source_hashes={}) +for path in [ROOT/'port/linux/game/plasma_collision_scene.c', ROOT/'port/linux/game/lighting_config.c', ROOT/'source/physics/collision_bsp.c', ROOT/'source/physics/collision_bsp.h', ROOT/'source/physics/collision_models.c', ROOT/'source/physics/collision_models.h', ROOT/'port/linux/game/ambient_emitter_lighting.c', ROOT/'port/linux/game/ambient_emitter_lighting.h', ROOT/'port/linux/game/lighting_menu.c', ROOT/'port/linux/game/authored_emitter_lighting.c', ROOT/'port/linux/game/authored_emitter_lighting.h', ROOT/'source/rasterizer/xbox/rasterizer_xbox_transparent_geometry.c', ROOT/'port/linux/game/needler_lighting.c', ROOT/'port/linux/game/ammo_counter_falloff.c', ROOT/'source/rasterizer/xbox/rasterizer_xbox_models.c', ROOT/'port/linux/game/ammo_counter_lighting.c', covenant, muzzle, ROOT/'source/items/weapons.c', ROOT/'port/linux/src/port_config.c', rocket, input_source, ROOT/'tools/fixtures/plasma_lighting_capture.c', source, main, backend, plasma, ROOT/'port/linux/game/plasma_falloff.c', + occlusion, ROOT/'port/linux/src/plasma_occlusion_gl.c', ROOT/'source/objects/object_lights.c', ROOT/'source/rasterizer/xbox/rasterizer_xbox.c', + ROOT/'port/linux/src/plasma_model_shader.c', ROOT/'port/linux/src/nv2a_vsh.c', ROOT/'port/linux/src/nv2a_psh.c', ROOT/'source/rasterizer/xbox/rasterizer_xbox_environment.c']: + manifest['source_hashes'][path.relative_to(ROOT).as_posix()] = hashlib.sha256(path.read_bytes()).hexdigest() +try: + manifest['source_hashes'][collision.relative_to(ROOT).as_posix()]=hashlib.sha256(collision_original).hexdigest() + manifest['source_hashes'][collision_models.relative_to(ROOT).as_posix()]=hashlib.sha256(collision_models_original).hexdigest() + header=ROOT/'port/linux/include/plasma_collision.h' + manifest['source_hashes'][header.relative_to(ROOT).as_posix()]=hashlib.sha256(header.read_bytes()).hexdigest() + manifest['verify_traces']=args.verify_traces + if args.verify_traces: + for path in [ROOT/'tools/lighting_trace_check.py', ROOT/'tools/fixtures/lighting_trace_check.inc']: + manifest['source_hashes'][path.relative_to(ROOT).as_posix()]=hashlib.sha256(path.read_bytes()).hexdigest() + for path in [shield, ROOT/'port/linux/game/overshield_effect.c', ROOT/'port/linux/game/shield_look.c']: + manifest['source_hashes'][path.relative_to(ROOT).as_posix()] = hashlib.sha256(path.read_bytes()).hexdigest() + text = 'void platform_log(const char *format,...);\n' + shield_original.decode().replace('\r\n','\n') + marker = '\t\tcolor.blue = sample.color.blue * glow->strength;' + assert text.count(marker) == 1 + text = text.replace(marker, marker+'\n\t\tplatform_log("SHIELD light time %.6f unit %ld strength %.5f position %.5f %.5f %.5f radius %.5f color %.5f %.5f %.5f", now, sample.unit_index, glow->strength, sample.position.x, sample.position.y, sample.position.z, sample.radius, color.red, color.green, color.blue);') + shield.write_text(text) + manifest['source_hashes'][emitter.relative_to(ROOT).as_posix()] = hashlib.sha256(emitter_original).hexdigest() + text = 'void platform_log(const char *format,...);\n' + emitter_original.decode().replace('\r\n','\n') + marker = '\t\temitter->connected = TRUE;' + assert text.count(marker) == 1 + text = text.replace(marker, marker+'\n\t\tplatform_log("EMITTER sample time %.6f strength %.6f kind %d position %.5f %.5f %.5f color %.5f %.5f %.5f", now, emitter->strength, emitter->kind, sample.position.x, sample.position.y, sample.position.z, color.red, color.green, color.blue);') + emitter.write_text(text) + text='int plasma_capture_skip_cinematic(void);\nint plasma_capture_turret_fire(void);\nint plasma_capture_scorpion_fire(void);\n'+input_original.decode().replace('\r\n','\n') + marker='\tif (seed < 0)' + assert marker in text + text=text.replace(marker,'\tif (getenv("HALO_PLASMA_CAPTURE_DOOR")) { pad->bAnalogButtons[XINPUT_GAMEPAD_A] = SDL_GetTicks()%1000 < 100 ? 255 : 0; return; }\n\tif (getenv("HALO_PLASMA_CAPTURE_COMBAT")) { pad->bAnalogButtons[XINPUT_GAMEPAD_RIGHT_TRIGGER] = (getenv("HALO_PLASMA_CAPTURE_KIND") && !strcmp(getenv("HALO_PLASMA_CAPTURE_KIND"), "pistol") ? SDL_GetTicks()%400 < 100 : SDL_GetTicks()%3000 < 2200) ? 255 : 0; return; }\n'+marker,1) + text = text.replace(marker, '\tif (getenv("HALO_MUZZLE_CAPTURE_WEAPON") && !getenv("HALO_MUZZLE_CAPTURE_CHARGED")) { pad->bAnalogButtons[XINPUT_GAMEPAD_RIGHT_TRIGGER] = SDL_GetTicks()%900 < 100 ? 255 : 0; return; }\n'+marker,1) + # Muzzle input must precede the general combat-fixture input. + start = text.index('\tif (getenv("HALO_MUZZLE_CAPTURE_WEAPON")') + end = text.index('\n', start) + 1 + line = text[start:end] + text = text[:start]+text[end:] + at = text.index('\tif (getenv("HALO_PLASMA_CAPTURE_COMBAT"))') + text = text[:at]+line+text[at:] + at = text.index('\tif (getenv("HALO_PLASMA_CAPTURE_COMBAT"))') + text = text[:at]+'\tif (getenv("HALO_WARTHOG_CAPTURE_EXTERIOR")) { pad->bAnalogButtons[XINPUT_GAMEPAD_RIGHT_TRIGGER] = plasma_capture_turret_fire() ? 255 : 0; return; }\n'+text[at:] + at = text.index('\tif (getenv("HALO_PLASMA_CAPTURE_COMBAT"))') + text = text[:at]+'\tif (getenv("HALO_SCORPION_CAPTURE")) { int fire = plasma_capture_scorpion_fire(); pad->bAnalogButtons[XINPUT_GAMEPAD_RIGHT_TRIGGER] = fire & 1 ? 255 : 0; pad->bAnalogButtons[XINPUT_GAMEPAD_LEFT_TRIGGER] = fire & 2 ? 255 : 0; return; }\n'+text[at:] + text = text.replace(marker, '\tif (getenv("HALO_COVENANT_CAPTURE_CAMPAIGN") && plasma_capture_skip_cinematic()) pad->bAnalogButtons[XINPUT_GAMEPAD_A] = SDL_GetTicks()%1000 < 100 ? 255 : 0;\n'+marker,1) + at = text.index('\tif (getenv("HALO_MUZZLE_CAPTURE_WEAPON")') + text = text[:at] + '\tif (getenv("HALO_LIGHTING_CAPTURE_TURN")) { pad->sThumbRX = (SHORT)(sin(SDL_GetTicks()*0.0007)*22000); pad->sThumbRY = (SHORT)(sin(SDL_GetTicks()*0.0004)*16000); }\n' + text[at:] + input_source.write_text(text) + shutil.copy2(ROOT / 'tools/fixtures/plasma_lighting_capture.c', fixture) + text = original.decode().replace('\r\n', '\n') + text = 'struct observer_result;\nstruct observer_result const *plasma_capture_view(struct observer_result const *source);\n' + text + camera = 'return render_interpolation_direct_camera(local_player_index,\n\t\trender_interpolation_blended_camera(local_player_index, observer));' + assert text.count(camera) == 1 + text = text.replace(camera, 'return plasma_capture_view(render_interpolation_direct_camera(local_player_index,\n\t\trender_interpolation_blended_camera(local_player_index, observer)));') + text = text.replace('void render_interpolation_tick(void)', + 'void plasma_capture_tick(void);\nvoid plasma_capture_frame(void);\n\nvoid render_interpolation_tick(void)', 1) + text = text.replace('long previous_tick = interpolation_tick++;', + 'long previous_tick = interpolation_tick++;\n\tplasma_capture_tick();', 1) + source.write_text(text) + text = projectiles_original.decode().replace('\r\n','\n') + text = 'int plasma_capture_hold_projectile(long index);\n'+text + begin = text.index('boolean projectile_update(') + marker = '\tprojectile = projectile_get(projectile_index);' + at = text.index(marker, begin) + text = text[:at]+'\tif (plasma_capture_hold_projectile(projectile_index)) return TRUE;\n'+text[at:] + projectiles.write_text(text) + text = occlusion_original.decode().replace('\r\n','\n') + text = 'void platform_log(const char *format,...);\n'+text + marker = '\tfield->valid = 1;' + assert text.count(marker) == 1 + text = text.replace(marker, marker+'\n\tplatform_log("PLASMA occlusion extent %.3f sample %.3f",field->extent,field->visibility[0]);') + occlusion.write_text(instrument(text) if args.verify_traces else text) + if args.verify_traces: + collision.write_text(instrument_collision(collision.read_text())) + collision_models.write_text(instrument_collision(collision_models.read_text())) + text = main_original.decode().replace('\r\n', '\n') + text = 'void plasma_capture_frame(void);\nvoid plasma_capture_camera(void);\n' + text + text = text.replace('main_game_render((double)main_globals.seconds_elapsed);', + 'plasma_capture_camera();\n\t\t\t\t\tmain_game_render((double)main_globals.seconds_elapsed);\n\t\t\t\t\tplasma_capture_frame();', 1) + main.write_text(text) + text = backend_original.decode().replace('\r\n', '\n') + text = 'int plasma_capture_should_capture(void);\nvoid plasma_capture_model_draw(unsigned int mask);\n' + text + marker = '\tentry = draw_program_get(program, immediate, &key, plasma_mask);' + assert text.count(marker) == 1 + text = text.replace(marker, marker+'\n\tplasma_capture_model_draw(plasma_mask);', 1) + text = text.replace('if (screenshot_every > 0 && device.frame % (unsigned long)screenshot_every == 0)', + 'if (plasma_capture_should_capture())', 1) + backend.write_text(text) + text = environment_original.decode().replace('\r\n', '\n') + text = 'void plasma_capture_specular_begin(long index);\nvoid plasma_capture_specular_draw(void);\n' + text + text = text.replace('void _rasterizer_environment_specular_light_begin(\n\tlong light_index)\n{', 'void _rasterizer_environment_specular_light_begin(\n\tlong light_index)\n{\n\tplasma_capture_specular_begin(light_index);', 1) + start = text.index('void _rasterizer_environment_specular_light_draw(') + end = text.index('void _rasterizer_environment_specular_lights_end(', start) + part = text[start:end] + marker = '\t\trasterizer_draw_dynamic_triangles_static_vertices(' + assert marker in part + part = part.replace(marker, '\t\tplasma_capture_specular_draw();\n' + marker) + text = text[:start] + part + text[end:] + environment.write_text(text) + text = plasma_original.decode().replace('\r\n', '\n') + text = 'void platform_log(const char *format, ...);\n' + text + marker = '\tif (!light_port_refresh_attachment(light_index, object_index))' + assert text.count(marker) == 1 + text = text.replace(marker, '\tplatform_log("PLASMA prepare %ld owner %ld tag %s", light_index, object_index, name);\n' + marker) + text = text.replace('plasma_lighting_attachments[index].rasterizer_index = rasterizer_index;', + '{ plasma_lighting_attachments[index].rasterizer_index = rasterizer_index; platform_log("PLASMA submit %ld", rasterizer_index); }', 1) + plasma.write_text(text) + text = rocket_original.decode().replace('\r\n', '\n') + text = 'void platform_log(const char *format,...);\n' + text + marker = '\t\t\trocket_lights[i].rasterizer_index = rasterizer_index;' + assert marker in text + text = text.replace(marker, marker + '\n\t\t\tplatform_log("PLASMA prepare %ld owner %ld tag weapons\\\\rocket launcher\\\\rocket", light_index, rocket_lights[i].object_index);') + rocket.write_text(text) + text = covenant_original.decode().replace('\r\n','\n') + text = 'void platform_log(const char *format,...);\n' + text + marker = '\t\t\tcovenant_lights[i].rasterizer_index = rasterizer_index;' + assert text.count(marker) == 1 + text = text.replace(marker, marker + '\n\t\t\tplatform_log("PLASMA prepare %ld owner %ld tag %s", light_index, covenant_lights[i].object_index, covenant_profiles[covenant_lights[i].profile].tag);') + covenant.write_text(text) + text = muzzle_original.decode().replace('\r\n','\n') + text = 'void platform_log(const char *format,...);\n' + text + marker = '\t\tpulse->connected = TRUE;' + assert text.count(marker) == 1 + text = text.replace(marker, marker+'\n\t\tplatform_log("MUZZLE sample tick %ld time %.6f strength %.6f position %.5f %.5f %.5f weapon %ld trigger %d", game_time_get(), now, strength, position.x, position.y, position.z, pulse->weapon, pulse->trigger);\n\t\tplatform_log("MUZZLE profile %s", muzzle_profiles[pulse->profile].tag);') + marker = '\t\t\tpulses[i].rasterizer = rasterizer_index;' + assert text.count(marker) == 1 + text = text.replace(marker, marker+'\n\t\t\tplatform_log("MUZZLE submit %ld", rasterizer_index);') + muzzle.write_text(text) + subprocess.run([sys.executable, 'configure.py', *saved_args], cwd=ROOT, check=True) + subprocess.run(['ninja', 'windows'], cwd=ROOT, check=True) + shutil.copy2(ROOT / 'build/windows/halo.exe', out / 'halo-capture.exe') + manifest['capture_sha256'] = hashlib.sha256((out/'halo-capture.exe').read_bytes()).hexdigest() + (out/'build-manifest.json').write_text(json.dumps(manifest, indent=2)) +finally: + shield.write_bytes(shield_original) + emitter.write_bytes(emitter_original) + covenant.write_bytes(covenant_original) + muzzle.write_bytes(muzzle_original) + rocket.write_bytes(rocket_original) + input_source.write_bytes(input_original) + source.write_bytes(original) + main.write_bytes(main_original) + backend.write_bytes(backend_original) + plasma.write_bytes(plasma_original) + environment.write_bytes(environment_original) + projectiles.write_bytes(projectiles_original) + occlusion.write_bytes(occlusion_original) + collision.write_bytes(collision_original) + collision_models.write_bytes(collision_models_original) + fixture.unlink(missing_ok=True) + subprocess.run([sys.executable, 'configure.py', *saved_args], cwd=ROOT, check=True) + subprocess.run(['ninja', 'windows'], cwd=ROOT, check=True) diff --git a/tools/plasma_visual_run.py b/tools/plasma_visual_run.py new file mode 100644 index 0000000000..c55fff1cd8 --- /dev/null +++ b/tools/plasma_visual_run.py @@ -0,0 +1,358 @@ +"""Run the capture-only build with isolated data, retaining images and timing. + +Example: python tools/plasma_visual_run.py --data-root C:/Games/GulchCE --fps 60 --enabled 1 +Only this runner's copied maps and generated map caches are removed. +""" +import argparse +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import statistics + +parser = argparse.ArgumentParser() +parser.add_argument('--data-root', required=True, type=Path) +parser.add_argument('--capture-dir', type=Path, help='Directory containing halo-capture.exe and its build manifest') +parser.add_argument('--fps', required=True, type=int, choices=[30, 60, 120, 240]) +parser.add_argument('--enabled', required=True, type=int, choices=[0, 1]) +parser.add_argument('--label', default='') +parser.add_argument('--map', choices=['bloodgulch', 'carousel', 'a10', 'b40', 'c40', 'ce-deathisland', 'mcc-digsite', 'mcc-ruby-c40']) +parser.add_argument('--kind', choices=['rifle','pistol','charged','rocket','needle','ghost','banshee','banshee-fuel','shade','fuel','wraith','mp-needle','mp-banshee-fuel','mp-shade','ce-fuel','grenade'], default='rifle') +parser.add_argument('--muzzle', choices=['ar','handgun','shotgun','sniper','rifle','pistol','charged','needler','rocket','flamethrower','warthog','scorpion']) +parser.add_argument('--both-lighting', action='store_true') +parser.add_argument('--prong-lighting', action='store_true', help='Isolate the standalone plasma prong spill in a rifle/pistol combat capture') +parser.add_argument('--weapon-glow', action='store_true', help='Exercise authored sword and charge lights') +parser.add_argument('--emitter', choices=['sword-elite','jackal','major','fuel','hunter','stationary','ammo-fp','ammo-marine','ammo-player','needler-fp','needler-marine','needler-player','needler-grunt']) +parser.add_argument('--ambient', choices=['ghost','banshee','dropship','warthog','scorpion','overshield','camo','teleporter']) +parser.add_argument('--shield', choices=['normal', 'charge', 'fp', 'elite']) +parser.add_argument('--glow-intensity', choices=['default','light_show'], default='default') +parser.add_argument('--shield-look', default='classic', choices=['classic','enhanced','classic_with_sprinkles','classic_honeycomb2']) +parser.add_argument('--turn', action='store_true', help='Capture-only yaw/pitch sweep for light orientation checks') +parser.add_argument('--hide-viewmodel', action='store_true', help='Keep the local rifle from obscuring third-person receivers') +parser.add_argument('--face-camera', action='store_true', help='Face a held-weapon fixture toward the camera to inspect torso and hand spill') +parser.add_argument('--grounded', action='store_true', help='Place the held-weapon actor on the actual floor') +parser.add_argument('--crouch', action='store_true', help='Exercise a held-weapon actor crouching and standing again') +parser.add_argument('--exterior', action='store_true', help='View the vehicle fixture from outside to inspect chassis blocking') +parser.add_argument('--sparse-images', action='store_true', help='Retain one image every three simulation ticks') +parser.add_argument('--image-step', type=int, choices=range(1,31), default=3, help='Simulation ticks between sparse captures') +parser.add_argument('--counter-detail', action='store_true', help='View a held world-model AR display over its holder\'s shoulder') +parser.add_argument('--resolution', default='640x480', help='Capture window size, for example 1280x720') +parser.add_argument('--mixed', action='store_true') +parser.add_argument('--model', action='store_true') +parser.add_argument('--occlusion', type=int, choices=[0,1], default=0) +parser.add_argument('--probe', action='store_true') +parser.add_argument('--no-images', action='store_true', help='Measure without screenshot readback or disk writes') +parser.add_argument('--combat', action='store_true') +parser.add_argument('--door', action='store_true') +parser.add_argument('--toggle', action='store_true') +parser.add_argument('--span', type=float) +parser.add_argument('--burst', type=int, choices=range(1,33), default=1) +parser.add_argument('--specular-only', action='store_true') +parser.add_argument('--per-pixel', action='store_true') +parser.add_argument('--distance', type=float) +parser.add_argument('--height', type=float) +parser.add_argument('--drop', type=float) +parser.add_argument('--receiver-distance', type=float) +args = parser.parse_args() +if args.prong_lighting: + if not args.combat or args.kind not in ('rifle', 'pistol') or args.weapon_glow or args.muzzle: + parser.error('--prong-lighting requires rifle/pistol --combat, without other weapon-light options') +if args.toggle and (args.emitter or args.ambient or args.shield or args.muzzle): + parser.error('--toggle requires a projectile capture; emitter, shield and muzzle fixtures use separate tick handlers') +if not re.fullmatch(r'[1-9][0-9]{2,3}x[1-9][0-9]{2,3}', args.resolution): + parser.error('--resolution must be WIDTHxHEIGHT') +if args.counter_detail and args.emitter not in ('ammo-player', 'ammo-marine'): + parser.error('--counter-detail requires a third-person AR holder') +if args.exterior and args.muzzle not in ('warthog', 'scorpion'): + parser.error('--exterior requires --muzzle warthog or scorpion') +if args.crouch and not args.shield and args.emitter not in ('ammo-player', 'ammo-marine', 'needler-player', 'needler-marine'): + parser.error('--crouch requires a third-person player or Marine emitter') +if args.map is None: + # Blood Gulch has no machine door for the moving-occluder fixture. + args.map = 'a10' if args.door else 'bloodgulch' +if args.muzzle: + args.combat = True +root = Path(__file__).resolve().parents[1] +assert re.fullmatch(r'[a-zA-Z0-9_-]*', args.label) +out = root / f'build/plasma-visual/{args.fps}-{args.enabled}{"-" + args.label if args.label else ""}' +out.mkdir(parents=True, exist_ok=False) +(out / 'maps').mkdir() +(out / 'screenshots').mkdir() +capture_dir = args.capture_dir.resolve() if args.capture_dir else root/'build/plasma-visual' +manifest = capture_dir/'build-manifest.json' +if manifest.exists(): + shutil.copy2(manifest, out/'build-manifest.json') +shutil.copy2(args.data_root/'maps/ui.map',out/'maps/ui.map') +if args.map=='ce-deathisland': + (out/'custom_maps').mkdir() + # Accept the original CE filename as well as the earlier fixture's name. + ce_map = 'deathisland_451254bb' if (args.data_root/'custom_maps/deathisland_451254bb.map').is_file() else 'deathisland' + for name in [ce_map+'.map','bitmaps.map','sounds.map','loc.map']: + shutil.copy2(args.data_root/'custom_maps'/name,out/'custom_maps'/name) + level='custom_maps\\'+ce_map +elif args.map=='mcc-digsite': + for name in ['1.map','bitmaps.map','sounds.map']: + target=out/'mcc_maps'/'DigsiteMP'/name + target.parent.mkdir(parents=True,exist_ok=True) + shutil.copy2(args.data_root/'mcc_maps'/'DigsiteMP'/name,target) + level=r'mcc_maps\DigsiteMP\1' +elif args.map=='mcc-ruby-c40': + for name in ['RubyRebalanced/c40.map', '_shared/singleplayer/bitmaps.map']: + target=out/'mcc_maps'/name + target.parent.mkdir(parents=True,exist_ok=True) + shutil.copy2(args.data_root/'mcc_maps'/name,target) + level=r'mcc_maps\RubyRebalanced\c40' +else: + shutil.copy2(args.data_root/'maps'/(args.map+'.map'),out/'maps'/(args.map+'.map')) + level=f'levels\\{args.map}\\{args.map}' if args.map in ('a10','b40','c40') else f'levels\\test\\{args.map}\\{args.map}' +(out/'init.txt').write_text(f'map_name {level}\n') +if args.specular_only: + with (out/'init.txt').open('a') as init: + init.write('(set rasterizer_environment_diffuse_lights false)\n') + +env = {k:v for k,v in os.environ.items() if not k.startswith('HALO_')} +env['PATH'] = str(root / 'build/windows') + os.pathsep + env.get('PATH', '') +env.update(HALO_DATA_ROOT=str(out), HALO_SAVE_ROOT=str(out/'saves'), HALO_HIDDEN_WINDOW='1', + HALO_NO_AUDIO='1', HALO_MAX_FPS=str(args.fps), HALO_NO_VSYNC='1', HALO_EXIT_AFTER='25' if args.door else '13', + HALO_NET_ONLINE='0', HALO_NET_PUBLIC_LOBBY='0', HALO_UPDATE_ANSWER='never', + HALO_NET_JOIN_FROM_CLIPBOARD='0', HALO_NET_ALLOW_UPNP='0', + HALO_CRASH_REPORTS='no', HALO_WINDOW_SIZE=args.resolution, HALO_PLASMA_LIGHTING=str(args.enabled), + HALO_SCREENSHOT_DIR=str(out/'screenshots'), HALO_PLASMA_OCCLUSION=str(args.occlusion)) +if args.map == 'mcc-digsite': + # This multiplayer package's scenario script is not a player-spawn path. + # Start an ordinary isolated local match, as the compatibility runner does, + # rather than capturing its empty campaign-style map_name session. + (out/'init.txt').write_text('') + env.update(HALO_NETWORK_TEST='local:'+level+':slayer', HALO_NETWORK_TEST_START='3', + HALO_NET_ADDRESS='127.0.0.86', HALO_NET_BROADCAST='127.0.0.86', + HALO_EXIT_AFTER='35') +if args.map in ('b40', 'c40', 'mcc-ruby-c40'): + env['HALO_COVENANT_CAPTURE_CAMPAIGN'] = '1' + env['HALO_EXIT_AFTER'] = '70' if args.map in ('b40', 'mcc-ruby-c40') else '35' +if args.prong_lighting: + env.update(HALO_PLASMA_PRONG_LIGHTING=str(args.enabled), HALO_PLASMA_LIGHTING='0') +if args.weapon_glow: + env['HALO_WEAPON_GLOW'] = str(args.enabled) +if args.turn: + env['HALO_LIGHTING_CAPTURE_TURN'] = '1' +if args.hide_viewmodel: + env['HALO_VIEWMODEL_VISIBLE'] = '0' +if args.face_camera: + env['HALO_EMITTER_CAPTURE_FACE_CAMERA'] = '1' +if args.grounded: + env['HALO_EMITTER_CAPTURE_GROUNDED'] = '1' +if args.crouch: + env['HALO_EMITTER_CAPTURE_CROUCH'] = '1' +if args.exterior and args.muzzle == 'warthog': + env['HALO_WARTHOG_CAPTURE_EXTERIOR'] = '1' +if args.sparse_images: + env['HALO_LIGHTING_CAPTURE_SPARSE'] = '1' + env['HALO_LIGHTING_CAPTURE_IMAGE_STEP'] = str(args.image_step) +if args.counter_detail: + env['HALO_EMITTER_CAPTURE_COUNTER_DETAIL'] = '1' +if args.emitter: + env['HALO_EXIT_AFTER'] = '70' if args.map in ('b40', 'mcc-ruby-c40') else '35' + env['HALO_EMITTER_CAPTURE'] = args.emitter + env['HALO_PLASMA_LIGHTING'] = '0' + env[{'jackal':'HALO_JACKAL_SHIELD_LIGHTING', 'major':'HALO_JACKAL_SHIELD_LIGHTING', + 'fuel':'HALO_FUEL_ROD_LIGHTING', 'hunter':'HALO_FUEL_ROD_LIGHTING', 'stationary':'HALO_COVENANT_SHIELD_LIGHTING', + 'ammo-fp':'HALO_AMMO_COUNTER_LIGHTING','ammo-marine':'HALO_AMMO_COUNTER_LIGHTING', + 'ammo-player':'HALO_AMMO_COUNTER_LIGHTING', 'needler-fp':'HALO_NEEDLER_LIGHTING', + 'needler-player':'HALO_NEEDLER_LIGHTING','needler-marine':'HALO_NEEDLER_LIGHTING', + 'needler-grunt':'HALO_NEEDLER_LIGHTING', 'sword-elite':'HALO_WEAPON_GLOW'}[args.emitter]] = str(args.enabled) +if args.ambient: + env['HALO_AMBIENT_CAPTURE']=args.ambient + env['HALO_PLASMA_LIGHTING']='0' + env['HALO_VEHICLE_LIGHTING' if args.ambient in ('ghost','banshee','dropship','warthog','scorpion') else 'HALO_WORLD_LIGHTING']=str(args.enabled) +if args.shield: + env.update(HALO_SHIELD_CAPTURE=args.shield, HALO_SHIELD_GLOW=str(args.enabled), + HALO_OVERSHIELD_EFFECT=str(int(args.shield in ('charge','fp'))), HALO_VIEWMODEL_SHIELD='1', + HALO_SHIELD_LOOK=args.shield_look, HALO_SHIELD_GLOW_INTENSITY=args.glow_intensity, HALO_PLASMA_LIGHTING='0') +if args.muzzle: + muzzle_tags = { + 'ar': r'weapons\assault rifle\assault rifle', 'handgun': r'weapons\pistol\pistol', + 'shotgun': r'weapons\shotgun\shotgun', 'sniper': r'weapons\sniper rifle\sniper rifle', + 'rifle': r'weapons\plasma rifle\plasma rifle', 'pistol': r'weapons\plasma pistol\plasma pistol', + 'charged': r'weapons\plasma pistol\plasma pistol', + 'needler': r'weapons\needler\mp_needler' if args.map == 'ce-deathisland' else r'weapons\needler\needler', + 'rocket': r'weapons\rocket launcher\rocket launcher', 'flamethrower': r'weapons\flamethrower\flamethrower', + 'warthog': r'vehicles\warthog\warthog gun', + 'scorpion': r'vehicles\scorpion\scorpion cannon', + } + env['HALO_MUZZLE_CAPTURE_WEAPON'] = muzzle_tags[args.muzzle] + env['HALO_MUZZLE_LIGHTING'] = str(args.enabled) + env['HALO_PLASMA_LIGHTING'] = str(int(args.both_lighting)) + if args.muzzle in ('warthog', 'scorpion'): + env['HALO_' + args.muzzle.upper() + '_CAPTURE'] = '1' + # The vehicle fixture equips its own weapon. Use the combat fixture's + # sustained bursts rather than the handheld muzzle fixture's tap input. + env.pop('HALO_MUZZLE_CAPTURE_WEAPON') + if args.muzzle == 'charged': + env['HALO_MUZZLE_CAPTURE_CHARGED'] = '1' + args.kind = 'charged' +for key in ['distance', 'height', 'receiver_distance', 'span', 'burst', 'drop']: + value = getattr(args, key) + if value is not None: + env['HALO_PLASMA_CAPTURE_'+key.upper()] = str(value) +env['HALO_PLASMA_CAPTURE_KIND'] = args.kind +for key in ['combat','door','toggle','mixed']: + if getattr(args,key):env['HALO_PLASMA_CAPTURE_'+key.upper()]='1' +if args.probe: + env['HALO_PLASMA_CAPTURE_PROBE']='1' +if args.no_images: + env['HALO_PLASMA_CAPTURE_NO_IMAGES']='1' +if args.model: + env['HALO_PLASMA_CAPTURE_MODEL'] = '1' +if args.per_pixel: + env['HALO_PER_PIXEL_LIGHTING'] = '1' +with (out/'stdout.log').open('wb') as so, (out/'stderr.log').open('wb') as se: + capture_executable = capture_dir/'halo-capture.exe' + process = subprocess.Popen([str(capture_executable)], cwd=out, + env=env, stdout=so, stderr=se, creationflags=subprocess.CREATE_NO_WINDOW) + try: + process.wait(timeout=145 if args.map in ('b40', 'c40', 'mcc-ruby-c40') else 45) + finally: + if process.poll() is None: + process.terminate() + process.wait(timeout=10) +logs = '\n'.join(p.read_text(errors='replace') for p in out.glob('*.log')) +times = [int(x) for x in re.findall(r'PLASMA frame (\d+)', logs)] +deltas = [b-a for a,b in zip(times, times[1:]) if b>a] +report = dict(kind=args.kind, mixed=args.mixed, cap=args.fps, enabled=args.enabled, exit=process.returncode, + screenshots=len(list((out/'screenshots').glob('*.bmp'))), frames=len(times), + selected_frames=len(re.findall(r'selected [1-9]', logs)), + average_fps=1000*(len(times)-1)/(times[-1]-times[0]) if len(times)>1 else None, + median_ms=statistics.median(deltas) if deltas else None, + shots=len(re.findall('PLASMA shot', logs)), + model_draws=sum(int(x) for x in re.findall(r'PLASMA draws model (\d+)', logs)), + specular_draws=sum(int(x) for x in re.findall(r'PLASMA draws model \d+ specular (\d+)', logs)), + max_selected=max([int(x) for x in re.findall(r'selected (\d+)',logs)] or [0]), burst=args.burst, combat=args.combat, door=args.door, toggle=args.toggle, occlusion=args.occlusion, probe=args.probe, occlusion_updates=len(re.findall('PLASMA occlusion extent',logs)), map=args.map, model=args.model, per_pixel=args.per_pixel, specular_only=args.specular_only) +report['authored_light_flags'] = sorted({int(x, 16) for x in re.findall(r'PLASMA enabled [01] light flags ([0-9a-f]+)', logs)}) +report['glow_template_flags'] = sorted({int(x, 16) for x in re.findall(r'PLASMA glow template [^\r\n]+ flags ([0-9a-f]+)', logs)}) +report['no_images'] = args.no_images +active_frames = [(int(t), int(n)) for t, n in re.findall(r'PLASMA frame (\d+)[^\r\n]+ selected (\d+)', logs)] +active_deltas = [b[0]-a[0] for a, b in zip(active_frames, active_frames[1:]) if a[1] and b[1] and b[0] > a[0]] +report['active_average_fps'] = 1000 / statistics.mean(active_deltas) if active_deltas else None +report['active_p95_ms'] = sorted(active_deltas)[int((len(active_deltas)-1)*.95)] if active_deltas else None +report['homing_shots'] = len(re.findall('PLASMA homing', logs)) +report['selected_tags'] = sorted(set(re.findall(r'PLASMA prepare [^\r\n]+ tag ([^\r\n]+)', logs))) +report['muzzle'] = args.muzzle +report['shield'] = args.shield +report['shield_look'] = args.shield_look +report['glow_intensity'] = args.glow_intensity +report['shield_created'] = bool(re.search(r'SHIELD created (?!-1 )', logs)) +report['ambient'] = args.ambient +report['ambient_created'] = bool(re.search(r'AMBIENT created (?!-1 )', logs)) +report['emitter'] = args.emitter +report['hide_viewmodel'] = args.hide_viewmodel +report['face_camera'] = args.face_camera +report['grounded'] = args.grounded +report['crouch'] = args.crouch +report['exterior'] = args.exterior +report['holder_crouch_samples'] = [float(x) for x in re.findall(r'EMITTER holder tick \d+ crouch ([0-9.]+)', logs)] +report['turn'] = args.turn +report['counter_detail'] = args.counter_detail +report['resolution'] = args.resolution +report['emitter_samples'] = len(re.findall('EMITTER sample', logs)) +report['emitter_created'] = bool(re.search(r'EMITTER created (?!-1 )', logs)) +report['both_lighting'] = args.both_lighting +report['muzzle_submissions'] = len(re.findall('MUZZLE submit', logs)) +report['muzzle_fade_samples'] = sum(0 < float(x) < .99 for x in re.findall(r'MUZZLE sample[^\r\n]+ strength ([0-9.]+)', logs)) +(out/'report.json').write_text(json.dumps(report, indent=2)) +print(json.dumps(report), flush=True) +for path in out.rglob('*.map'): + assert path.resolve().is_relative_to(out.resolve()) + path.unlink() +if process.returncode or (report['shots'] != 3 and not args.combat and not args.emitter and not args.shield and not args.ambient) or (not args.no_images and not report['screenshots']): + raise SystemExit('Capture incomplete; inspect report.json and logs') +if args.ambient and not report['ambient_created']: + raise SystemExit('Ambient fixture missing; this is not a passing capture') +if args.shield and not report['shield_created']: + raise SystemExit('Shield fixture did not create its actor') +if args.emitter and (not report['emitter_created'] or (args.emitter != 'sword-elite' and bool(report['emitter_samples']) != bool(args.enabled))): + raise SystemExit('Emitter creation or activation failed') +if args.emitter == 'sword-elite' and args.enabled and r'weapons\energy sword\energy sword' not in report['selected_tags']: + raise SystemExit('Sword attachment never entered enhanced lighting') +if args.crouch and not args.shield and report['holder_crouch_samples'] != [1.0, 1.0, 0.0]: + raise SystemExit('Holder did not crouch and return to standing') +if bool(report['selected_frames']) != bool(args.enabled or (args.muzzle and args.both_lighting)): + raise SystemExit('Lighting selection did not match the requested mode') +if report['average_fps'] is None or report['average_fps'] < args.fps * .95: + raise SystemExit('Capture did not sustain the requested FPS within 5 percent') + +if args.enabled and args.model and not report['model_draws']: + raise SystemExit('Capture never reached a selected model draw') +if args.enabled and args.specular_only: + flags = report['authored_light_flags'] or report['glow_template_flags'] + # Bit 1 is _light_definition_no_specular_bit in object_lights.c. + if flags and all(value & 2 for value in flags): + if report['specular_draws']: + raise SystemExit('Capture ignored the authored no-specular flag') + elif not report['specular_draws']: + raise SystemExit('Capture never reached a selected specular draw') + +if args.enabled and args.occlusion and not report['occlusion_updates']: + raise SystemExit('Capture did not update any occlusion fields') + +if args.combat and 'PLASMA combat equipped' not in logs: + raise SystemExit('Combat fixture did not equip the requested weapon') +if args.probe and args.enabled and report['max_selected'] < (min(args.burst, 8) if args.kind in ('needle', 'mp-needle', 'wraith') else args.burst): + raise SystemExit('Stress capture did not select the requested simultaneous light count') +if args.door: + positions = [float(x) for x in re.findall(r'PLASMA door position ([0-9.]+)', logs)] + if not positions or min(positions) > .1 or max(positions) < .9: + raise SystemExit('Door did not complete both open and closed states') +if args.toggle: + intervals = re.split(r'PLASMA toggle ([01])', logs) + if len(intervals) < 5: + raise SystemExit('Toggle capture did not exercise both states') + for i in range(1, len(intervals)-1, 2): + if intervals[i] == '0' and 'PLASMA occlusion extent' in intervals[i+1]: + raise SystemExit('Occlusion updated while disabled') + +expected_tags = { + 'grenade': r'weapons\plasma grenade\plasma grenade', + 'rifle': r'weapons\plasma rifle\bolt', + 'pistol': r'weapons\plasma pistol\bolt', + 'charged': r'weapons\plasma rifle\charged bolt', + 'rocket': r'weapons\rocket launcher\rocket', + 'needle': 'weapons\\needler\\needle', + 'ghost': 'vehicles\\ghost\\ghost bolt', + 'banshee': 'vehicles\\banshee\\banshee bolt', + 'banshee-fuel': 'vehicles\\banshee\\banshee fuel rod', + 'shade': 'vehicles\\c gun turret\\c gun turret', + 'fuel': 'weapons\\fuel rod gun\\fuel rod', + 'wraith': 'vehicles\\wraith\\wraith mortar', + 'mp-needle': 'weapons\\needler\\mp_needle', + 'mp-banshee-fuel': 'vehicles\\banshee\\mp_banshee fuel rod', + 'mp-shade': 'vehicles\\c gun turret\\mp gun turret', + 'ce-fuel': 'weapons\\plasma_cannon\\plasma_cannon', +} +if args.enabled and not args.prong_lighting and not args.muzzle and not args.emitter and not args.shield and not args.ambient: + expected = {expected_tags[args.kind]} + if args.mixed: + expected = {expected_tags[kind] for kind in ('rifle', 'pistol', 'charged', 'rocket') if args.kind == 'rocket' or kind != 'rocket'} + if not expected.issubset(report['selected_tags']): + raise SystemExit('Capture did not select every requested projectile kind') +if not args.enabled and not (args.muzzle and args.both_lighting and args.occlusion) and report['occlusion_updates']: + raise SystemExit('Disabled lighting still updated occlusion') +if args.kind == 'charged' and args.model and not args.probe and not args.combat and report['homing_shots'] != 3: + raise SystemExit('Charged-shot capture did not exercise the homing target') + +if args.muzzle and args.enabled and (not report['muzzle_submissions'] or not report['muzzle_fade_samples']): + raise SystemExit('Muzzle capture did not exercise submission and smooth fade') +if args.muzzle and not args.enabled and report['muzzle_submissions']: + raise SystemExit('Disabled muzzle feature still submitted lights') + +if args.muzzle == "warthog" and args.enabled and r"MUZZLE profile vehicles\warthog\warthog gun" not in logs: + raise SystemExit("Capture did not fire the Warthog turret") +if args.muzzle == 'scorpion' and args.enabled: + if r'MUZZLE profile vehicles\scorpion\scorpion cannon' not in logs or set(re.findall(r'MUZZLE sample[^\r\n]+ trigger ([01])', logs)) != {'0', '1'}: + raise SystemExit('Capture did not fire both Scorpion guns') + +if args.prong_lighting and args.enabled: + expected = 'weapons\\plasma '+args.kind+'\\plasma '+args.kind + if expected not in report['selected_tags']: + raise SystemExit('Prong capture never selected the intended weapon attachment') diff --git a/tools/player_notes.py b/tools/player_notes.py new file mode 100644 index 0000000000..39ed89ca6a --- /dev/null +++ b/tools/player_notes.py @@ -0,0 +1,360 @@ +#!/usr/bin/env python3 +"""Collect authored Player-Note lines from Git, without subject fallbacks.""" + +import argparse +from dataclasses import dataclass +from datetime import date +import json +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile + +ROOT = Path(__file__).resolve().parents[1] +MAX_ENTRIES = 8 +MAX_NOTES = 4096 +MAX_BUILD_NUMBER = 2147483647 +SHA = re.compile(r"[0-9a-fA-F]{40}\Z") +CATEGORY = re.compile(r"[A-Z][A-Z0-9]*(?: [A-Z0-9]+)*\Z") +# Repair the published testing merge's category spelling without rewriting +# history. Only this immutable commit gets the correction; new notes stay strict. +HISTORICAL_NOTE_PREFIXES = { + "4f3eec76a1165a111bff83047b064a55c156f3bc": + ("Player-Note: [Android] ", "Player-Note: [ANDROID] "), +} +# A published main promotion was corrected before release. Suppress its withdrawn +# note only where the explicit withdrawal is in history; testing keeps its note. +# A future restoration must carry its own reviewed Player-Note annotation. +HISTORICAL_NOTE_WITHDRAWALS = { + "192ba0b5c0c1549b76bc7b21de786c9fd7202711": + "9bf9554aa86dbeba9fa49f5d8ff1b99f2ba82c1b", +} + + +class NotesError(ValueError): + """An invalid annotation, manifest or Git range.""" + + +@dataclass +class Commit: + sha: str + parents: list + notes: list + omitted: bool + + +def git(repo, *args): + result = subprocess.run( + ["git", "--no-pager", "--no-replace-objects", *args], cwd=repo, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False, + ) + if result.returncode: + detail = result.stderr.decode("utf-8", errors="replace").strip() + raise NotesError(f"git {args[0]} failed: {detail}") + return result.stdout.decode("utf-8", errors="replace") + + +def resolve_commit(repo, value, label, allow_head=False): + if not isinstance(value, str) or not (SHA.fullmatch(value) or (allow_head and value == "HEAD")): + raise NotesError(f"{label} must be a full 40-character commit SHA" + + (" or HEAD" if allow_head else "")) + try: + sha = git(repo, "rev-parse", "--verify", "--end-of-options", value).strip() + object_type = git(repo, "cat-file", "-t", sha).strip() + except NotesError as exc: + raise NotesError(f"{label} {value} is unavailable; fetch complete history or correct the SHA: {exc}") from exc + if object_type != "commit": + raise NotesError(f"{label} {value} does not name a commit") + return sha + + +def require_ancestor(repo, ancestor, head, label): + # The count also distinguishes an unavailable object from a non-ancestor. + if git(repo, "rev-list", "--count", ancestor, "^" + head, "--").strip() != "0": + raise NotesError(f"{label} {ancestor} is not an ancestor of head {head}") + + +def validate_note(text, context): + if not isinstance(text, str) or not 1 <= len(text) <= 100: + raise NotesError(f"{context}: note must contain 1 to 100 printable ASCII characters") + if any(ord(c) < 32 or ord(c) > 126 or c in "\\|" for c in text): + raise NotesError(f"{context}: note must be printable ASCII without backslashes or menu pipes") + text = text.strip(" ") + if not text: + raise NotesError(f"{context}: note is empty; use Player-Note: none to omit a commit") + return text + + +def validate_category(category, context, allow_empty=True): + if allow_empty and category == "": + return category + if not isinstance(category, str) or not 1 <= len(category) <= 24 or not CATEGORY.fullmatch(category): + raise NotesError(f"{context}: category must be 1 to 24 uppercase ASCII letters, digits and single spaces, starting with a letter") + return category + + +def validate_categories(categories, notes, context): + if not isinstance(categories, list) or len(categories) != len(notes): + raise NotesError(f"{context}: categories must be a list with exactly one label per note") + return [validate_category(category, context) for category in categories] + + +def parse_notes(message, context): + notes = [] + omitted = False + # Split only at LF: splitlines() would silently consume hostile controls. + for line in message.split("\n"): + if not line.lower().startswith("player-note:"): + continue + if not line.startswith("Player-Note:"): + raise NotesError(f"{context}: malformed annotation; use Player-Note: short sentence") + text = line[len("Player-Note:"):] + text = text.strip(" ") + category = "" + if text.startswith("["): + match = re.fullmatch(r"\[([^\]]*)\] (.*)", text) + if match is None: + raise NotesError(f"{context}: use Player-Note: [CATEGORY] short sentence for categorized notes") + category = validate_category(match[1], context, allow_empty=False) + text = match[2] + text = validate_note(text, context) + if text.casefold() == "none": + if category: + raise NotesError(f"{context}: Player-Note: none cannot have a category") + omitted = True + else: + notes.append((text, category)) + if omitted and notes: + raise NotesError(f"{context}: Player-Note: none cannot accompany player notes") + return notes, omitted + + +def note_key(text): + return " ".join(text.casefold().split()).removesuffix(".").rstrip() + + +def load_catchup(repo, path, head): + try: + data = json.loads(Path(path).read_text(encoding="utf-8")) + except (OSError, ValueError) as exc: + raise NotesError(f"cannot read catch-up manifest {path}: {exc}") from exc + if not isinstance(data, dict) or type(data.get("schema_version")) is not int or data["schema_version"] != 1: + raise NotesError(f"{path}: expected catch-up schema_version 1") + baseline = resolve_commit(repo, data.get("baseline", ""), "catch-up baseline") + require_ancestor(repo, baseline, head, "catch-up baseline") + if not isinstance(data.get("notes"), list): + raise NotesError(f"{path}: notes must be a list") + notes = {} + for index, entry in enumerate(data["notes"], 1): + context = f"{path}: catch-up note {index}" + if not isinstance(entry, dict): + raise NotesError(f"{context}: expected commit and text") + sha = resolve_commit(repo, entry.get("commit", ""), context + " commit") + text = validate_note(entry.get("text"), context) + if text.casefold() == "none": + raise NotesError(f"{context}: omit an unwanted catch-up entry instead of writing none") + category = validate_category(entry.get("category", ""), context) + notes.setdefault(sha, []).append((text, category)) + return baseline, notes + + +def read_commits(repo, baseline, head): + raw = git(repo, "log", "--reverse", "--topo-order", "-z", + "--format=%H%x00%P%x00%B", f"{baseline}..{head}", "--") + fields = raw.split("\0") + if fields[-1] == "": + fields.pop() + if len(fields) % 3: + raise NotesError("Git returned an invalid commit record") + commits = {} + for offset in range(0, len(fields), 3): + sha, parents, message = fields[offset:offset + 3] + if sha in HISTORICAL_NOTE_PREFIXES: + old, new = HISTORICAL_NOTE_PREFIXES[sha] + message = "\n".join(new + line[len(old):] if line.startswith(old) else line + for line in message.split("\n")) + notes, omitted = parse_notes(message, f"commit {sha}") + commits[sha] = Commit(sha, parents.split(), notes, omitted) + for withdrawal, original in HISTORICAL_NOTE_WITHDRAWALS.items(): + if withdrawal in commits and original in commits: + commits[original].omitted = True + return commits + + +def ordered_commits(commits, head): + """Order by first-parent introduction, then Git's topological order.""" + chain = [] + sha = head + while sha in commits: + chain.append(sha) + parents = commits[sha].parents + sha = parents[0] if parents else None + introduced = {} + for group, sha in enumerate(reversed(chain)): + pending = [sha] + while pending: + current = pending.pop() + if current not in commits or current in introduced: + continue + introduced[current] = group + pending.extend(commits[current].parents) + # Stable sorting retains Git's order within each group, without a + # complete history scan for every first-parent commit. + return sorted(commits.values(), key=lambda commit: introduced[commit.sha]) + + +def load_previous(repo, path, base, build_number): + if base is None: + raise NotesError("--previous requires --base to identify the published archive's commit") + try: + data = json.loads(Path(path).read_text(encoding="utf-8")) + except (OSError, ValueError) as exc: + raise NotesError(f"cannot read previous changelog archive {path}: {exc}") from exc + if not isinstance(data, dict) or type(data.get("schema_version")) is not int or data["schema_version"] != 2: + raise NotesError(f"{path}: unsupported previous archive; expected schema_version 2") + archive_head = resolve_commit(repo, data.get("head", ""), "previous archive head") + if archive_head != base: + raise NotesError(f"{path}: previous archive head must equal --base {base}") + entries = data.get("entries") + if not isinstance(entries, list) or not 1 <= len(entries) <= MAX_ENTRIES: + raise NotesError(f"{path}: previous archive must contain 1 to {MAX_ENTRIES} entries") + seen_builds = set() + validated = [] + last_build = build_number + for index, entry in enumerate(entries, 1): + context = f"{path}: previous entry {index}" + if not isinstance(entry, dict): + raise NotesError(f"{context}: expected build, date, commit and notes") + build = entry.get("build") + if type(build) is not int or not 1 <= build <= MAX_BUILD_NUMBER or build in seen_builds: + raise NotesError(f"{context}: build must be a unique positive integer at most {MAX_BUILD_NUMBER}") + if last_build is not None and build >= last_build: + raise NotesError(f"{context}: build numbers must decrease from the current build through older entries") + seen_builds.add(build) + last_build = build + entry_date = entry.get("date") + try: + if not isinstance(entry_date, str) or date.fromisoformat(entry_date).isoformat() != entry_date: + raise ValueError() + except ValueError as exc: + raise NotesError(f"{context}: date must be a valid YYYY-MM-DD date") from exc + commit = resolve_commit(repo, entry.get("commit", ""), context + " commit") + require_ancestor(repo, commit, archive_head, context + " commit") + if index == 1 and commit != archive_head: + raise NotesError(f"{context}: newest entry commit must equal the archive head") + if not isinstance(entry.get("notes"), list): + raise NotesError(f"{context}: notes must be a list") + notes = [validate_note(note, context) for note in entry["notes"]] + saved = {"build": build, "date": entry_date, "commit": commit, "notes": notes} + if "categories" in entry: + saved["categories"] = validate_categories(entry["categories"], notes, context) + validated.append(saved) + if sum(len(entry["notes"]) for entry in validated) > MAX_NOTES: + raise NotesError(f"{path}: previous archive exceeds {MAX_NOTES} notes") + return validated + + +def collect(repo, head="HEAD", base=None, catchup=None, preview=False, + build_number=None, previous=None, require_notes=False): + if build_number is not None and (type(build_number) is not int or not 1 <= build_number <= MAX_BUILD_NUMBER): + raise NotesError(f"build number must be a positive integer at most {MAX_BUILD_NUMBER}") + if preview and build_number is not None: + raise NotesError("--preview cannot accompany --build-number") + repo = Path(repo) + if git(repo, "rev-parse", "--is-shallow-repository").strip() != "false": + raise NotesError("player notes require complete Git history; use checkout fetch-depth: 0 or git fetch --unshallow") + head = resolve_commit(repo, head, "head", allow_head=True) + baseline, catchup_notes = load_catchup( + repo, catchup or repo / "port/assets/changelog/catchup.json", head) + if base is not None: + base = resolve_commit(repo, base, "base") + require_ancestor(repo, base, head, "base") + previous_entries = load_previous(repo, previous, base, build_number) if previous is not None else [] + commits = read_commits(repo, baseline, head) + release_range = set(git(repo, "rev-list", f"{base or baseline}..{head}", "--").split()) + seen = set() + release_highlights = [] + # Deduplicate across full authored history, including already released notes. + for commit in ordered_commits(commits, head): + if commit.omitted: + continue + for note, category in catchup_notes.get(commit.sha, []) + commit.notes: + key = note_key(note) + if key not in seen: + seen.add(key) + if commit.sha in release_range: + release_highlights.append((note, category)) + release_notes = [note for note, _ in release_highlights] + if require_notes and release_range and not release_notes: + # A release-tip omission is an explicit review of the integrated range. + # An omission on an unrelated maintenance commit cannot cover a merge. + reviewed = head in commits and commits[head].omitted + unreviewed = [sha for sha in release_range + if sha not in commits or not commits[sha].omitted] + if unreviewed and not reviewed: + raise NotesError( + "new commits have no release notes; add Player-Note: highlights " + "to the integration commit or reviewed catch-up notes. If the " + "entire release has no player-facing changes, explicitly mark " + "its tip Player-Note: none after review") + commit_date = git(repo, "show", "-s", "--format=%cs", head, "--").strip() + entries = [{"build": build_number, "date": commit_date, "commit": head, "notes": release_notes}] + categories = [category for _, category in release_highlights] + if any(categories): + entries[0]["categories"] = categories + entries.extend(previous_entries) + warnings = [] + if len(entries) > MAX_ENTRIES: + warnings.append(f"omitted {len(entries) - MAX_ENTRIES} older changelog entries (keeping newest {MAX_ENTRIES})") + entries = entries[:MAX_ENTRIES] + if sum(len(entry["notes"]) for entry in entries) > MAX_NOTES: + raise NotesError(f"changelog exceeds {MAX_NOTES} notes; shorten or consolidate authored notes (none were silently discarded)") + markdown = "\n".join("- " + note for note in release_notes) + "\n" if release_notes else "No player-facing notes were recorded for this build.\n" + return {"schema_version": 2, "head": head, "entries": entries}, markdown, warnings + + +def write_outputs(output, data, markdown): + output = Path(output) + output.mkdir(parents=True, exist_ok=True) + staged = [] + try: + for name, text in (("changelog.json", json.dumps(data, indent=2) + "\n"), + ("notes.md", markdown)): + with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", newline="\n", + dir=output, prefix=".player-notes-", delete=False) as file: + staged.append((Path(file.name), output / name)) + file.write(text) + for temporary, destination in staged: + os.replace(temporary, destination) + finally: + for temporary, _ in staged: + temporary.unlink(missing_ok=True) + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--head", default="HEAD", help="full commit SHA, or HEAD (default)") + parser.add_argument("--base", help="full SHA of the previous successful release") + parser.add_argument("--catchup", type=Path, default=ROOT / "port/assets/changelog/catchup.json") + parser.add_argument("--build-number", type=int, help="positive GitHub Actions build number; otherwise preview") + parser.add_argument("--preview", action="store_true", help="create an UNRELEASED entry without a build number (default)") + parser.add_argument("--previous", type=Path, help="published schema-2 changelog archive for --base") + parser.add_argument("--require-notes", action="store_true", + help="reject new release commits without notes or explicit omission review") + parser.add_argument("--output", type=Path, required=True, help="directory for changelog.json and notes.md") + args = parser.parse_args(argv) + try: + data, markdown, warnings = collect(ROOT, args.head, args.base, args.catchup, args.preview, + args.build_number, args.previous, args.require_notes) + write_outputs(args.output, data, markdown) + except (NotesError, OSError) as exc: + parser.exit(1, f"player notes: {exc}\n") + for warning in warnings: + print(f"player notes: {warning}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/port_settings.py b/tools/port_settings.py index ea2aed64bb..f000656cfd 100644 --- a/tools/port_settings.py +++ b/tools/port_settings.py @@ -28,9 +28,9 @@ QUIT_ITEM_PLACE = (192, 427) YES_NO = [("YES", "true"), ("NO", "false")] ON_OFF = [("ON", "true"), ("OFF", "false")] -# the multiplayer armor colors, in the profile's order (player_profile.c) -SHIELD_COLORS = ["white", "black", "red", "blue", "gray", "yellow", "green", "pink", "purple", "cyan", "cobalt", - "orange", "teal", "sage", "brown", "tan", "maroon", "salmon"] +MENU_STYLE = ("MENU STYLE:", "display.menu_frontend", + [("STOCK", "off"), ("MODERN", "modern"), ("CLASSIC PC", "pc"), ("XBOX", "xbox")], + "Choose the menu style. Applies on return to the\nmain menu; pause menus keep their existing style.", None) XBOX_BUTTON_STYLES = [("XBOX CLASSIC", "classic"), ("XBOX GEMS", "gems"), ("XBOX DARK GEMS", "menu_gems"), ("XBOX MODERN", "xbox_modern")] PS_BUTTON_STYLES = [("PS CLASSIC", "ps_classic"), ("PS GEMS", "ps_gems"), @@ -59,13 +59,10 @@ "video_settings": { "screen": "video_settings_screen", "header": ("header_profile_video_settings", f"{PE}/video_settings/header_profile_video_settings"), - # a 28px step (the other screens' 30 would take the desktop's ten - # rows into the help: Graphics' is 27). each platform packs its own - # rows, so a row hidden on this machine does not leave a gap - "spacing": 28, - # (below the desktop's last row, 353: its two lines clear of the - # buttons, 414) - "help_top": 358, "help_height": 54, + # Desktop rows and categories fit above the help text. + # Each platform packs its own rows without gaps for hidden entries. + "spacing": 26, + "help_top": 364, "platform_places": True, # (rows in the place of the row before them: Window Size in # Resolution's, port/linux/game/menu_functions.c showing the one the @@ -111,7 +108,7 @@ ("HIGH-RES TEXT:", "display.high_res_text", ON_OFF, "Draw text and titles with high-res fonts; off\ndraws the game's own.", None), ("WIDESCREEN LOADING:", "display.widescreen_loading", ON_OFF, - "Widen the original loading screen, keeping its\nstock sweep and glow trails.", None), + "Widen the original loading screen, keeping its\nstock sweep and glow trails. Includes MCC.", None), ("ANTI-ALIASING:", "display.anti_aliasing", [("OFF", "off"), ("FXAA", "fxaa"), ("SMAA", "smaa"), ("SSAA 2X", "ssaa2x"), ("MSAA 2X", "msaa2x"), ("MSAA 4X", "msaa4x"), ("MSAA 8X", "msaa8x")], @@ -202,7 +199,7 @@ "network_setup": { "screen": "network_settings_screen", "header": ("header_profile_network_settings", f"{PE}/network_setup/header_profile_network_settings"), - "spacing": 30, + "spacing": 27, # (the router, the clipboard and the updates, which the web build # has not: the other rows from the top there) "platform_places": True, @@ -233,6 +230,8 @@ "screen": "gamepad_setup_screen", "header": ("header_profile_controller_setting", f"{PE}/controller_edit/header_profile_controller_setting"), "spacing": 27, + "platform_spacing": {"android": 23}, + "platform_places": True, "rows": [ ("LOOK SENSITIVITY:", "profile.look_sensitivity", [(str(step), str(step)) for step in range(1, 11)], "How fast the right stick turns the view.", None), @@ -254,21 +253,54 @@ "categories": [("BUTTON REMAPPING", "controller_remapping", "Custom button layouts for P1-P4.\nUse / Reload stays combined."), ("BUTTON APPEARANCE", "controller_appearance", - "Keyboard/controller glyphs and PC-menu legends.\nGameplay controller art needs High-Res HUD.")], + "Controller artwork and bumper style.\nRequires High-Res HUD in Graphics."), + ("ANDROID CONTROLS", "gamepad_setup/android", + "Touch controls, gyro aiming and the\noptional offline cheat menu.", "android")], + }, + "gamepad_setup/android": { + "screen": "android_controls_screen", "spacing": 30, + "header": ("header_profile_controller_setting", f"{PE}/controller_edit/header_profile_controller_setting"), + "rows": [ + ("TOUCH CONTROLS:", "input.touch_controls", [("AUTO", "auto"), ("ON", "on"), ("OFF", "off")], + "Auto shows touch controls without a gamepad.\nOn also shows them with a connected gamepad.", "android"), + ("TOUCH AIM ASSIST:", "input.touch_aim_assist", ON_OFF, + "Apply controller aim assistance to touch aiming.", "android"), + ("CHEAT MENU:", "android.cheat_menu", ON_OFF, + "Show a CHEATS touch button and Options entry.\nOffline or game host only. Off by default.", "android"), + ], + "categories": [("GYRO AIM", "gamepad_setup/gyro", + "Phone gyro mode, sensitivity and inversion.\nTouch settings keeps your saved layout.", "android")], + }, + "gamepad_setup/gyro": { + "screen": "gyro_settings_screen", "spacing": 30, + "header": ("header_profile_controller_setting", f"{PE}/controller_edit/header_profile_controller_setting"), + "rows": [ + ("GYRO AIM:", "input.gyro_aim", + [("TOUCH SETTINGS", "legacy"), ("OFF", "false"), ("ON", "true"), ("ZOOM ONLY", "zoom")], + "Touch settings keeps the saved gyro switch and\nsensitivity. On/Zoom use the settings below.", "android"), + ("HORIZONTAL SENSITIVITY:", "input.gyro_sensitivity_horizontal", + [(f"{step / 4:g}", f"{step / 4:g}") for step in range(1, 41)], + "How far the gyro turns the view left and right.\nSeparate from swipe sensitivity.", "android"), + ("VERTICAL SENSITIVITY:", "input.gyro_sensitivity_vertical", + [(f"{step / 4:g}", f"{step / 4:g}") for step in range(1, 41)], + "How far the gyro turns the view up and down.\nSeparate from swipe sensitivity.", "android"), + ("INVERT HORIZONTAL:", "input.gyro_invert_horizontal", ON_OFF, + "Reverse the gyro's horizontal turn.", "android"), + ("INVERT VERTICAL:", "input.gyro_invert_vertical", ON_OFF, + "Reverse the gyro's vertical turn.\nIndependent of the profile's Invert Look.", "android"), + ], }, "controller_appearance": { "screen": "controller_appearance_screen", "spacing": 30, "header": ("header_profile_controller_setting", f"{PE}/controller_edit/header_profile_controller_setting"), "same_place": ["hud_button_style_xbox", "hud_button_style_ps", "hud_button_style_switch", "detected_button_style"], "rows": [ - ("MENU GLYPHS:", "display.menu_button_glyphs", ON_OFF, - "Use the selected keyboard/controller style in\nexisting PC-menu face-button legends.", None), - ("KEYBOARD GLYPHS:", "display.keyboard_glyphs", ON_OFF, - "Opt in to automatic keyboard/mouse keycaps.\nRequires Auto Button Detection.", None), ("AUTO BUTTON DETECTION:", "input.auto_button_detection", ON_OFF, - "Detect controller artwork and, with Keyboard\nGlyphs enabled, follow keyboard/mouse activity.", None), + "Follow keyboard/mouse or controller activity.\nControllers use their family's saved artwork.", None), + ("MENU GLYPHS:", "display.menu_button_glyphs", ON_OFF, + "Use glyphs in stock PC menus and pause legends.\nRequires High-Res HUD; modern prompts are separate.", None), ("BUTTON STYLE:", "display.hud_button_style", XBOX_BUTTON_STYLES + PS_BUTTON_STYLES + SWITCH_BUTTON_STYLES + [("KEYBOARD", "keyboard")], - "Manual style when auto detection is off. Keyboard\nuses current bindings; controllers need High-Res HUD.", None), + "Manual style when auto detection is off. Keyboard\nuses current bindings. Requires High-Res HUD.", None), ("BUTTON STYLE:", "display.hud_button_style_xbox", XBOX_BUTTON_STYLES, "Preferred Xbox artwork for automatic detection.\nRequires High-Res HUD in Graphics.", None), ("BUTTON STYLE:", "display.hud_button_style_ps", PS_BUTTON_STYLES, @@ -316,18 +348,19 @@ # Video Setup's categories open ordinary settings screens. Each has the same # pending edits, Defaults, OK and Cancel as the other settings screens. _video = SCREENS["video_settings"] -_graphics = {"display.widescreen_loading", "display.show_fps", "display.high_res_hud", - "display.high_res_text", "display.anti_aliasing", +_graphics = {"display.show_fps", "display.high_res_hud", + "display.high_res_text", "display.widescreen_loading", "display.anti_aliasing", "display.anisotropic_filtering", "display.shadow_resolution", "display.per_pixel_lighting", "display.model_detail"} # (the visual modifiers: a screen of their own, Extra Effects) -_extra_effects = {"display.shield_glow", "display.shield_glow_intensity", - "display.overshield_effect", "display.hdr", "display.hdr_output", "display.hdr_tone_mapping", "display.hdr_paper_white", - "display.hdr_peak_brightness"} +_shield_lighting = {"display.shield_glow", "display.shield_glow_intensity"} +_shield_rows = [row for row in _video["rows"] if row[1] in _shield_lighting] +_extra_effects = {"display.overshield_effect", "display.hdr", "display.hdr_output", + "display.hdr_tone_mapping", "display.hdr_paper_white", "display.hdr_peak_brightness"} SCREENS["video_settings/graphics"] = { "screen": "graphics_settings_screen", "header": _video["header"], "spacing": 27, "same_place": ["anti_aliasing_android"], - "rows": [row for row in _video["rows"] if row[1] in _graphics], + "rows": [MENU_STYLE] + [row for row in _video["rows"] if row[1] in _graphics], } SCREENS["video_settings/extra_effects"] = { "screen": "extra_effects_settings_screen", "header": _video["header"], "spacing": 30, @@ -353,13 +386,42 @@ "How bright white is (the menus, the HUD, the\ngrey bars), in nits. Choose what looks right.", None), ], } -_video["rows"] = [row for row in _video["rows"] if row[1] not in _graphics | _extra_effects] +_video["rows"] = [row for row in _video["rows"] if row[1] not in _graphics | _extra_effects | _shield_lighting] _video["categories"] = [ ("GRAPHICS:", "video_settings/graphics", "The HUD, text, anti-aliasing, shadows,\nlighting and HDR."), ("FOV AND VIEWMODELS:", "video_settings/fov_viewmodels", "The field of view and the first-person\nweapon. Their defaults keep the stock view."), + ("DYNAMIC LIGHTING:", "video_settings/dynamic_lighting", + "Added light from projectiles, weapons and\nenergy shields. Added lights default to off.", "desktop web"), ("EXTRA EFFECTS:", "video_settings/extra_effects", - "Visual modifiers the stock game does not\nhave, such as the shield glow."), + "Visual modifiers the stock game does not\nhave, such as HDR and overshields."), +] +SCREENS["video_settings/dynamic_lighting"] = { + "screen": "dynamic_lighting_settings_screen", "header": _video["header"], "spacing": 26, + "help_top": 370, "help_height": 40, + "rows": [ + ("PROJECTILE LIGHTS:", "display.plasma_lighting", ON_OFF, + "Plasma, grenades, rockets and flame streams cast\nsoft light on nearby surfaces and models.", None), + ("MUZZLE FLASH LIGHTS:", "display.muzzle_lighting", ON_OFF, + "Weapon flashes light nearby surfaces, including\nWarthog and Scorpion guns. Stock effects remain.", None), + ("WEAPON GLOW:", "lighting.weapon_glow", ON_OFF, + "Swords, plasma charge, fuel rods, Needler and AR\nscreens cast light on nearby surfaces.", None), + ("PLASMA PRONG LIGHTING:", "display.plasma_prong_lighting", ON_OFF, + "Short, soft spill from plasma-weapon prongs.\nUses the shared eight-light occlusion budget.", None), + ("SHIELD EMITTERS:", "lighting.shield_emitters", ON_OFF, + "Jackal and stationary shields cast light\non nearby surfaces.", None), + ("VEHICLE LIGHTS:", "display.vehicle_lighting", ON_OFF, + "Engine glow and directional headlights illuminate\nvehicles and nearby surfaces.", None), + ("WORLD EMITTERS:", "display.world_lighting", ON_OFF, + "Visible powerups and teleporters cast soft light.\nStock effects and gameplay remain unchanged.", None), + ("LIGHT OCCLUSION:", "display.plasma_occlusion", ON_OFF, + "Block projectile and emitter light behind walls.\nMuzzle and vehicle lights always use blocking.", None), + ] + _shield_rows, +} +# Android builds omit this renderer. Keep both the entry and its controls +# unavailable; existing configuration values cannot activate its inert hooks. +SCREENS["video_settings/dynamic_lighting"]["rows"] = [ + (*row[:4], "desktop web") for row in SCREENS["video_settings/dynamic_lighting"]["rows"] ] SCREENS["video_settings/fov_viewmodels"] = { "screen": "fov_viewmodel_settings_screen", "header": _video["header"], "spacing": 30, @@ -372,15 +434,43 @@ "Draw first-person weapons, hands and attached\nvisuals. Gameplay and sound continue when off.", None), ("PASSENGER THIRD PERSON:", "display.passenger_third_person", ON_OFF, "Third-person Warthog and Scorpion passengers in\nthe campaign and co-op. Weapon zoom is disabled.", None), + ("SHIELD LOOK:", "display.shield_look", [("DEFAULT", "classic"), ("CLASSIC WITH SPRINKLES", "classic_with_sprinkles"), ("MARK VI", "enhanced"), ("INFINITE HONEYCOMB", "classic_honeycomb2")], + "Classic keeps map shields. Other looks keep custom colour.\nSprinkles adds layers, arcs and recharge to the classic surface.", None), ("ARM SHIELDS:", "display.viewmodel_shield", ON_OFF, "The energy shield's flare on your first-person\narms too, as on your body.", None), + ("THIRD PERSON:", "display.third_person", ON_OFF, + "Right-shoulder view on foot. Zoom uses first\nperson. The reticle follows your aim point.", None), ("LEGS:", "display.first_person_legs", ON_OFF, "Your legs in first person, seen looking down,\nmoving as you run. Your body as others see it.", None), - ("SHIELD COLOR:", "display.shield_color", [("DEFAULT", "default")] + [(c.upper(), c) for c in SHIELD_COLORS], - "Your shield's flare in an armor color, whatever\nyour armor. Only you see it. Default: its own.", None), ], } +SCREENS["video_settings/fov_viewmodels"]["spacing"] = 26 +SCREENS["video_settings/fov_viewmodels"]["categories"] = [ + ("SHOULDER CAMERA:", "video_settings/shoulder_camera", + "Choose the shoulder and camera position.\nB swaps shoulders while playing."), +] +SCREENS["video_settings/fov_viewmodels"]["extra_help"] = [ + "CONTROLLED BY HOST. Your personal camera\\npreference returns after leaving the match.", +] +SCREENS["video_settings/shoulder_camera"] = { + "screen": "shoulder_camera_settings_screen", "header": _video["header"], "spacing": 30, + "rows": [ + ("CAMERA MOTION:", "display.third_person_smooth", [("SMOOTH", "true"), ("SHARP", "false")], + "Smooth eases recovery and shoulder changes.\nSharp moves immediately; collision stays active.", None), + ("LEFT SHOULDER:", "display.third_person_left_shoulder", ON_OFF, + "Off uses the right shoulder. B swaps in game.\nRemap it under Controls Setup > Camera.", None), + ("DISTANCE:", "display.third_person_distance", + [(f"{n / 100:.2f}", f"{n / 100:.2f}") for n in [30, 45, 60, 70, 85, 100, 125, 150, 175, 200]], + "Distance behind the eye, in world units.\nAlt + wheel adjusts in game. Default 0.85.", None), + ("HEIGHT:", "display.third_person_height", + [(f"{n / 100:.2f}", f"{n / 100:.2f}") for n in [-20, -10, 0, 6, 12, 18, 24, 36, 48, 60]], + "Shift + wheel adjusts height in game.\nDefault 0.12 world units.", None), + ("LATERAL OFFSET:", "display.third_person_offset", + [(f"{n / 100:.2f}", f"{n / 100:.2f}") for n in [0, 6, 12, 18, 24, 30, 36, 48, 60]], + "Hold Caps Lock + wheel to move left or right.\nDefault 0.24 world units to the right.", None), + ], +} # Audio Setup's sound processing (port/linux/src/dsound_sdl.c): reverb, # HRTF and the resampler, a screen of their own (a category, as Video Setup's); # the devices and the volumes stay on Audio Setup @@ -418,6 +508,7 @@ _hud_rows = [row for row in _network["rows"] if row[1] in _hud_settings] _network["rows"] = [row for row in _network["rows"] if row[1] not in _hud_settings] _network["categories"] = [ + ("BOTS:", "network_setup/bots", "Configure optional bots and manage the host's bots\nduring a multiplayer match."), ("MAP SHARING:", "network_setup/map_sharing", "Download CE maps or approved MCC packages.\nManage sharing and downloaded MCC copies."), ("MULTIPLAYER HUD:", "network_setup/multiplayer_hud", @@ -429,6 +520,30 @@ ("DISCORD ACCOUNT:", "network_setup/discord_account", "Link a Discord account, which lets you join\nservers that block VPNs while you use one."), ] +SCREENS["network_setup/bots"] = { + "screen": "bots_screen", "header": _network["header"], "title": "BOTS", "spacing": 30, + "save_event": "port bots settings save", + "rows": [ + ("BOT COUNT:", "bots.count", [(str(n), str(n)) for n in range(64)], + "Set the lobby's bot count, up to 63.\nBots fill the available player slots.", None), + ("NETWORK BOTS:", "bots.network", ON_OFF, + "Allow bots in a network lobby.\nPress OK to apply before starting.", None), + ("DIFFICULTY:", "bots.skill", [(s.upper(), s) for s in ("recruit", "easy", "normal", "heroic", "veteran", "legendary")], + "Set bot aim, reactions and awareness.", None), + ("TEAMS:", "bots.teams", [("EVEN", "even"), ("OPPOSE", "against")], + "Balance teams, or put bots on the\nother team from the first human.", None), + ("ENHANCED BOTS:", "bots.enhanced", ON_OFF, + "Add tactics and CTF/King goals.\nTakes effect when loading a map.", None), + ("VEHICLES:", "bots.vehicles", ON_OFF, + "Enhanced bots can drive vehicles\nand use turrets. Off by default.", None), + ("ROUTES:", "bots.routes", [(s.upper(), s) for s in ("direct", "lanes", "mixed")], + "Let enhanced bots take other routes.\nDirect keeps the original routes.", None), + ("PATH WORKER:", "bots.thread", ON_OFF, + "Run path searches in the background.\nOff by default. Applies next map.", None), + ], + "categories": [("MANAGE CURRENT BOTS", "network_setup/bots/manage", + "Add or remove bots during a match.\nThe saved Bot Count stays the same.")], +} SCREENS["network_setup/map_sharing"] = { "screen": "map_sharing_settings_screen", "header": _network["header"], "spacing": 30, "categories": [("MCC PACKAGES:", "network_setup/mcc_packages", @@ -569,12 +684,12 @@ # Controls Setup: the keyboard and mouse's actions, in groups (the order of # port/linux/game/menu_functions.c's table of them) -CONTROL_GROUPS = ["MOVEMENT", "WEAPONS", "ACTIONS", "COMMUNICATION"] +CONTROL_GROUPS = ["MOVEMENT", "WEAPONS", "ACTIONS", "COMMUNICATION", "CAMERA"] CONTROL_ROWS = 7 # the settings whose rows have the wider spinner (a device's name) WIDE_SETTINGS = {"audio.output_device", "audio.input_device", "streamer.slurs", "streamer.swearing", - "streamer.insults", "network.listings", "network.browser_maps", "network.browser_sort"} + "streamer.insults", "display.shield_look", "network.listings", "network.browser_maps", "network.browser_sort"} # Teamplay Options' rows of the port's (_teamplay_options_extras): the # gametype's FORCE TEAM SPAWNS, then the host's voice chat and vote kicks; @@ -670,22 +785,35 @@ def _screen(folder: str, spec: dict, rows: list, list_inputs: list, list_handler lines = [] lines += _widget(f"{base}/{spec['screen']}", [("width", 640), ("height", 480), ("flags", "pass_unhandled_to_focused_child pause_game"), - ("bitmap", "bitmaps/gradient")], + ("bitmap", spec.get("background_bitmap", "bitmaps/gradient"))], ['', '', f'', f'']) - lines += _widget(f"{base}/{header}", [("controller", 1), ("left", 35), ("top", 11), ("width", 605), ("height", 59), - ("bitmap", header_bitmap)], []) - lines += _widget(f"{base}/help", [("type", "text"), ("controller", 1), ("left", 68), - ("top", spec.get("help_top", 350)), ("width", 482), + header_style = [("bitmap", header_bitmap)] if not spec.get("title") else [ + ("type", "text"), ("text", spec["title"]), ("font", "ui\\large_ui"), ("color", "#FFFFFFFF"), ("text_y", 18)] + lines += _widget(f"{base}/{header}", [("controller", 1), ("left", 35), ("top", spec.get("header_top", 11)), ("width", 605), ("height", 59), + *header_style], []) + lines += _widget(f"{base}/help", [("type", "text"), ("controller", 1), ("left", spec.get("help_left", 68)), + ("top", spec.get("help_top", 350)), ("width", spec.get("help_width", 482)), ("height", spec.get("help_height", 60)), ("string_list", None if spec.get("dynamic_help") else f"{base}/help_strings"), - ("font", spec.get("help_font", "ui\\large_ui")), ("color", "#FFFFFFFF")], []) + ("font", spec.get("help_font", "ui\\large_ui")), ("color", "#FFFFFFFF")], + [f''] if spec.get("help_init") else []) children = [f'' for name in list_inputs] + list_handlers # (each row: its widget, platform, and the place it is in, else the next) for index, (row, platform, *place) in enumerate(rows): - y = 73 + (place[0] if place else index) * spec["spacing"] - children.append(f'') - children.append(f'') + position = place[0] if place else index + if spec.get("platform_spacing"): + # Extra Android controls must not move desktop/web settings. + groups = {} + for name in platform.split() if platform else ("desktop", "android", "web"): + spacing = spec["platform_spacing"].get(name, spec["spacing"]) + groups.setdefault(spec.get("rows_top", 73) + position * spacing, []).append(name) + for y, names in groups.items(): + children.append(f'') + else: + y = spec.get("rows_top", 73) + position * spec["spacing"] + children.append(f'') + children.append(f'') lines += _widget(f"{base}/options_menu", [("type", "column_list"), ("width", 640), ("height", 480), ("flags", "pass_unhandled_to_focused_child up_down_tabs_children"), @@ -757,6 +885,7 @@ def _setting_screen(folder: str, spec: dict) -> list: # (a device's name wants the wider spinner Server Setup's co-op rows # have: WIDE_SETTINGS) wide = setting in WIDE_SETTINGS + shield_look = setting == "display.shield_look" bumper_style = setting == "display.hud_bumper_style" controller_style = setting.startswith("display.hud_button_style") # Dynamic captions retain their help index without a string list that @@ -764,21 +893,21 @@ def _setting_screen(folder: str, spec: dict) -> list: extra += _widget(row, [("width", 512), ("height", 28), ("flags", "pass_unhandled_to_focused_child"), ("bitmap", "bitmaps/option_bkds"), ("color", "#FF2896FF"), ("platform", platform)], [f'', - f'']) + f'']) extra += _widget(f"{base}/{key}_label", [("type", "text"), ("controller", 1), ("width", 300), ("height", 22), ("string_list", None if controller_style else f"{base}/labels"), ("string_index", index), ("font", "ui\\large_ui"), ("color", "#FF2896FF"), ("text_x", 13), ("text_y", 4)], []) extra += _widget(f"{base}/{key}_spinner", - [("type", "spinner"), ("left", None if wide else 3), ("top", 2), ("width", 252 if controller_style or bumper_style else 206 if wide else 147), + [("type", "spinner"), ("left", None if wide else 3), ("top", 2), ("width", 252 if shield_look or controller_style or bumper_style else 206 if wide else 147), ("height", 20), ("flags", "pass_unhandled_to_focused_child left_right_tabs_items"), ("strings", "|".join(shown for shown, _ in choices)), ("setting", setting), ("values", "|".join(value for _, value in choices)), ("font", "ui\\large_ui"), ("color", "#FF2896FF"), ("align", "center"), ("text_y", 4 if wide else 1), ("header_bitmap", "bitmaps/arrow_sm_left"), ("footer_bitmap", "bitmaps/arrow_sm_right"), ("header_bounds", "7 -13 19 -7" if wide else "7 -6 19 0"), - ("footer_bounds", "7 254 19 260" if controller_style or bumper_style else "7 208 19 214" if wide else "7 150 19 156")], + ("footer_bounds", "7 254 19 260" if shield_look or controller_style or bumper_style else "7 208 19 214" if wide else "7 150 19 156")], ['']) # (each category's row: its label, the screen it opens, its help, and the # platforms it is for, as a row's: every one's when it names none) @@ -805,8 +934,9 @@ def _setting_screen(folder: str, spec: dict) -> list: ("font", "ui\\large_ui"), ("color", "#FF2896FF"), ("text_x", 13), ("text_y", 4)], []) extra += _button(f"{base}/button_defaults", 3, ['', '']) - extra += _button(f"{base}/button_ok", 1, ['', - '']) + save_event = spec.get("save_event", "port settings save") + extra += _button(f"{base}/button_ok", 1, [f'', + f'']) extra += _strings(f"{base}/labels", [label for label, *_ in spec["rows"]] + [label for label, *_ in spec.get("categories", ())]) if spec.get("words"): @@ -814,7 +944,7 @@ def _setting_screen(folder: str, spec: dict) -> list: # (the help of the row whose label is string n is n + 1: the buttons' is 0) extra += _strings(f"{base}/help_strings", [""] + [help_text.replace("\n", "\\n") for _, _, _, help_text, *_ in spec["rows"]] + - [help_text.replace("\n", "\\n") for _, _, help_text, *_ in spec.get("categories", ())]) + [help_text.replace("\n", "\\n") for _, _, help_text, *_ in spec.get("categories", ())] + spec.get("extra_help", [])) return _screen(folder, spec, rows, ["port settings help", *spec.get("inputs", ())], [], extra) @@ -878,7 +1008,7 @@ def _controller_screen() -> list: base = f"{PE}/{folder}" rows, extra = [], [] for key, label, choices in [("player", "PLAYER:", "P1|P2|P3|P4"), - ("group", "SHOW:", "MOVEMENT|COMBAT|GENERAL|COMMUNICATION|DEBUG")]: + ("group", "SHOW:", "MOVEMENT|COMBAT|GENERAL|COMMUNICATION|DEBUG|CAMERA PERSPECTIVE")]: row = f"{base}/op_{key}" rows.append((row, None)) extra += _widget(row, [("width", 512), ("height", 28), ("flags", "pass_unhandled_to_focused_child"), @@ -922,6 +1052,29 @@ def _controller_screen() -> list: for line in lines] +SCREENS["network_setup/bots/manage"] = { + "screen": "bots_manage_screen", "header": _network["header"], "title": "MANAGE BOTS", + "spacing": 36, "dynamic_help": True, "rows": [], + "help_top": 300, "help_height": 110, + "help_init": "port bots init", +} + + +def _bots_manage_screen(folder, spec): + base = f"{PE}/{folder}" + rows, extra = [], [] + for operation, verb in (("add", "ADD"), ("drop", "REMOVE")): + for team, label in (("any", "ANY TEAM"), ("red", "RED TEAM"), ("blue", "BLUE TEAM")): + row = f"{base}/op_{operation}_{team}" + rows.append((row, None)) + extra += _widget(row, [("type", "text"), ("width", 512), ("height", 28), + ("bitmap", "bitmaps/option_bkds"), ("text", f"{verb} BOT - {label}"), + ("font", "ui\\large_ui"), ("color", "#FF2896FF"), ("text_x", 13), ("text_y", 4)], + ['', '', + '']) + extra += _button(f"{base}/button_ok", 1, ['', '']) + lines = _screen(folder, spec, rows, [], [], extra) + return [line for line in lines if f' dict: @@ -931,7 +1084,7 @@ def settings_files() -> dict: files[f"{PE}/{folder}".replace("/", ".") + ".xml"] = ( _mcc_downloads() if folder == "network_setup/mcc_downloads" else _controller_screen() if folder == "controller_remapping" else - _setting_screen(folder, spec)) + _bots_manage_screen(folder, spec) if folder == "network_setup/bots/manage" else _setting_screen(folder, spec)) files[f"{PE}/network_setup/mcc_download".replace("/", ".") + ".xml"] = _mcc_download() files[f"{PE}/controls_setup".replace("/", ".") + ".xml"] = _controls_screen() return {name: ['', @@ -1558,16 +1711,66 @@ def _password_screen() -> list: return lines +def _bots_link(base, name, host_only=False): + target = f"{PE}/network_setup/bots/bots_screen" + return _widget(f"{base}/{name}", [("type", "text"), ("width", 128), ("height", 24), + ("bitmap", "bitmaps/text_button_background"), ("text", "BOTS"), ("font", "ui\\small_ui"), + ("color", "#FFFFFFFF"), ("align", "center"), ("text_y", 2)], + ([ '' ] if host_only else []) + + [f'', f'', + '']) + + +def _session_options(base: str, host: str) -> list: + rows, extra = [], [] + for key, label, values in [ + ("session_compatibility", "SESSION COMPATIBILITY:", "CROSSPLAY|GULCHCE ONLY"), + ("camera_policy", "CAMERA POLICY:", "PLAYER CHOICE|FORCED ON|FORCED OFF"), + ]: + extra += _widget(f"{base}/op_{key}", [("width", 512), ("height", 28), + ("flags", "pass_unhandled_to_focused_child"), ("bitmap", "bitmaps/option_bkds"), ("color", "#FF2896FF")], + [f'', f'']) + extra += _widget(f"{base}/{key}_label", [("type", "text"), ("controller", 1), ("width", 260), ("height", 22), + ("text", label), ("font", "ui\\large_ui"), ("color", "#FF2896FF"), ("text_x", 13), ("text_y", 4)], []) + # Generated spinners draw at their bounds, ignoring text_y. Top 3 + + # child y 1 matches the label's text_y 4; arrows centre on the 28px row. + extra += _widget(f"{base}/{key}_spinner", [("type", "spinner"), ("top", 3), ("width", 237), ("height", 20), + ("flags", "pass_unhandled_to_focused_child left_right_tabs_items"), ("strings", values), + ("font", "ui\\large_ui"), ("color", "#FF2896FF"), ("align", "center"), + ("header_bitmap", "bitmaps/arrow_sm_left"), ("footer_bitmap", "bitmaps/arrow_sm_right"), + ("header_bounds", "7 0 19 6"), ("footer_bounds", "7 231 19 237")], + ['']) + rows.append((f"{base}/op_{key}", None)) + extra += _value_row(base, "invite", 2, "ss copy invite") + extra += _strings(f"{base}/labels", ["", "", "INVITE LINK:"]) + rows.append((f"{base}/op_invite", None)) + extra += _strings(f"{base}/help_strings", [ + "OpenCE and GulchCE can join; third person is off.\\nXbox, CE and MCC maps use the shared protocol.", + "Compatible GulchCE hosts and clients only.\\nEnables GulchCE session features, including third person.", + "Compatibility is locked for this session.\\nClose the lobby to choose another mode.", + "Each player chooses first or third person.\\nTheir camera toggle remains available.", + "Everyone uses third person on foot. Scoping and\\ntight spaces still use first person.", + "Third person is disabled for everyone.\\nNormal vehicle and cinematic cameras remain.", + "Players join by this invite link. Enter copies it.\\nLAN games use the server browser instead.", + ]) + lines = _screen(base, {"screen": "session_options_screen", "spacing": 30, + "header": ("header", f"{host}/header_server_settings")}, rows, + ["server settings update"], [''], extra) + return [line for line in lines if f' list: """Create Game's server settings (in the PC version's place): the game's name, the most players (up to the port's 128), its invite link, and whether the server browser lists it (PUBLIC or PRIVATE: an internet game's)""" base = f"{MT}/server_settings" - # (thirteen places: the main rows 22 high and as far apart, as their - # spinners and values already are, the help lower and smaller) - spec = {"screen": "server_settings_screen", "spacing": 22, "help_top": 366, - "help_height": 48, "help_font": "ui\\small_ui", + # Twelve full-height rows: leave the selection artwork room to draw. + spec = {"screen": "server_settings_screen", "spacing": 28, "help_top": 392, "help_height": 40, "rows_top": 49, + "help_left": 67, "help_width": 486, + "help_font": "ui\\small_ui", "button_top": 448, + "background_bitmap": "bitmaps/gradient_big", "header_top": -10, "header": ("header_server_settings", f"{base}/header_server_settings")} rows, extra = [], [] extra += _value_row(base, "server_name", 0, "ss edit server name") @@ -1589,8 +1792,6 @@ def _server_settings() -> list: ("header_bitmap", "bitmaps/arrow_sm_left"), ("footer_bitmap", "bitmaps/arrow_sm_right"), ("header_bounds", "7 -6 19 0"), ("footer_bounds", "7 150 19 156")], []) rows.append((f"{base}/op_max_players", None)) - extra += _value_row(base, "invite", 2, "ss copy invite") - rows.append((f"{base}/op_invite", None)) # (PUBLIC or PRIVATE: menu_functions.c's server_settings_update) extra += _widget(f"{base}/op_listing", [("width", 512), ("height", 28), ("flags", "pass_unhandled_to_focused_child"), @@ -1614,6 +1815,20 @@ def _server_settings() -> list: # which players from the server browser must type extra += _value_row(base, "password", 10 + len(COOP_SETUP_SCREENS), "ss edit server password") rows.append((f"{base}/op_password", None)) + # Session options occupy the former camera row; the established host + # layout and all detailed gametype links remain in their original places. + session = f"{base}/session_options" + extra += _widget(f"{base}/op_session_options", [("width", 512), ("height", 28), + ("flags", "pass_unhandled_to_focused_child"), ("bitmap", "bitmaps/option_bkds"), ("color", "#FF2896FF")], + [f'', + f'', + '', + f'']) + extra += _widget(f"{base}/session_options_label", [("type", "text"), ("controller", 1), + ("width", 480), ("height", 22), ("string_list", f"{base}/labels"), ("string_index", 13), + ("font", "ui\\large_ui"), ("color", "#FF2896FF"), ("text_x", 13), ("text_y", 4)], []) + rows.append((f"{base}/op_session_options", None)) + extra += _session_options(session, base) # MAP SHARING (map_share.c), a screen of its own as co-op's options are, # for any game: SETUP_OPTIONS_PLACE below it key, _, _, _ = MAP_SHARE_SETUP @@ -1626,7 +1841,7 @@ def _server_settings() -> list: f'']) extra += _widget(f"{base}/{key}_label", [("type", "text"), ("controller", 1), ("width", 300), ("height", 22), ("string_list", f"{base}/labels"), - ("string_index", 11 + len(COOP_SETUP_SCREENS)), + ("string_index", 12 + len(COOP_SETUP_SCREENS)), ("font", "ui\\large_ui"), ("color", "#FF2896FF"), ("text_x", 13), ("text_y", 4)], []) rows.append((f"{base}/op_{key}", None, SETUP_OPTIONS_PLACE - 1)) @@ -1677,8 +1892,7 @@ def _server_settings() -> list: extra += _strings(f"{base}/labels", ["GAME NAME:", "MAXIMUM PLAYERS:", "INVITE LINK:", "GAME TYPE:", "PLAYER OPTIONS:", "ITEM OPTIONS:", "VEHICLE OPTIONS:", "INDICATOR OPTIONS:", "TEAMPLAY OPTIONS:", "LISTING:", - *(f"{title}:" for _, title, _, _ in COOP_SETUP_SCREENS), "PASSWORD:", - f"{MAP_SHARE_SETUP[1]}:"]) + *(f"{title}:" for _, title, _, _ in COOP_SETUP_SCREENS), "PASSWORD:", "SESSION OPTIONS:", f"{MAP_SHARE_SETUP[1]}:"]) extra += _strings(f"{base}/help_strings", [ "", "The name the game shows in the lists of games.\\nEnter changes it.", @@ -1697,20 +1911,21 @@ def _server_settings() -> list: *(help_text for _, _, help_text, _ in COOP_SETUP_SCREENS), # (PASSWORD's) "Players from the Server Browser must type it to\\njoin (an invite link needs none). Enter sets it.", + "Session compatibility and the host camera policy.\\nChoose who can join and which views they can use.", + "Everyone uses third person on foot. Scoping and\\ntight spaces still use first person.", + "Third person is disabled for everyone.\\nNormal vehicle and cinematic cameras remain.", # (MAP SHARING's) MAP_SHARE_SETUP[2], # (LISTING's PUBLIC, on a machine with a publisher key: menu_functions.c's # server_settings_update) "Listed for everyone through the brokers, and on\\nthe master servers with your publisher key.", ]) - # (the main rows 22 high, their containers only: their spinners and - # values are 22 or less already, and the other screens' rows stay 28) - main_rows = {row for row, *_ in rows} - extra = [line.replace('height="28"', 'height="22"', 1) - if any(line.startswith(f'\t'], extra) + # The footer has an unused middle slot; keep the existing rows in place. + lines = [line.replace(f' list: # (SWITCH TEAM first: hidden in a game without teams, which # moves the focus to the first shown, START NOW; at the end # it traps none) - [f'', - f'', - f'', - f'']) + # Five full-width button backgrounds fit the 640-wide bar. + [f'', + f'', + f'', + f'', + f'']) + lines += _bots_link(base, "lobby_button_bots", host_only=True) for key, caption, handlers in ( ("add", "ADD PLAYER", [f'', f'']), @@ -2445,10 +2663,11 @@ def redraw_letters(redraws: Path) -> dict: return letters -def menu_item_frames(text: str, redraws: Path) -> list: +def menu_item_frames(text: str, redraws: Path, spacing: dict = None) -> list: """the frames (svg, width, height) of a main menu item of the port's: its text in the redraws' own letters (redraw_letters), spaced, placed and - coloured as their items are, dim, then white with their blue glow""" + coloured as their items are, dim, then white with their blue glow; + feature-owned captions can supply their own letter-pair spacing""" from fontTools.pens.boundsPen import BoundsPen from fontTools.svgLib.path import parse_path @@ -2458,7 +2677,8 @@ def menu_item_frames(text: str, redraws: Path) -> list: pen = BoundsPen(None) parse_path(letters[letter], pen) widths.append(pen.bounds[2]) - spaces = [MENU_ITEM_SPACES[first + second] for first, second in zip(text, text[1:])] + spacing = MENU_ITEM_SPACES if spacing is None else spacing + spaces = [spacing[first + second] for first, second in zip(text, text[1:])] x = MENU_ITEM_MIDDLE - (sum(widths) + sum(spaces)) * MENU_ITEM_SCALE / 2 uses = [] for index, letter in enumerate(text): diff --git a/tools/render_stutter_build.py b/tools/render_stutter_build.py new file mode 100644 index 0000000000..f67a7995d0 --- /dev/null +++ b/tools/render_stutter_build.py @@ -0,0 +1,183 @@ +"""Build a Windows timing probe from scratch copies of an already built checkout. + +The optional honeycomb omission is an experiment, not a shipping renderer. +No production source or object is overwritten. Use equal settings and fixed +simulation ticks when comparing checkouts; driver caches remain uncontrolled. +""" +import argparse +import hashlib +import json +from pathlib import Path +import shutil +import subprocess + + +def omit_honeycomb(source): + for statement in ['xgpu_text_append(&text, "%s", shield_honeycomb_glsl);', + 'xgpu_text_append(&text, "\\tresult = shield_honeycomb_surface(result);\\n");']: + assert source.count(statement) == 1 + guarded = '\tif (key->shield_honeycomb)\n\t\t' + statement + '\n' + plain = '\t' + statement + '\n' + source = source.replace(guarded, '') if guarded in source else source.replace(plain, '') + return source + + +def build(root, output, honeycomb=False, deterministic=False, record_prepared=False): + root = root.resolve(); output = output.resolve() + assert output.is_relative_to(root/'build') + output.mkdir(parents=True, exist_ok=True) + entries = json.loads(subprocess.check_output(['ninja', '-t', 'compdb', 'windows_cc'], cwd=root, text=True)) + link = json.loads(subprocess.check_output(['ninja', '-t', 'compdb', '-x', 'windows_link'], cwd=root, text=True))[0]['command'] + backend = (root/'port/linux/src/d3d8_gl.c').read_text() + timer = r''' +static Uint64 stutter_started[12],stutter_time[12]; +static unsigned long stutter_calls[12]; +void stutter_begin(int k) {stutter_started[k]=SDL_GetTicksNS();} +void stutter_end(int k) {stutter_time[k]+=SDL_GetTicksNS()-stutter_started[k];stutter_calls[k]++;} +struct stutter_sample {Uint64 ns,time[12];unsigned long calls[12];long tick;int playing;}; +static struct stutter_sample stutter_samples[40000]; +static unsigned long stutter_count; +static void stutter_dump(void) { + FILE *file=fopen("frames.csv","w");unsigned long i;int j; + if(!file)return; + fprintf(file,"ns,tick,playing,compile_ns,compile_calls,link_ns,link_calls,load_ns,load_calls,store_ns,store_calls,texture_ns,texture_calls,all_texture_ns,all_texture_calls,watch_ns,watch_calls,upload_ns,upload_calls,generation_ns,generation_calls,override_ns,override_calls,result_ns,result_calls,texture_create_ns,texture_create_calls\n"); + for(i=0;ins,s->tick,s->playing); + for(j=0;j<12;j++)fprintf(file,",%llu,%lu",s->time[j],s->calls[j]); + fprintf(file,"\n"); + } + fclose(file); +} +void stutter_frame(long tick,int playing) { + if(!stutter_count)atexit(stutter_dump); + if(stutter_count<40000) { + struct stutter_sample *s=&stutter_samples[stutter_count++]; + s->ns=SDL_GetTicksNS();s->tick=tick;s->playing=playing; + memcpy(s->time,stutter_time,sizeof(stutter_time));memcpy(s->calls,stutter_calls,sizeof(stutter_calls)); + } + memset(stutter_time,0,sizeof(stutter_time));memset(stutter_calls,0,sizeof(stutter_calls)); +} +''' + assert backend.count('#include ') == 1 + backend = backend.replace('#include ', '#include \n'+timer) + if 'if (!material_preparing)' in backend: + anchor = '\tif (!material_preparing)\n\t\tshader_prepare_record' + assert backend.count(anchor) == 1 + backend = backend.replace(anchor, '''\tif (material_preparing) { + static FILE *pairs; + if (!pairs) pairs=fopen("prepared-pairs.csv","w"); + if (pairs) fprintf(pairs,"%016llx,%016llx\\n", + (unsigned long long)shader_hash(vertex_shader),(unsigned long long)shader_hash(fragment_shader)); + } +'''+anchor) + if record_prepared: + backend = backend.replace(anchor, '\tshader_prepare_record') + for kind, call, status in [(0, 'glCompileShader(shader);', 'glGetShaderiv(shader, GL_COMPILE_STATUS, &status);'), + (1, 'glLinkProgram(entry->program);', 'glGetProgramiv(entry->program, GL_LINK_STATUS, &status);')]: + assert backend.count(call) == 1 + start = backend.index(call); end = backend.index(status, start)+len(status) + backend = backend[:start]+f'stutter_begin({kind});'+backend[start:end]+f'stutter_end({kind});'+backend[end:] + for kind, call in [(2, 'entry->program = program_cache_load(shader_hash(vertex_shader), shader_hash(fragment_shader));'), + (3, 'program_cache_store(entry->program, shader_hash(vertex_shader), shader_hash(fragment_shader));')]: + assert backend.count(call) == 1 + backend = backend.replace(call, '{'+f'stutter_begin({kind});'+call+f'stutter_end({kind});'+'}') + main = (root/'source/main/main.c').read_text() + main = 'void stutter_frame(long,int);\n'+main + anchor = '\t\tmain_frame_rate_debug();' + assert main.count(anchor) == 1 + main = main.replace(anchor, anchor+'\n stutter_frame(game_in_progress()?game_time_get():-1,game_in_progress()&&!main_globals.main_menu_scenario_loaded);') + sources = {'port/linux/src/d3d8_gl.c': backend, 'source/main/main.c': main} + texture = (root/'port/linux/src/xbox_textures.c').read_text() + assert texture.count('GLuint xgpu_texture_get(') == 1 + texture = 'void stutter_begin(int);void stutter_end(int);\n'+texture.replace( + 'GLuint xgpu_texture_get(', 'static GLuint measured_texture_get(') + for kind, call in [(6, 'memory_watch_protect(entry->address, entry->size);'), + (7, 'upload(entry->texture, entry->target, &entry->description, (const unsigned char *)entry->address, palette,\n\t\t\t\tcustom_edition_texels_order(entry->address));'), + (9, 'entry->override = hud_hires_override_find(entry->address, entry->description.width,\n\t\t\t\tentry->description.height, entry->description.levels > 1 ?\n\t\t\t\txgpu_texture_level_offset(&entry->description, 1) : xgpu_texture_face_size(&entry->description));'), + (11, 'entry->texture = xgpu_texture_name_new();' if 'xgpu_texture_name_new' in texture else 'glGenTextures(1, &entry->texture);')]: + assert texture.count(call) == 1 + texture = texture.replace(call, f'stutter_begin({kind});'+call+f'stutter_end({kind});') + texture = texture.replace('static GLuint texture_entry_result(', 'static GLuint measured_texture_result(') + texture = texture.replace('memory_watch_generation(entry->address, entry->size)', 'measured_generation(entry->address, entry->size)') + texture = texture.replace('static GLuint measured_texture_get(', ''' +static unsigned long measured_generation(unsigned long address,unsigned long size) { + unsigned long result;stutter_begin(8);result=memory_watch_generation(address,size);stutter_end(8);return result; +} +static GLuint texture_entry_result(struct texture_entry *entry,GLenum *target,struct xgpu_texture_description *description) { + GLuint result;stutter_begin(10);result=measured_texture_result(entry,target,description);stutter_end(10);return result; +} +static GLuint measured_texture_get(''') + texture += ''' +GLuint xgpu_texture_get(DWORD const *resource,D3DCOLOR const *palette, + GLenum *target,struct xgpu_texture_description *description) { + GLuint result;stutter_begin(5); + result=measured_texture_get(resource,palette,target,description); + stutter_end(5);return result; +} +''' + sources['port/linux/src/xbox_textures.c'] = texture + if deterministic: + # Split-screen test matches still use the network-server path, where + # stock fixed_step is intentionally inactive. This isolated probe is + # for one process only; never use it for network compatibility tests. + condition = 'halo_fixed_step() && main_globals.connection == _game_connection_local' + assert main.count(condition) == 2 + sources['source/main/main.c'] = main.replace(condition, 'halo_fixed_step() /* port: diagnostic fixed clock */') + timing = (root/'source/game/game_time.c').read_text() + condition = 'halo_fixed_step() && game_connection() == _game_connection_local' + assert timing.count(condition) == 1 + sources['source/game/game_time.c'] = timing.replace(condition, 'halo_fixed_step() /* port: diagnostic fixed clock */') + game = (root/'source/game/game.c').read_text() + condition = 'set_random_seed(game_globals->options.random_seed);' + assert game.count(condition) == 1 + sources['source/game/game.c'] = game.replace(condition, 'set_random_seed(0xDEADBEEF); /* port: diagnostic fixed seed */') + bots = (root/'port/linux/game/bots.c').read_text() + assert bots.count('network_game_get_random_seed()') == 1 + sources['port/linux/game/bots.c'] = bots.replace('network_game_get_random_seed()', + '0xDEADBEEF /* port: diagnostic bot seed */') + if (root/'port/linux/src/mcc_texture_bridge.c').exists(): + texture = (root/'port/linux/src/mcc_texture_bridge.c').read_text() + texture = 'void stutter_begin(int);void stutter_end(int);\n'+texture.replace('BOOL xgpu_mcc_texture_get(', 'static BOOL measured_mcc_texture_get(') + texture += ''' +BOOL xgpu_mcc_texture_get(DWORD const *resource,D3DCOLOR const *palette, + GLuint *texture,GLenum *target,struct xgpu_texture_description *description) { + BOOL result;stutter_begin(4); + result=measured_mcc_texture_get(resource,palette,texture,target,description); + stutter_end(4);return result; +} +''' + sources['port/linux/src/mcc_texture_bridge.c'] = texture + if honeycomb: + sources['port/linux/src/nv2a_psh.c'] = omit_honeycomb((root/'port/linux/src/nv2a_psh.c').read_text()) + manifest = dict(source_root=str(root), honeycomb_omitted=honeycomb, deterministic=deterministic, + record_prepared=record_prepared, source_hashes={}) + for relative, source in sources.items(): + entry = next(e for e in entries if e['file'].replace('\\', '/') == relative) + path = output/Path(relative).name; obj = path.with_suffix('.o') + path.write_text(source) + manifest['source_hashes'][relative] = hashlib.sha256((root/relative).read_bytes()).hexdigest() + command = entry['command'] + for old, new in [(entry['file'], str(path)), (entry['output'], str(obj))]: + command = command.replace(old, new).replace(old.replace('/', '\\'), new) + subprocess.run(command+' -Iport/linux/src -Iport/linux/game -Isource/main -Isource/game', cwd=root, check=True) + link = link.replace(entry['output'], str(obj)).replace(entry['output'].replace('/', '\\'), str(obj)) + link = link.replace('build\\windows\\halo.exe', str(output/'halo.exe')) + marker = ' -o '+str(output/'halo.exe')+' ' + head, tail = link.split(marker, 1) + response = output/'link.rsp'; response.write_text(tail) + subprocess.run(head+' --rsp-quoting=windows'+marker+'@'+str(response), cwd=root, check=True) + shutil.copy2(root/'build/windows/SDL3.dll', output/'SDL3.dll') + manifest['executable_sha256'] = hashlib.sha256((output/'halo.exe').read_bytes()).hexdigest() + (output/'manifest.json').write_text(json.dumps(manifest, indent=2)) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--source', type=Path, default=Path(__file__).resolve().parents[1]) + parser.add_argument('--output', type=Path, required=True) + parser.add_argument('--omit-honeycomb', action='store_true') + parser.add_argument('--deterministic', action='store_true', help='Single-process benchmark only: fixed clock and seed') + parser.add_argument('--record-prepared', action='store_true', help='Diagnostic recipe capture includes speculative materials') + args = parser.parse_args() + build(args.source, args.output, args.omit_honeycomb, args.deterministic, args.record_prepared) diff --git a/tools/render_stutter_run.py b/tools/render_stutter_run.py new file mode 100644 index 0000000000..c3cb0de5bd --- /dev/null +++ b/tools/render_stutter_run.py @@ -0,0 +1,152 @@ +"""Run one hidden, isolated renderer probe; retain timings and verified saves. + +Data must be a disposable copy under this checkout's build directory. Fixed +steps provide the same input cues per tick; compare simulation logs before +claiming identical combat. Neither this tool nor its cache seed controls the +driver's separate shader cache. +""" +import argparse +import csv +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import statistics +import subprocess +import zipfile + + +def compare_player_traces(reference, current, first=30, last=1200): + def samples(log): + # Machine slots differ between builds with different bot capacities. + # Positions, aim, health, inventory, animation and scores remain exact. + return {int(match[1]): re.sub(r' m\d+(?= |$)', ' m', match[2]) + for match in re.finditer(r'network test: tick (\d+) (player 0:.*?) \| items', log) + if first <= int(match[1]) <= last} + left, right = samples(reference), samples(current) + common = left.keys() & right.keys() + identical = sum(left[tick] == right[tick] for tick in common) + return dict(compared=len(common), identical=identical, + missing=len(left.keys() ^ right.keys()), + matched=bool(common) and identical == len(common) and left.keys() == right.keys()) + + +def summarize(rows, first=600, last=1200): + samples = [dict(row, frame_ms=(row['ns']-before['ns'])/1e6) + for before, row in zip(rows, rows[1:]) + if row['playing'] and before['playing'] and first <= row['tick'] <= last] + if not samples: + return {} + values = sorted(r['frame_ms'] for r in samples) + return dict(frames=len(values), mean_ms=statistics.mean(values), p99_ms=values[int(len(values)*.99)], + worst_ms=max(values), over16=sum(v>16.667 for v in values), over50=sum(v>50 for v in values), + worst_frames=sorted(samples, key=lambda r:r['frame_ms'], reverse=True)[:12], + totals={k:sum(r[k] for r in samples) for k in rows[0] if k.endswith(('_ns', '_calls'))}) + + +def run(args): + root = Path(__file__).resolve().parents[1] + if not re.fullmatch(r'[1-9][0-9]*x[1-9][0-9]*', args.resolution): + raise ValueError('Resolution must be WIDTHxHEIGHT') + out = args.output.resolve(); data = args.data.resolve(); binary = args.binary.resolve() + assert out.is_relative_to(root/'build') and data.is_relative_to(root/'build') + out.mkdir(parents=True, exist_ok=False) + debug = data/'debug.txt' + debug_offset = debug.stat().st_size if debug.exists() else 0 + cache = out/'saves/shader_cache'; cache.mkdir(parents=True) + if args.seed: + with zipfile.ZipFile(args.seed) as archive: + for name in archive.namelist(): + if name.startswith('saves/shader_cache/') and name.endswith('.bin'): + target = out/name + assert target.resolve().is_relative_to(cache) + target.write_bytes(archive.read(name)) + for name in ['halo.exe', 'SDL3.dll']: + shutil.copy2(binary.parent/name, out/name) + display = dict(shader_prepare=args.prepare, mcc_texture_prepare_mb=128 if args.prepare else 0, + texture_prepare_mb=128 if args.prepare else 0, + shield_look='classic_honeycomb2' if args.honeycomb else 'classic', + per_pixel_lighting=False, high_res_hud=False, viewmodel_shield=args.honeycomb, + first_person_legs=False, anti_aliasing='off', shadow_resolution=128, + anisotropic_filtering=1, model_detail='stock') + if args.quality: + display.update(per_pixel_lighting=True, anti_aliasing='msaa8x', shadow_resolution=1024, + anisotropic_filtering=16, model_detail='highest', first_person_legs=True, + viewmodel_shield=True, overshield_effect=True) + (out/'config.toml').write_text('[display]\n'+''.join(f'{k} = {json.dumps(v)}\n' for k,v in display.items())) + env = {k:v for k,v in os.environ.items() if not k.startswith('HALO_')} + env.update(HALO_DATA_ROOT=str(data), HALO_SAVE_ROOT=str(out/'saves'), HALO_HIDDEN_WINDOW='1', + HALO_DISPLAY_MODE='windowed', HALO_WINDOW_SIZE=args.resolution, HALO_MAX_FPS='120', HALO_NO_VSYNC='1', + HALO_NO_AUDIO='1', HALO_EXIT_AFTER=str(args.seconds), HALO_FIXED_STEP='1', + HALO_NET_ONLINE='0', HALO_NET_PUBLIC_LOBBY='0', HALO_NET_ALLOW_UPNP='0', + HALO_NET_JOIN_FROM_CLIPBOARD='0', HALO_DISCORD='0', HALO_NET_ADDRESS='127.0.0.1', + HALO_NET_BROADCAST='127.0.0.1', HALO_UPDATE_ANSWER='never', HALO_CRASH_REPORTS='no', + HALO_NETWORK_TEST='local:'+args.map.replace('/', '\\')+':slayer', + HALO_NETWORK_TEST_START='5', HALO_NETWORK_TEST_SCORE='10000', HALO_BOTS='7', + HALO_BOT_SKILL='heroic', HALO_TEST_INPUT='bot:1', HALO_GPU_STATS='1') + for setting in ['PLASMA_LIGHTING','MUZZLE_LIGHTING','JACKAL_SHIELD_LIGHTING','COVENANT_SHIELD_LIGHTING', + 'FUEL_ROD_LIGHTING','AMMO_COUNTER_LIGHTING','NEEDLER_LIGHTING','PLASMA_OCCLUSION','SHIELD_GLOW']: + env['HALO_'+setting] = '0' + if args.lighting: + env['HALO_SHIELD_GLOW'] = '1' + (out/'settings.json').write_text(json.dumps(dict(display=display, environment={k:v for k,v in env.items() if k.startswith('HALO_')}, + executable_sha256=hashlib.sha256(binary.read_bytes()).hexdigest()), indent=2)) + process = None + try: + with (out/'game.log').open('wb') as log: + process = subprocess.Popen([str(out/'halo.exe')], cwd=out, env=env, stdout=log, stderr=log, + creationflags=subprocess.CREATE_NO_WINDOW) + (out/'pid.txt').write_text(str(process.pid)) + process.wait(timeout=args.seconds+90) + report = dict(exit=process.returncode) + if args.compare: + report['player_trace_comparison'] = compare_player_traces( + args.compare.read_text(errors='replace'), (out/'game.log').read_text(errors='replace')) + if (out/'frames.csv').exists(): + with (out/'frames.csv').open() as file: + rows = [{k:int(v) for k,v in row.items()} for row in csv.DictReader(file)] + report['settled'] = summarize(rows) + report['gameplay'] = summarize(rows, first=1, last=1200) + report['max_tick'] = max((row['tick'] for row in rows if row['playing']), default=-1) + (out/'report.json').write_text(json.dumps(report, indent=2)) + print(json.dumps(dict(exit=report['exit'], **{k:v for k,v in report.get('settled', {}).items() + if k not in ('worst_frames', 'totals')})), flush=True) + finally: + if process and process.poll() is None: + process.terminate(); process.wait(timeout=10) + if debug.exists(): + with debug.open('rb') as log: + log.seek(debug_offset) + (out/'debug.txt').write_bytes(log.read()) + if (data/'gamestate.txt').exists(): + shutil.copy2(data/'gamestate.txt', out/'gamestate.txt') + saves = [p for p in (out/'saves').rglob('*') if p.is_file() and not (p.suffix=='.map' and p.name.startswith('cache'))] + manifest = [dict(path=p.relative_to(out).as_posix(), sha256=hashlib.sha256(p.read_bytes()).hexdigest()) for p in saves] + with zipfile.ZipFile(out/'saves.zip', 'x', zipfile.ZIP_DEFLATED) as archive: + for path, item in zip(saves, manifest): archive.write(path, item['path']) + archive.writestr('manifest.json', json.dumps(manifest, indent=2)) + with zipfile.ZipFile(out/'saves.zip') as archive: + for item in manifest: assert hashlib.sha256(archive.read(item['path'])).hexdigest() == item['sha256'] + for path in saves+list((out/'saves').rglob('cache*.map'))+[out/'halo.exe', out/'SDL3.dll']: + assert path.resolve().is_relative_to(out) and not path.is_symlink() + assert all(not p.is_junction() for p in [path, *path.parents] if p.is_relative_to(out)) + path.unlink() + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--binary', type=Path, required=True) + parser.add_argument('--data', type=Path, required=True) + parser.add_argument('--output', type=Path, required=True) + parser.add_argument('--map', default='custom_maps/deathisland') + parser.add_argument('--seconds', type=int, default=60) + parser.add_argument('--resolution', default='1920x1080') + parser.add_argument('--seed', type=Path) + parser.add_argument('--compare', type=Path, help='Reference game.log; compare sampled player state before interpreting timings') + parser.add_argument('--prepare', action='store_true') + parser.add_argument('--honeycomb', action='store_true') + parser.add_argument('--quality', action='store_true', help='Match the reported high-quality display settings') + parser.add_argument('--lighting', action='store_true', help='Enable Shield Glow, as in the reported settings') + run(parser.parse_args()) diff --git a/tools/requirements-frontend.txt b/tools/requirements-frontend.txt new file mode 100644 index 0000000000..8387ea0083 --- /dev/null +++ b/tools/requirements-frontend.txt @@ -0,0 +1,2 @@ +# Match the Pillow/FreeType wheels used to generate the checked-in menu art. +Pillow==12.3.0 diff --git a/tools/system_link_bots.py b/tools/system_link_bots.py index 3d53204617..2aa3f64906 100644 --- a/tools/system_link_bots.py +++ b/tools/system_link_bots.py @@ -29,11 +29,18 @@ import errno import ipaddress import math +import re import selectors import socket import struct import sys import time +from pathlib import Path + +# Join admission uses the shared agreement even for stand-in machines that +# send only system-link messages, not distributed gameplay messages. +NETWORK_VERSION = int(re.search(r"^#define HALO_PORT_NETWORK_VERSION (\d+)$", + (Path(__file__).resolve().parents[1] / "port/linux/include/halo_port_limits.h").read_text(), re.M)[1]) SERVER_PORT = 0x141E CLIENT_PORT = 0x141F diff --git a/tools/test_android_ce_texture_cache.py b/tools/test_android_ce_texture_cache.py index 9477b6b05a..706b1f3d5a 100644 --- a/tools/test_android_ce_texture_cache.py +++ b/tools/test_android_ce_texture_cache.py @@ -58,6 +58,7 @@ def run_c(tmp_path, code): static unsigned long xgpu_texture_face_size(const struct xgpu_texture_description *d) { return 1024; } static unsigned long xgpu_texture_level_offset(const struct xgpu_texture_description *d,int l) { return 1024; } static void glGenTextures(int n,GLuint *t) { *t=++next_texture; } +static GLuint xgpu_texture_name_new(void) { GLuint texture;glGenTextures(1,&texture);return texture; } static void glDeleteTextures(int n,GLuint *t) {} static void xgpu_gl_state_invalidate(void) {} static long hud_hires_override_find(unsigned long a,unsigned long w,unsigned long h,unsigned long b) { return -1; } diff --git a/tools/test_android_dynamic_lighting.py b/tools/test_android_dynamic_lighting.py new file mode 100644 index 0000000000..aaebd5344e --- /dev/null +++ b/tools/test_android_dynamic_lighting.py @@ -0,0 +1,162 @@ +"""Android omits optional lighting code, even for old configs or host glow policy.""" +import io +from pathlib import Path +import re +import subprocess +from types import SimpleNamespace +import xml.etree.ElementTree as ET + +from tools import android_build, ninja_syntax +from test_mcc_identity import compile_tool +from test_web_build import graph as web_graph + +ROOT = Path(__file__).resolve().parents[1] + + +def test_android_build_excludes_feature_modules(monkeypatch, tmp_path): + monkeypatch.chdir(ROOT) + ndk = tmp_path / 'ndk' + (ndk / 'toolchains/llvm/prebuilt/test-host').mkdir(parents=True) + monkeypatch.setenv('ANDROID_NDK_HOST_TAG', 'test-host') + monkeypatch.setattr(android_build, 'fetch_third_party', lambda: None) + sln = SimpleNamespace(build_dir=tmp_path / 'graph', android_ndk=ndk, + android_guest_cc='clang', compiler_launcher=None, + port_release=False, port_profile=False, port_pgo='off', + port_pgo_profile=None, port_portable=True, port_lto='off') + output = io.StringIO() + android_build.generate_android_build(ninja_syntax.Writer(output), sln) + android = output.getvalue().replace('\\', '/') + web = web_graph().replace('\\', '/') + for folder, names in [('game', android_build.DYNAMIC_LIGHTING_GAME_SOURCES), + ('src', android_build.DYNAMIC_LIGHTING_PLATFORM_SOURCES)]: + for name in names: + source = f'port/linux/{folder}/{name}' + assert (ROOT / source).is_file() + assert source not in android, source + assert source in web, source + stub = 'port/android/guest/dynamic_lighting_disabled.c' + assert stub in android and stub not in web + # Stock lighting, surface animation and network policy are still compiled. + for source in ['source/objects/object_lights.c', 'port/linux/game/overshield_effect.c', + 'port/linux/game/network_shield_effects.c']: + assert source in android + + +def test_android_hooks_preserve_stock_values_and_surface_reset(tmp_path): + (tmp_path / 'cseries.h').write_text(''' +typedef int boolean; +typedef float real; +#define FALSE 0 +#define NONE (-1) +''') + (tmp_path / 'real_math.h').write_text(''' +typedef struct { float x, y, z; } real_point3d; +typedef struct { float i, j, k; } real_vector3d; +typedef struct { float red, green, blue; } real_rgb_color; +''') + (tmp_path / 'plasma_model_shader.h').write_text( + (ROOT / 'port/linux/include/plasma_model_shader.h').read_text()) + # Compile the whole replacement against the real feature headers. There + # are deliberately no config, network, allocation, collision or GL stubs: + # an accidental dependency on those services must fail the link. + source = tmp_path / 'check.c' + production = (ROOT / 'port/android/guest/dynamic_lighting_disabled.c').read_text() + source.write_text(production + r''' +#include +static int resets; +void overshield_effect_reset(void) { resets++; } +int main(void) +{ + int map; + real_rgb_color color = {0.2f, 0.7f, 0.3f}, saved = color; + real_point3d position = {1, 2, 3}, old_position = position; + real_vector3d direction = {0, 0, 1}, old_direction = direction; + unsigned long pixel[64], old_pixel[64]; + float radius = 2.5f, axis[3] = {0, 0, 1}, origin[3] = {1, 2, 3}; + memset(pixel, 0x5a, sizeof(pixel)); + memcpy(old_pixel, pixel, sizeof(pixel)); + for (map = 0; map < 3; map++) + { + shield_glow_reset(); plasma_lighting_reset(); + muzzle_lighting_forget(); covenant_lighting_forget(); + covenant_emitter_lighting_forget(); rocket_lighting_forget(); + ammo_counter_lighting_forget(); needler_lighting_forget(); + plasma_lighting_window_begin(); shield_glow_window_begin(); + muzzle_lighting_window_begin(); covenant_lighting_window_begin(); + covenant_emitter_lighting_window_begin(); rocket_lighting_window_begin(); + muzzle_lighting_shot(42, 0); muzzle_lighting_shot(42, 1); + muzzle_lighting_update(); covenant_lighting_update(); + covenant_emitter_lighting_update(); rocket_lighting_update(); shield_glow_update(); + plasma_lighting_prepare(17, 42, NONE); plasma_lighting_submitted(17, 1); + muzzle_lighting_submitted(17, 1); covenant_lighting_submitted(17, 1); + covenant_emitter_lighting_submitted(17, 1); rocket_lighting_submitted(17, 1); + shield_glow_submitted(17, 1); plasma_model_lighting_reset(); + plasma_model_lighting_slot(17, 0); plasma_model_lighting_slot(17, 1); + if (plasma_lighting_selected(1) || muzzle_lighting_selected(1) || + covenant_lighting_selected(1) || covenant_emitter_lighting_selected(1) || + rocket_lighting_selected(1) || shield_glow_selected(1) || + plasma_model_lighting_mask() || shield_glow_enabled() || + covenant_emitter_lighting_enabled() || covenant_lighting_owns(17, 42)) return 1; + if (plasma_lighting_radius(17, 42, radius) != radius || + muzzle_lighting_radius(17, radius) != radius || + covenant_lighting_radius(17, 42, radius) != radius || + covenant_emitter_lighting_radius(17, radius) != radius || + rocket_lighting_radius(17, 42, radius) != radius || + shield_glow_radius(17, radius) != radius) return 2; + plasma_specular_begin(1); plasma_falloff_begin(1); plasma_falloff_specular_begin(1); + if (plasma_specular_color(0x7f2040ffUL) != 0x7f2040ffUL) return 3; + covenant_lighting_color(42, 10, &color); + ammo_counter_lighting_screen(0, &color); needler_lighting_material(0, &color); + ammo_counter_lighting_draw_begin(0, 0x12345678UL); ammo_counter_lighting_draw_end(); + needler_lighting_transparent(0, (struct pixel_shader_definition *)pixel, 4); + if (memcmp(&color, &saved, sizeof(color)) || memcmp(pixel, old_pixel, sizeof(pixel))) return 4; + if (ammo_counter_lighting_position(42, &position, &direction) || + needler_lighting_position(42, &position, &direction) || + memcmp(&position, &old_position, sizeof(position)) || + memcmp(&direction, &old_direction, sizeof(direction))) return 5; + if (muzzle_lighting_vehicle_occlusion(17) || plasma_lighting_vehicle_occlusion(17) || + covenant_emitter_lighting_vehicle_occlusion(17) || + covenant_emitter_lighting_occlusion_ignore(17) != NONE || + covenant_emitter_lighting_cone(1, axis, origin, &radius) || radius != 2.5f) return 6; + plasma_lighting_frame_end(); muzzle_lighting_frame_end(); covenant_lighting_frame_end(); + covenant_emitter_lighting_frame_end(); rocket_lighting_frame_end(); shield_glow_frame_end(); + plasma_falloff_end(); plasma_falloff_dispose(); + } + return resets == 3 ? 0 : 7; +} +''') + # Unused hook arguments are intentional on the unsupported platform. + source.write_text('#pragma clang diagnostic ignored "-Wunused-parameter"\n' + source.read_text()) + executable = compile_tool(tmp_path, [source]) + result = subprocess.run([str(executable)], capture_output=True, text=True, timeout=10) + assert result.returncode == 0, result.stdout + result.stderr + + +def test_android_menu_and_default_config_exclude_dynamic_lighting(): + import port_settings + config = (ROOT / 'port/linux/src/port_config.c').read_text() + spec = port_settings.SCREENS['video_settings/dynamic_lighting'] + category = next(row for row in port_settings.SCREENS['video_settings']['categories'] + if row[1] == 'video_settings/dynamic_lighting') + assert category[3] == 'desktop web' + for _, setting, _, _, platform in spec['rows']: + assert platform == 'desktop web' + groups = { + 'lighting.weapon_glow': ['display.weapon_glow', 'display.fuel_rod_lighting', + 'display.ammo_counter_lighting', 'display.needler_lighting'], + 'lighting.shield_emitters': ['display.jackal_shield_lighting', 'display.covenant_shield_lighting'], + } + for member in groups.get(setting, [setting]): + declaration = re.search(r'\{ "' + re.escape(member) + r'",[^\n]+', config)[0] + assert '_platform_desktop,' in declaration + assert '"false"' in declaration or member == 'display.shield_glow_intensity' + for name, lines in port_settings.settings_files().items(): + if name.endswith(('video_settings.xml', 'dynamic_lighting.xml')): + assert (ROOT / 'port/assets/menus/ce' / name).read_text() == '\n'.join(lines) + widgets = ET.fromstring('\n'.join(lines)) + visible_on = set() + for child in widgets.iter('child'): + if child.get('widget', '').endswith('/op_dynamic_lighting'): + visible_on.update(child.get('platform', '').split()) + if name.endswith('video_settings.xml'): + assert visible_on == {'desktop', 'web'} diff --git a/tools/test_android_mcc_memory.py b/tools/test_android_mcc_memory.py new file mode 100644 index 0000000000..2a8cedc07f --- /dev/null +++ b/tools/test_android_mcc_memory.py @@ -0,0 +1,232 @@ +"""Exercise the Android MCC host allocator and guest bridge with failing OS calls.""" +from pathlib import Path +import shutil +import subprocess +import sys + +import pytest + +from test_mcc_identity import compile_tool + +ROOT = Path(__file__).resolve().parents[1] + + +def implementation(path): + return "\n".join(line for line in (ROOT / path).read_text().splitlines() + if not line.startswith("#include")) + + +@pytest.fixture(scope="module") +def allocator(tmp_path_factory): + work = tmp_path_factory.mktemp("android-mcc-memory") + source = work / "test.c" + source.write_text(r''' +#include +#include +#include +#include +#include +#include +#define HALO_ANDROID 1 +#define HOST_LOG_WARN 5 +static void host_logf(int priority, const char *format, ...) {(void)priority; (void)format;} +#define platform_log(...) ((void)0) +#define MAP_FAILED ((void *)-1) +#define MAP_PRIVATE 1 +#define MAP_ANONYMOUS 2 +#define MAP_NORESERVE 4 +#define MAP_FIXED_NOREPLACE 8 +#define MAP_FIXED 16 +#define PROT_NONE 0 +#define PROT_READ 1 +#define PROT_WRITE 2 +typedef int test_mutex; +#define pthread_mutex_t test_mutex +#define pthread_mutex_lock test_mutex_lock +#define pthread_mutex_unlock test_mutex_unlock +#define PTHREAD_MUTEX_INITIALIZER 0 +#define CHECK(c) do { if (!(c)) {fprintf(stderr, "%d: %s\n", __LINE__, #c); exit(1);} } while (0) +static int depth, maps, unmaps, blocked, wrong_address, fail_commit, fail_release, fail_unmap; +static int pages, contents; +static void *owned; +static int pthread_mutex_lock(pthread_mutex_t *p) {(void)p; CHECK(depth++ == 0); return 0;} +static int pthread_mutex_unlock(pthread_mutex_t *p) {(void)p; CHECK(--depth == 0); return 0;} +static void *mmap(void *p, size_t n, int prot, int flags, int fd, long offset) { + CHECK(depth == 1 && n == 0x4000000u && fd == -1 && offset == 0); + maps++; + if (flags & MAP_FIXED) { + CHECK(owned && p == owned); /* Never replace a foreign reservation. */ + if ((prot && fail_commit) || (!prot && fail_release)) {errno=ENOMEM; return MAP_FAILED;} + pages=!!prot; contents=0; + return p; + } + CHECK(flags & MAP_FIXED_NOREPLACE); + if (owned || blocked) {errno=EEXIST; return MAP_FAILED;} + CHECK(prot == PROT_NONE); + owned=wrong_address ? (void *)(uintptr_t)0x60000000u : p; + return owned; +} +static int munmap(void *p, size_t n) { + CHECK(depth == 1 && p == owned && n == 0x4000000u); + if(fail_unmap) {errno=ENOMEM; return -1;} + unmaps++; owned=NULL; pages=0; contents=0; return 0; +} +''' + implementation("port/android/host/host_mcc_memory.c") + "\n" + + implementation("port/linux/src/mcc_memory.c") + r''' +int main(int argc, char **argv) { + void *p; int before, i; + CHECK(argc == 2); + if (!strcmp(argv[1], "collision")) { + blocked=1; + host_mcc_memory_initialize(); + CHECK(!owned && !mcc_window && !pages); + CHECK(!mcc_memory_reserve(0x50000000u,0x4000000u) && errno == EEXIST); + CHECK(!unmaps && !owned); + blocked=0; /* Retry if the foreign allocation has since gone away. */ + } else if (!strcmp(argv[1], "old-kernel")) { + wrong_address=1; + host_mcc_memory_initialize(); + CHECK(!owned && !mcc_window && unmaps == 1); + CHECK(!mcc_memory_reserve(0x50000000u,0x4000000u) && errno == EEXIST); + CHECK(!owned && unmaps == 2); + wrong_address=0; + } else if (!strcmp(argv[1], "invalid")) { + CHECK(!mcc_memory_reserve(0x40440000u,0x4000000u) && errno == EINVAL); + CHECK(!mcc_memory_reserve(0x80000000u,0x4000000u)); + CHECK(!mcc_memory_reserve(0x50000001u,0x4000000u)); + CHECK(!mcc_memory_reserve(0x50000000u,0x4000001u)); + CHECK(!mcc_memory_reserve(0xffffffffu,0xffffffffu)); + CHECK(!maps); + } + host_mcc_memory_initialize(); + CHECK(owned == (void *)(uintptr_t)0x50000000u && !pages && !mcc_active); + before=maps; host_mcc_memory_initialize(); CHECK(maps == before); + if (!strcmp(argv[1], "commit-failure")) { + fail_commit=1; + CHECK(!mcc_memory_reserve(0x50000000u,0x4000000u) && errno == ENOMEM); + CHECK(owned && !mcc_active && !pages); + fail_commit=0; + } + for(i=0;i<3;i++) { + p=mcc_memory_reserve(0x50000000u,0x4000000u); + CHECK(p == owned && pages && mcc_active && !contents); + contents=42; + before=maps; + CHECK(!mcc_memory_reserve(0x50000000u,0x4000000u) && errno == EBUSY); + CHECK(!mcc_memory_reserve(0x51000000u,0x4000000u) && errno == EBUSY); + CHECK(host_mcc_memory_release(0x51000000u,0x4000000u) == -EINVAL); + CHECK(host_mcc_memory_release(0x50000000u,1) == -EINVAL); + mcc_memory_release(NULL,0); + CHECK(maps == before && contents == 42); + if (!strcmp(argv[1], "release-failure")) { + fail_release=1; + CHECK(host_mcc_memory_release(0x50000000u,0x4000000u) == -ENOMEM); + CHECK(mcc_active && contents == 42); + CHECK(!mcc_memory_reserve(0x50000000u,0x4000000u) && errno == EBUSY); + fail_release=0; + } + mcc_memory_release(p,0x4000000u); + CHECK(owned == p && !mcc_active && !pages && !contents); + CHECK(host_mcc_memory_release(0x50000000u,0x4000000u) == -EINVAL); + } + if (!strcmp(argv[1], "alternate")) { + fail_unmap=1; + CHECK(!mcc_memory_reserve(0x51000000u,0x4000000u) && errno == ENOMEM); + CHECK(owned == (void *)(uintptr_t)0x50000000u); + fail_unmap=0; + blocked=1; + CHECK(!mcc_memory_reserve(0x51000000u,0x4000000u) && errno == EEXIST); + CHECK(!owned); + blocked=0; + p=mcc_memory_reserve(0x51000000u,0x4000000u); + CHECK(p == (void *)(uintptr_t)0x51000000u); + mcc_memory_release(p,0x4000000u); + CHECK(mcc_memory_reserve(0x50000000u,0x4000000u) == (void *)(uintptr_t)0x50000000u); + mcc_memory_release(owned,0x4000000u); + } + CHECK(depth == 0); + return 0; +} +''') + return compile_tool(work, [source]) + + +@pytest.mark.parametrize("case", ["reload", "collision", "old-kernel", "invalid", + "commit-failure", "release-failure", "alternate"]) +def test_android_mcc_reservation(allocator, case): + subprocess.run([str(allocator), case], check=True, capture_output=True, text=True, timeout=10) + + +def test_android_imports_and_startup(tmp_path): + main = (ROOT / "port/android/host/host_main.c").read_text() + startup = main[main.index("JNIEXPORT jint JNICALL JNI_OnLoad"):main.index("int main(")] + assert startup.index("host_memory_reserve_early();") < startup.index("host_mcc_memory_initialize();") + table = tmp_path / "imports.c" + subprocess.run([sys.executable, str(ROOT / "tools/android_imports.py"), + "--host-table", str(table), str(tmp_path / "imports.s"), + str(ROOT / "port/android/host_imports.list")], check=True) + for name in ("host_mcc_memory_reserve", "host_mcc_memory_release"): + assert name in table.read_text() + assert name in (ROOT / "port/android/guest/runtime/guest_host.h").read_text() + + +@pytest.mark.skipif(sys.platform != "linux", reason="real Linux mmap semantics") +def test_real_reserved_pages_and_foreign_mapping(tmp_path): + compiler = shutil.which("clang") + if not compiler: + pytest.skip("clang required") + source = tmp_path / "real.c" + source.write_text(r''' +#include "host_mcc_memory.h" +#include +#include +#include +#include +#include +#include +#define CHECK(c) do {if(!(c)){fprintf(stderr,"%d: %s\n",__LINE__,#c);exit(1);}}while(0) +void host_logf(int priority, const char *format, ...) {(void)priority;(void)format;} +static int successes; +static void *acquire(void *unused) { + long long result=host_mcc_memory_reserve(0x50000000u,0x4000000u); + (void)unused; + CHECK(result==0x50000000u || result==-EBUSY); + if(result>0) __sync_add_and_fetch(&successes,1); + return NULL; +} +int main(void) { + unsigned char *p=(unsigned char *)(uintptr_t)0x50000000u; + void *other; + pthread_t a,b; + /* A real occupied page: even a partial overlap must survive unchanged. */ + CHECK(mmap(p+4096,4096,PROT_READ|PROT_WRITE, + MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED_NOREPLACE,-1,0)==p+4096); + p[4096]=123; + host_mcc_memory_initialize(); + CHECK(host_mcc_memory_reserve(0x50000000u,0x4000000u)==-EEXIST); + CHECK(p[4096]==123); + CHECK(!munmap(p+4096,4096)); + host_mcc_memory_initialize(); + other=mmap(p,4096,PROT_NONE,MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED_NOREPLACE,-1,0); + CHECK(other==MAP_FAILED && errno==EEXIST); + CHECK(!pthread_create(&a,NULL,acquire,NULL)); + CHECK(!pthread_create(&b,NULL,acquire,NULL)); + CHECK(!pthread_join(a,NULL) && !pthread_join(b,NULL) && successes==1); + p[0]=42;p[0x3ffffff]=43; + CHECK(!host_mcc_memory_release(0x50000000u,0x4000000u)); + CHECK(mmap(p,4096,PROT_NONE,MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED_NOREPLACE,-1,0)==MAP_FAILED); + CHECK(errno==EEXIST); + CHECK(host_mcc_memory_reserve(0x50000000u,0x4000000u)==0x50000000u); + CHECK(!p[0] && !p[0x3ffffff]); + CHECK(!host_mcc_memory_release(0x50000000u,0x4000000u)); + return 0; +} +''') + binary = tmp_path / "real" + result = subprocess.run([compiler, "-std=gnu89", "-Wall", "-Wextra", "-Werror", "-pthread", + "-I", str(ROOT / "port/android/include"), + "-I", str(ROOT / "port/android/host"), str(source), + str(ROOT / "port/android/host/host_mcc_memory.c"), "-o", str(binary)], + capture_output=True, text=True) + assert result.returncode == 0, result.stderr + subprocess.run([str(binary)], check=True, capture_output=True, text=True, timeout=10) diff --git a/tools/test_android_render_policy.py b/tools/test_android_render_policy.py index 155e640cbe..6df0790379 100644 --- a/tools/test_android_render_policy.py +++ b/tools/test_android_render_policy.py @@ -128,12 +128,13 @@ def test_policy_is_selected_before_game_resources(): assert imports.count("host_android_chip_family") == 1 -@pytest.mark.parametrize("enabled,ce,cached,valid,loads,legacy", [ - (1, 1, 1, 1, 1, 0), (0, 1, 1, 1, 0, 1), - (1, 0, 1, 1, 0, 1), (0, 0, 1, 1, 0, 1), - (1, 1, 0, 1, 0, 1), (1, 1, 1, 0, 0, 0), +@pytest.mark.parametrize("enabled,ce,mcc,cached,valid,loads,legacy", [ + (1, 1, 0, 1, 1, 1, 0), (0, 1, 0, 1, 1, 0, 1), + (1, 0, 0, 1, 1, 0, 1), (0, 0, 0, 1, 1, 0, 1), + (1, 1, 0, 0, 1, 0, 1), (1, 1, 0, 1, 0, 0, 0), + (1, 1, 1, 1, 1, 0, 1), (0, 1, 1, 1, 1, 0, 1), ]) -def test_texture_dispatch_boundaries(tmp_path, enabled, ce, cached, valid, loads, legacy): +def test_texture_dispatch_boundaries(tmp_path, enabled, ce, mcc, cached, valid, loads, legacy): source = (ROOT / "source/cache/xbox_texture_cache.c").read_text() get = function(source, "_texture_cache_bitmap_get_hardware_format") block = get[get.index("#ifdef HALO_ANDROID"):get.index("#endif") + len("#endif")] @@ -156,6 +157,6 @@ def test_texture_dispatch_boundaries(tmp_path, enabled, ce, cached, valid, loads int load = 1; ''' code += block + "\n{ legacy++; }\n}\nint main(void) { struct bitmap_data bitmap={0};\n" - code += f"android_texture_fixes={enabled};ce={ce};valid={valid};bitmap.flags={cached};dispatch(&bitmap);\n" + code += f"android_texture_fixes={enabled};ce={ce};mcc={mcc};valid={valid};bitmap.flags={cached};dispatch(&bitmap);\n" code += f"return loads!={loads} || legacy!={legacy}; }}\n" run_c(tmp_path, code) diff --git a/tools/test_android_shader_logs.py b/tools/test_android_shader_logs.py new file mode 100644 index 0000000000..bd404d91e0 --- /dev/null +++ b/tools/test_android_shader_logs.py @@ -0,0 +1,95 @@ +"""Exercise the shipped collector with a fake adb process, without a device.""" +import importlib.util +import json +from pathlib import Path +import subprocess +import sys +import zipfile + +import pytest + +ROOT = Path(__file__).resolve().parents[1] +SCRIPT = ROOT / 'port/android/diagnostics/collect_shader_logs.py' +spec = importlib.util.spec_from_file_location('collect_shader_logs', SCRIPT) +collector = importlib.util.module_from_spec(spec) +spec.loader.exec_module(collector) + + +@pytest.fixture +def fake_adb(tmp_path, monkeypatch): + audit = tmp_path / 'commands.jsonl' + monkeypatch.setenv('TEST_ADB_AUDIT', str(audit)) + script = tmp_path / 'adb.py' + script.write_text(r''' +import json, os, sys, time +args = sys.argv[1:] +with open(os.environ['TEST_ADB_AUDIT'], 'a') as output: + output.write(json.dumps(args)+'\n') +if args[:2] == ['-s', 'test-device']: + args = args[2:] +if args == ['get-state']: + print('device') +elif args[:2] == ['shell', 'getprop']: + print('test-property') +elif args[:3] == ['shell', 'dumpsys', 'package']: + print('versionName=test-build') +elif args[0] == 'logcat': + if os.environ.get('TEST_ADB_DISCONNECT'): + print('device disconnected', file=sys.stderr, flush=True) + sys.exit(3) + print('OpenGL ES 3.0 on test-GPU', flush=True) + print('cannot compile the vertex shader:', flush=True) + print('no precision specified for sampler3D', flush=True) + print('uniform sampler3D plasma_occ_texture0;', flush=True) + for i in range(500): + print('shader source line '+str(i), flush=True) + time.sleep(30) +else: + sys.exit('unexpected command: '+repr(args)) +''') + return [sys.executable, str(script), '-s', 'test-device'], audit + + +def test_capture_preserves_shader_source_and_only_reads_device(fake_adb, tmp_path): + adb, audit = fake_adb + folder = tmp_path / 'capture' + archive = collector.collect(adb, folder, 0.4) + with zipfile.ZipFile(archive) as zipped: + assert zipped.testzip() is None + raw = zipped.read('shader-logcat.txt').decode() + assert 'no precision specified for sampler3D' in raw + assert 'shader source line 499' in raw + assert len(raw) > 4096 + summary = zipped.read('summary.txt').decode() + assert 'cannot compile' in summary and 'does not prove' in summary + metadata = json.loads(zipped.read('device.json')) + assert metadata['stop_reason'] == 'time limit' + assert metadata['ro.product.model'] == 'test-property' + calls = [json.loads(line) for line in audit.read_text().splitlines()] + assert all(call[:2] == ['-s', 'test-device'] for call in calls) + calls = [call[2:] for call in calls] + assert calls == [['get-state'], + *[['shell', 'getprop', key] for key in collector.PROPERTIES], + ['shell', 'dumpsys', 'package', 'com.halo.decomp'], + ['logcat', '-v', 'threadtime', '-T', '1', 'halo:V', '*:S']] + with pytest.raises(FileExistsError): + collector.collect(adb, folder, 0.4) + + +def test_disconnect_retains_partial_diagnostics(fake_adb, tmp_path, monkeypatch): + adb, _ = fake_adb + monkeypatch.setenv('TEST_ADB_DISCONNECT', '1') + folder = tmp_path / 'disconnected' + with pytest.raises(RuntimeError, match='adb stopped'): + collector.collect(adb, folder, 1) + with zipfile.ZipFile(folder.with_suffix('.zip')) as zipped: + assert 'device disconnected' in zipped.read('adb-errors.txt').decode() + assert json.loads(zipped.read('device.json'))['logcat_exit_code'] == 3 + + +@pytest.mark.parametrize('seconds', ['0', '601']) +def test_duration_is_bounded(seconds): + result = subprocess.run([sys.executable, str(SCRIPT), '--seconds', seconds], + capture_output=True, text=True, timeout=10) + assert result.returncode == 2 + assert 'between 1 and 600' in result.stderr diff --git a/tools/test_android_signing.py b/tools/test_android_signing.py new file mode 100644 index 0000000000..9f0297d739 --- /dev/null +++ b/tools/test_android_signing.py @@ -0,0 +1,69 @@ +"""Exercise the CI signing script without real credentials or Android tools.""" + +import base64 +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + + +SCRIPT = Path(__file__).with_name("android_signing.py") + + +class SigningTests(unittest.TestCase): + def run_signing(self, ref, key="", password=""): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + env_file = root / "env" + env = dict(os.environ, GITHUB_REF=ref, KEYSTORE=key, + HALO_ANDROID_KEYSTORE_PASSWORD=password, + RUNNER_TEMP=directory, GITHUB_ENV=str(env_file)) + result = subprocess.run([sys.executable, str(SCRIPT)], env=env, + capture_output=True, text=True) + staged = root / "halo.keystore" + return (result, staged.read_bytes() if staged.exists() else None, + env_file.read_text() if env_file.exists() else "") + + def test_main_requires_both_secrets(self): + for key, password in (("", ""), ("a2V5", ""), ("", "password")): + with self.subTest(key_present=bool(key), password_present=bool(password)): + result, staged, exported = self.run_signing("refs/heads/main", key, password) + self.assertNotEqual(result.returncode, 0) + self.assertIn("::error::", result.stdout) + self.assertIsNone(staged) + self.assertEqual(exported, "") + + def test_other_branch_without_secrets_keeps_debug_builds(self): + result, staged, exported = self.run_signing("refs/heads/testing") + self.assertEqual(result.returncode, 0) + self.assertIn("::warning::", result.stdout) + self.assertIsNone(staged) + self.assertEqual(exported, "") + + def test_partial_configuration_on_other_branch_fails(self): + result, _, _ = self.run_signing("refs/heads/testing", "a2V5") + self.assertNotEqual(result.returncode, 0) + + def test_malformed_base64_fails_without_exporting_key(self): + result, staged, exported = self.run_signing("refs/heads/main", "!invalid!", "password") + self.assertNotEqual(result.returncode, 0) + self.assertIsNone(staged) + self.assertEqual(exported, "") + + def test_configured_build_stages_key_without_logging_secrets(self): + key = b"synthetic keystore contents" + encoded = base64.encodebytes(key).decode() + for ref in ("refs/heads/main", "refs/heads/testing"): + with self.subTest(ref=ref): + result, staged, exported = self.run_signing(ref, encoded, "private-password") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(staged, key) + self.assertTrue(exported.startswith("HALO_ANDROID_KEYSTORE=")) + self.assertNotIn("private-password", result.stdout + result.stderr + exported) + self.assertNotIn(encoded.strip(), result.stdout + result.stderr + exported) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_bots.py b/tools/test_bots.py index 7e6c0ab4d5..bb785f8ae9 100644 --- a/tools/test_bots.py +++ b/tools/test_bots.py @@ -1,7 +1,8 @@ """The bots (port/linux/game/bots.c, bots.count) in the game: a local Slayer game on a stock map, played without a person (debug.network_test "local:", the scripted controller 1 of debug.test_input) for a minute and more, in which every bot walks the map, the bots kill and die, and the game ends cleanly; and a system link game, which no bot joins -whatever bots.count asks. Needs the retail maps in assets/maps and ninja linux's build/linux/halo; the game draws +when bots.network is off. Enhanced objective cases additionally require actual CTF capture or hill scores. +Retail map/build/profile paths can be supplied through HALO_TEST_MAPS, HALO_TEST_GAME and HALO_TEST_SAVES. The game draws offscreen (SDL's offscreen video driver), with no audio, internet play or update check.""" import math @@ -13,13 +14,13 @@ import pytest -RETAIL_MAPS = Path("assets/maps") -GAME = Path("build/linux/halo") +RETAIL_MAPS = Path(os.environ.get("HALO_TEST_MAPS", "assets/maps")) +GAME = Path(os.environ.get("HALO_TEST_GAME", "build/linux/halo")) # a player's line of the network test's each second (network_test.c): alive or dead, its kills, deaths, team and -# machine (a bot's is BOTS_FIRST_MACHINE, 113, and up) -PLAYER = re.compile(r"player (\d+): (?:\((-?[\d.]+) (-?[\d.]+) -?[\d.]+\)|dead).*? s-?\d+ k(-?\d+) d(-?\d+) f-?\d+ " +# machine (a bot's is BOTS_FIRST_MACHINE, 65, and up) +PLAYER = re.compile(r"player (\d+): (?:\((-?[\d.]+) (-?[\d.]+) -?[\d.]+\)|dead).*? s(?P-?\d+) k(-?\d+) d(-?\d+) f-?\d+ " r"t-?\d+ m(\d+)") -BOTS_FIRST_MACHINE = 113 +BOTS_FIRST_MACHINE = 65 def _game(map_name): @@ -31,20 +32,47 @@ def _play(tmp_path, test, seconds, **settings): """the game played for that many seconds: (exit status, its output, debug.txt)""" (tmp_path / "data").mkdir() (tmp_path / "save").mkdir() - (tmp_path / "data" / "maps").symlink_to(RETAIL_MAPS.resolve()) - game = tmp_path / "halo" + if os.environ.get("HALO_TEST_SAVES"): + shutil.copytree(os.environ["HALO_TEST_SAVES"], tmp_path / "save", dirs_exist_ok=True, + ignore=shutil.ignore_patterns("cache*.map")) + if os.name == "nt": + maps = tmp_path / "data" / "maps" + maps.mkdir() + # Only this scenario's maps; remove these disposable copies after the run. + for name in {"ui.map", "carousel.map", test.split(":")[1] + ".map"}: + source = RETAIL_MAPS / name + if source.is_file(): + shutil.copyfile(source, maps / name) + else: + (tmp_path / "data" / "maps").symlink_to(RETAIL_MAPS.resolve()) + game = tmp_path / ("halo.exe" if os.name == "nt" else "halo") shutil.copy(GAME, game) + for library in GAME.parent.glob("*.dll"): + shutil.copy(library, tmp_path / library.name) env = {**os.environ, "SDL_VIDEODRIVER": "offscreen", "SDL_AUDIODRIVER": "dummy", "HALO_DATA_ROOT": str(tmp_path / "data"), "HALO_SAVE_ROOT": str(tmp_path / "save"), - "HALO_HIDDEN_WINDOW": "1", "HALO_FULLSCREEN": "0", "HALO_NO_VSYNC": "1", "HALO_NO_AUDIO": "1", - "HALO_UPDATE_AUTO": "false", "HALO_NET_ONLINE": "false", "HALO_NET_ADDRESS": "127.0.0.1", - "HALO_NET_BROADCAST": "127.255.255.255", "HALO_NETWORK_TEST": test, "HALO_NETWORK_TEST_START": "5", + "HALO_HIDDEN_WINDOW": "1", "HALO_NULL_RENDERER": "1", "HALO_FULLSCREEN": "0", "HALO_NO_VSYNC": "1", "HALO_NO_AUDIO": "1", + "HALO_UPDATE_AUTO": "false", "HALO_NET_ONLINE": "false", + "HALO_NET_ADDRESS": os.environ.get("HALO_TEST_NET_ADDRESS", "127.0.0.1"), + "HALO_NET_BROADCAST": os.environ.get("HALO_TEST_NET_BROADCAST", "127.255.255.255"), "HALO_NETWORK_TEST": test, "HALO_NETWORK_TEST_START": "5", "HALO_NETWORK_TEST_SCORE": "500", "HALO_TEST_INPUT": "bot:1", "HALO_EXIT_AFTER": str(seconds + 20)} env.update({name: str(value) for name, value in settings.items()}) - result = subprocess.run([str(game)], cwd=tmp_path, env=env, capture_output=True, text=True, - errors="replace", timeout=seconds + 120) - debug = tmp_path / "data" / "debug.txt" - return result.returncode, result.stdout + result.stderr, debug.read_text(errors="replace") if debug.is_file() else "" + try: + result = subprocess.run([str(game)], cwd=tmp_path, env=env, capture_output=True, text=True, + errors="replace", timeout=seconds + 120, + creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0) + output = result.stdout + result.stderr + (tmp_path / "output.log").write_text(output, encoding="utf-8") + debug = tmp_path / "data" / "debug.txt" + return result.returncode, output, debug.read_text(errors="replace") if debug.is_file() else "" + finally: + owned = [game, *(tmp_path.glob("*.dll")), *((tmp_path / "save").rglob("cache*.map"))] + if os.name == "nt": + owned.extend((tmp_path / "data" / "maps").glob("*.map")) + for path in owned: + assert path.resolve().is_relative_to(tmp_path.resolve()) and not path.is_symlink() + if path.is_file(): + path.unlink() def _players(output): @@ -56,7 +84,7 @@ def _players(output): for match in PLAYER.finditer(line): index = int(match.group(1)) player = players.setdefault(index, {"walked": 0.0}) - player.update(kills=int(match.group(4)), deaths=int(match.group(5)), machine=int(match.group(6))) + player.update(score=int(match.group("score")), kills=int(match.group(5)), deaths=int(match.group(6)), machine=int(match.group(7))) if match.group(2) is None: last.pop(index, None) continue @@ -89,6 +117,21 @@ def test_bots_play_a_local_slayer_game(tmp_path, map_name, variant, count, skill assert "bots: fights since" in output, "no line of the fight's counts after the bots line" +@pytest.mark.parametrize("variant", ["slayer", "ctf", "king"]) +def test_enhanced_bots_play_objectives(tmp_path, variant): + _game("bloodgulch") + status, output, debug = _play(tmp_path, f"local:bloodgulch:{variant}", 75, + HALO_BOTS=6, HALO_BOTS_ENHANCED="true", HALO_BOT_ROUTES="mixed") + assert status == 0, output[-2000:] + assert not re.search(r"assert|exception", output + debug, re.I), output[-2000:] + bots = [player for player in _players(output).values() if player["machine"] >= BOTS_FIRST_MACHINE] + assert len(bots) == 6, output[-2000:] + assert all(bot["walked"] >= 20 for bot in bots), bots + assert sum(bot["kills"] for bot in bots) > 0, bots + if variant == "king": + assert sum(bot["score"] for bot in bots) > 0, f"no objective scores: {bots}" + + def test_no_bots_in_a_system_link_game(tmp_path): _game("bloodgulch") status, output, _ = _play(tmp_path, "host:bloodgulch:slayer", 30, HALO_BOTS=6) @@ -97,3 +140,20 @@ def test_no_bots_in_a_system_link_game(tmp_path): assert players, "the system link game did not start" assert all(player["machine"] < BOTS_FIRST_MACHINE for player in players.values()), "a bot in a system link game" assert not re.search(r"\bbots: ", output), "the bots ran in a system link game" + + +def test_enhanced_bots_capture_flag(tmp_path): + """An unopposed team must complete a flag run; kills do not satisfy it. + + Balanced matches above exercise contested play. Requiring a capture in + every short balanced match confuses competent defense with AI failure. + """ + _game("bloodgulch") + status, output, debug = _play(tmp_path, "local:bloodgulch:ctf", 180, + HALO_BOTS=6, HALO_BOTS_ENHANCED="true", HALO_BOT_TEAMS="against", + HALO_BOT_ROUTES="mixed", HALO_TEST_INPUT="") + assert status == 0, output[-2000:] + assert not re.search(r"assert|exception", output + debug, re.I), output[-2000:] + bots = [p for p in _players(output).values() if p["machine"] >= BOTS_FIRST_MACHINE] + assert len(bots) == 6, bots + assert sum(p["score"] for p in bots) > 0, f"no completed flag run: {bots}" diff --git a/tools/test_bots_menu.py b/tools/test_bots_menu.py new file mode 100644 index 0000000000..9fb6aa5f35 --- /dev/null +++ b/tools/test_bots_menu.py @@ -0,0 +1,72 @@ +"""Bot menus remain reachable, generated, and use typed host actions.""" +from pathlib import Path +import xml.etree.ElementTree as ET + +import port_settings + +ROOT = Path(__file__).resolve().parents[1] +MENUS = ROOT / "port/assets/menus/ce" +BASE = port_settings.PE + "/network_setup/bots" + + +def document(path): + return ET.parse(MENUS / (path.replace("/", ".") + ".xml")).getroot() + + +def test_generated_bot_screens_and_entry_points(): + generated = port_settings.settings_files() + generated.update(port_settings.multiplayer_files()) + for path in (BASE, BASE + "/manage", port_settings.PE + "/network_setup", + port_settings.PE + "/network_setup.in_game", + port_settings.MT + "/server_settings", port_settings.MT + "/lobby"): + name = path.replace("/", ".") + ".xml" + assert (MENUS / name).read_text(encoding="utf-8") == "\n".join(generated[name]) + for path in (port_settings.PE + "/network_setup", port_settings.PE + "/network_setup.in_game", + port_settings.MT + "/server_settings", port_settings.MT + "/lobby"): + assert any(BASE + "/bots_screen" in node.attrib.values() for node in document(path).iter()) + lobby = document(port_settings.MT + "/lobby") + assert lobby.find(".//on[@run='port bots host entry']") is not None + + +def test_capacity_choices_and_live_actions(): + root = document(BASE) + count = root.find(".//widget[@setting='bots.count']") + assert count is not None + assert count.get("values").split("|") == [str(n) for n in range(64)] + root = document(BASE + "/manage") + help_widget = root.find("widget[@name='" + BASE + "/manage/help']") + assert help_widget.find("on[@event='created'][@run='port bots init']") is not None + # A string list (including inline text) overwrites runtime feedback on render. + assert "text" not in help_widget.attrib and "string_list" not in help_widget.attrib + rows = [w for w in root.findall("widget") if w.find("on[@run='port bots command']") is not None] + assert {w.get("name").rsplit("/", 1)[1] for w in rows} == { + "op_add_any", "op_add_red", "op_add_blue", "op_drop_any", "op_drop_red", "op_drop_blue"} + for row in rows: + assert row.find("on[@event='left_mouse']") is not None + assert row.find("on[@event='a']") is not None + # All menu-local child references resolve, including the management footer. + names = {w.get("name") for w in root.findall("widget")} + for child in root.iter("child"): + target = child.get("widget") + if target.startswith(BASE): + assert target in names + + +def test_bot_settings_apply_only_on_ok_and_help_fits(): + root = document(BASE) + ok = root.find("widget[@name='" + BASE + "/button_ok']") + registered = (ROOT / "port/linux/game/menu_tags.c").read_text() + for event in ("a", "start"): + assert ok.find(f"on[@event='{event}'][@run='port bots settings save'][@back='true']") is not None + assert '"port bots settings save"' in registered + # Cancel/back never saves the choices or applies a host policy. + screen = root.find("widget[@name='" + BASE + "/bots_screen']") + for event in ("b", "back"): + assert "run" not in screen.find(f"on[@event='{event}']").attrib + help_widget = root.find("widget[@name='" + BASE + "/help']") + assert int(help_widget.get("top")) + int(help_widget.get("height")) <= 414 + helps = root.find("strings[@name='" + BASE + "/help_strings']") + for hint in helps: + lines = hint.get("text").split("\\n") + assert len(lines) <= 2 + assert all(len(line) <= 42 for line in lines) diff --git a/tools/test_cache_file_formats.py b/tools/test_cache_file_formats.py index c5a0a5180b..1a197cda49 100644 --- a/tools/test_cache_file_formats.py +++ b/tools/test_cache_file_formats.py @@ -397,12 +397,13 @@ def __init__(self, opensauce_flags=None, trailing=b"", font_style_reference=NONE, pitch_ranges=1, bsp_sizes=(0x1000,), sound_compression=1, model=None, bsp_material=None, shaders=(), animation_overlay=None, weapon_hud=None, hud_bitmap_flags=None, in_map_bitmap=None, strings_name="test\\strings", - strings=("hello", "world!"), name=b"test", tags_checksum=0): + strings=("hello", "world!"), name=b"test", tags_checksum=0, hud_digits=None): self.bsp_sizes = bsp_sizes # the header's name and the tag data's checksum, by which Chimera's # map list knows a map self.name = name self.tags_checksum = tags_checksum + self.hud_digits = hud_digits self.sound_compression = sound_compression # opt-in tags and content, so the defaults above keep their counts self.model = model @@ -467,6 +468,8 @@ def build(self): tags.append(("antr", "test\\animations", False)) if self.weapon_hud is not None: tags.append(("wphi", "test\\weapon hud", False)) + if self.hud_digits is not None: + tags += [("matg", "test\\globals", False), ("hud#", "test\\digits", False)] # further structure BSPs go last, so the indices above never move bsp_tag_indices = [1] + [len(tags) + extra for extra in range(len(self.bsp_sizes) - 1)] tags += [("sbsp", f"test\\bsp {extra + 2}", False) for extra in range(len(self.bsp_sizes) - 1)] @@ -546,6 +549,17 @@ def build(self): tag_data.u32(sound + 0x98, self.pitch_ranges) address_of["test\\sound"] = sound address_of["test\\weapon"] = tag_data.add(bytes(0x100)) + if self.hud_digits is not None: + globals_address = tag_data.reserve(0x1AC) + interface = tag_data.reserve(0x130) + digits = tag_data.reserve(0x64) + digits_index = [name for _, name, _ in tags].index("test\\digits") + tag_data.block(globals_address + 0x140, 1, interface) + tag_data.u32(interface + 0xB0 + 12, ((salt + digits_index) << 16) | digits_index) + tag_data.u32(digits + 12, ((salt + 2) << 16) | 2) + tag_data.put(digits + 16, struct.pack("6b", *self.hud_digits)) + address_of["test\\globals"] = globals_address + address_of["test\\digits"] = digits for group_name, name, external in self.extra_tags: address_of[name] = tag_data.add(bytes(0x40)) if self.model is not None: @@ -1054,6 +1068,25 @@ def test_hud_elements_drawing_a_halo_pc_half_scale_bitmap_are_halved(report_tool assert (f32_at(tags, items + 4), f32_at(tags, items + 8)) == (1.0, 1.0) +@pytest.mark.parametrize("placement_flag,bitmap_flags,static_scale,item_scale", [ + (0, 0, 1.0, 1.0), (4, 0, 0.5, 1.0), + (0, 0x10, 0.5, 0.5), (0, 0x80, 0.5, 0.5), + (4, 0x80, 0.5, 0.5), (4, 0x10, 0.25, 0.5), + (0, 0x90, 0.25, 0.25), (4, 0x90, 0.25, 0.25), +]) +def test_hud_scale_flags_compose_without_scaling_crosshair_placement_flags( + report_tool, tmp_path, placement_flag, bitmap_flags, static_scale, item_scale): + cache = Map(weapon_hud=[((1.0, 1.0), placement_flag), ((1.0, 1.0), 0), + ((1.0, 1.0), placement_flag)], hud_bitmap_flags=bitmap_flags) + returncode, _, tags = converted(report_tool, cache, tmp_path) + assert returncode == 0 + hud = cache.addresses["test\\weapon hud"] + statics = u32_at(tags, hud + 0x64) + items = u32_at(tags, u32_at(tags, hud + 0x88) + 0x38) + assert f32_at(tags, statics + 0x28) == static_scale + assert f32_at(tags, items + 4) == item_scale + + @pytest.mark.parametrize("name, tags_checksum, listed", [ (b"rev_snowcast_cavebeta", 1683840640, True), (b"Rev_Snowcast_CaveBeta", 1683840640, True), @@ -1073,6 +1106,24 @@ def test_maps_chimera_lists_get_halo_pc_behaviours(report_tool, tmp_path, name, assert report["hud_placements_rescaled"] == ("0" if listed else "2") +@pytest.mark.parametrize("name, checksum, matched", [ + (b"bigass_open_v1.1", 0xD2BC19F7, True), + (b"Bigass_Open_V1.1", 0xD2BC19F7, True), + (b"bigass_open_v1.1", 0xD2BC19F6, False), + (b"another_map", 0xD2BC19F7, False), +]) +def test_bigass_open_digit_metrics_and_meter_identity(report_tool, tmp_path, name, checksum, matched): + cache = Map(name=name, tags_checksum=checksum, hud_digits=(16, 14, 0, 0, 6, 7)) + returncode, report, tags = converted(report_tool, cache, tmp_path) + assert returncode == 0 + assert report["halo_pc_behaviours"] == ( + "hud_number_scale xbox_ammo_meter_channels" if matched else "none") + metrics = struct.unpack_from("6b", tags, cache.addresses["test\\digits"] - BASE + 16) + assert metrics == ((8, 7, 0, 0, 3, 4) if matched else (16, 14, 0, 0, 6, 7)) + flags = u16_at(tags, cache.addresses["test\\in map bitmap"] + 6) + assert bool(flags & (1 << 4)) == matched + + SCORE_HINT = 'Hold "%s" for score' @@ -1201,6 +1252,8 @@ def instance_case(tag_index, delta, fmt, value): "the model vertex and index data do not fit in the file"), "handle": (instance_case(3, 0x0C, "state != _network_game_server_state_pregame ||", "") + stub = r''' +#include +#include +typedef int boolean; +#define TRUE 1 +#define FALSE 0 +#define NONE -1 +enum {HALO_KEYBOARD_TOGGLE_PERSPECTIVE=21,HALO_KEYBOARD_SWAP_SHOULDER=19}; +enum {_network_game_server_state_pregame=0}; +struct network_game {unsigned char cooperative_flags;}; +struct network_game_server {int state;struct network_game game;}; +static struct network_game_server host; +static struct network_game *current; +static struct network_game_server *server_pointer; +static char const *host_setting="player_choice"; +static int preference,shoulder,writes,sends; +static int capability=1; +static int third_person_session_active(void){return capability;} +static int network_game_is_active(void){return current!=NULL;} +static int main_menu_is_active(void){return current==NULL;} +static void main_goto_main_menu(void){/* No menu transition for camera settings. */} +static int network_game_is_splitscreen_local(void){return 0;} +static unsigned long held; +static struct network_game *network_game_get_game(void){return current;} +static struct network_game_server *global_network_game_server_get(void){return server_pointer;} +static int network_game_server_send_game_data_pregame(struct network_game_server *s){(void)s;sends++;return 1;} +static void network_event(char const *s){(void)s;} +char const *config_string(char const *s){(void)s;return host_setting;} +int config_boolean(char const *s){return strstr(s,"left_shoulder")?shoulder:preference;} +int config_write(char const *s,char const *v){int value=!strcmp(v,"true");if(strstr(s,"left_shoulder"))shoulder=value;else preference=value;writes++;return 1;} +static unsigned long halo_keyboard_actions(short p){(void)p;return held;} +struct pc_menu_setting {char const *setting;short loaded_index,value_count;char const *values[2];}; +struct widget_instance {struct {struct {short selected_index;} list;} parameters;}; +static short setting_value_index(struct pc_menu_setting const *s,char const *v){int i;for(i=0;ivalue_count;i++)if(!strcmp(s->values[i],v))return i;return NONE;} +static int setting_write(char const *s,char const *v){return config_write(s,v);} +#define platform_log(...) ((void)0) +unsigned int controller_remap_pressed(short port,unsigned int mask){(void)port;(void)mask;return 0;} +''' + pad_enums + enums + "\n" + defines + "\n" + policy + setter + menu_functions + r''' +#define CHECK(c) do{if(!(c))return __LINE__;}while(0) +static void press(unsigned long key){held=0;third_person_input_update();held=key;third_person_input_update();} +int main(void){int i,p,saved;struct network_game remote; + struct pc_menu_setting setting={"display.third_person",0,2,{"false","true"}}; + struct widget_instance spinner={{{0}}}; + CHECK(third_person_host_policy()==0); + host_setting="forced_on";CHECK(third_person_host_policy()==1); + host_setting="forced_off";CHECK(third_person_host_policy()==2); + host_setting="bad";CHECK(third_person_host_policy()==0); + capability=0;current=&remote;preference=1;CHECK(third_person_policy()==2&&!third_person_enabled()); + CHECK(!third_person_match_flags_valid(16)&&third_person_match_flags_valid(15));capability=1;current=NULL; + for(i=0;i<256;i++)CHECK(!!third_person_match_flags_valid(i)==(i<=47)); + CHECK(!third_person_match_flags_valid(256)); + for(p=0;p<3;p++)for(i=0;i<2;i++){ + remote.cooperative_flags=(p<cooperative_flags)" in function(client, "network_game_client_game_settings_updated") + menus = (ROOT / "port/linux/game/menu_functions.c").read_text() + for name in ("setting_write", "setting_save"): + assert '"display.third_person"' in function(menus, name) + assert "third_person_policy() != _third_person_player_choice" in function(menus, name) + assert "third_person_input_update();" in (ROOT / "source/main/main.c").read_text() + assert 'config_write_boolean("display.third_person"' not in (ROOT / "port/linux/src/xinput_sdl.c").read_text() + +def test_host_camera_menu_layout(): + import xml.etree.ElementTree as ET + import port_settings + root = ET.fromstring("\n".join(port_settings.multiplayer_files()["main_menu.multiplayer_type_select.server_settings.xml"])) + base = "main_menu/multiplayer_type_select/server_settings/" + menu = root.find(f"widget[@name='{base}options_menu']") + rows = {node.attrib["widget"].removeprefix(base): int(node.attrib["y"]) for node in menu.findall("child")} + help_box = root.find(f"widget[@name='{base}help']") + assert int(help_box.attrib["left"]) == 54 + 13 + assert int(help_box.attrib["height"]) >= 40 + assert int(help_box.attrib["top"]) + int(help_box.attrib["height"]) <= rows["button_bar"] + common = ["op_server_name", "op_max_players", "op_listing", "op_password", "op_session_options", "op_map_share_options"] + for mode in (["op_coop_options", "op_voice_options"], ["op_game_type", "op_player_options", "op_item_options", "op_vehicle_options", "op_indicator_options", "op_team_options"]): + positions = [rows[name] for name in common + mode] + assert len(set(positions)) == len(positions) + assert max(positions) + 28 <= int(root.find(f"widget[@name='{base}help']").attrib["top"]) + assert all(b - a >= 28 for a, b in zip(sorted(positions), sorted(positions)[1:])) + assert all(int(root.find(f"widget[@name='{base}{name}']").attrib["height"]) >= 28 for name in common + mode) + assert root.find(f"widget[@name='{base}op_session_options']/on[@event='a']").attrib["open"] == base + "session_options/session_options_screen" + sub = base + "session_options/" + assert "op_invite" not in rows + assert root.find(f"widget[@name='{sub}options_menu']/child[@widget='{sub}op_invite']") is not None + for key in ("session_compatibility", "camera_policy"): + row = root.find(f"widget[@name='{sub}op_{key}']") + label = root.find(f"widget[@name='{sub}{key}_label']") + spinner = root.find(f"widget[@name='{sub}{key}_spinner']") + child = row.find(f"child[@widget='{sub}{key}_spinner']") + assert row.attrib["width"] == "512" and row.attrib["height"] == "28" + assert label.attrib["font"] == spinner.attrib["font"] == "ui\\large_ui" + assert int(child.attrib["y"]) + int(spinner.attrib["top"]) == int(label.attrib["text_y"]) + assert spinner.attrib["align"] == "center" + for arrow in ("header_bounds", "footer_bounds"): + top, left, bottom, right = map(int, spinner.attrib[arrow].split()) + assert 0 <= left < right <= int(spinner.attrib["width"]) + assert 0 <= top < bottom <= int(spinner.attrib["height"]) + assert spinner.find('on[@event="left_mouse"]').attrib["run"] == "mouse spinner 1wide click" + assert root.find(f"widget[@name='{sub}camera_policy_spinner']").attrib["strings"] == "PLAYER CHOICE|FORCED ON|FORCED OFF" + # Camera help adds three entries before map sharing and publisher help. + import re + menus = (ROOT / "port/linux/game/menu_functions.c").read_text() + stored = ET.parse(ROOT / "port/assets/menus/ce/main_menu.multiplayer_type_select.server_settings.xml").getroot() + for document in (root, stored): + help_text = [entry.attrib["text"] for entry in + document.find(f"strings[@name='{base}help_strings']")] + for name, phrase in (("MAP_SHARE_OPTIONS_HELP", "Custom Edition map"), + ("SERVER_LISTING_PUBLISHER_HELP", "publisher key")): + index = int(re.search(r"#define " + name + r" (\d+)", menus).group(1)) + assert phrase in help_text[index] + spec = port_settings.SCREENS["video_settings/fov_viewmodels"] + assert 1 + len(spec["rows"]) + len(spec["categories"]) == 10 + assert spec["extra_help"][0].startswith("CONTROLLED BY HOST") diff --git a/tools/test_camera_protocol.py b/tools/test_camera_protocol.py new file mode 100644 index 0000000000..6e8c8fa88e --- /dev/null +++ b/tools/test_camera_protocol.py @@ -0,0 +1,306 @@ +"""Exercise camera admission, including direct joins that bypass discovery.""" +from pathlib import Path +import re +import subprocess + +from harness import enum_with, function +from test_mcc_identity import compile_tool + +ROOT = Path(__file__).resolve().parents[1] + + +def test_camera_admission(tmp_path): + camera = (ROOT / "port/linux/game/third_person_protocol.c").read_text() + camera = "\n".join(line for line in camera.splitlines() if not line.startswith("#include")) + server = (ROOT / "source/networking/network_server_message_handler.c").read_text() + # Execute the real dispatcher's size and admission gates before message dispatch. + gate = function(server, "network_game_server_handle_client_message") + gate = gate[:gate.index("\tmessage_type =")] + gate += "(void)result;(void)message_type;(void)packet_type;return TRUE;\n}\n" + reset = function((ROOT / "source/networking/network_client_manager.c").read_text(), "network_game_client_reset") + open_game = function((ROOT / "source/networking/network_server_manager.c").read_text(), "network_game_server_open_game") + lobby = function((ROOT / "port/linux/game/menu_functions.c").read_text(), "lobby_join_reset") + limits = (ROOT / "port/linux/include/halo_port_limits.h").read_text() + version = re.search(r"^#define HALO_PORT_NETWORK_VERSION \d+$", limits, re.M).group() + code = r''' +#include +#include +#include "third_person_protocol.h" +typedef unsigned char byte; +typedef unsigned short word; +typedef int boolean; +#define TRUE 1 +#define FALSE 0 +#define CHECK(x) do {if(!(x)){fprintf(stderr,"line %d: %s\n",__LINE__,#x);return 1;}}while(0) +#define match_assert(...) ((void)0) +#define HALO_PORT_ADVERTISED_DISTRIBUTED_FLAG 1 +#define THIRD_PERSON_POLICY_MASK 48 +#define THIRD_PERSON_POLICY_SHIFT 4 +struct network_game {int machine_count;unsigned char cooperative_flags;}; +struct network_game_server {struct network_game game;int flags;void *connection;}; +static struct network_game_server *host; +static char const *mode="opence_crossplay"; +static int resets,sends; +char const *config_string(char const *name){(void)name;return mode;} +int config_write(char const *name,char const *value){(void)name;mode=value;return 1;} +static struct network_game_server *global_network_game_server_get(void){return host;} +struct network_game *network_game_server_get_game(struct network_game_server *s){return &s->game;} +boolean network_game_server_send_game_data_pregame(struct network_game_server *s){(void)s;sends++;return 1;} +static short third_person_host_policy(void){return 1;} +static void third_person_reset(void){resets++;} + +struct network_game_server_client_machine {int joined;}; +static int network_game_server_client_machine_is_joined_to_game(struct network_game_server *s, + struct network_game_server_client_machine *m) {(void)s;return m->joined;} +static void network_event(char const *fmt,...) {(void)fmt;} +#define NONE -1 +#define SET_FLAG(flags,bit,value) ((flags) = ((flags) & ~(1 << (bit))) | ((value) << (bit))) +#define csmemset memset +#define _network_game_server_game_open_bit 0 +static void network_server_allow_client_connections(void *c,int allow) {(void)c;(void)allow;} +static void halo_virtual_gamepads_start(void) {} +static struct {int adding,controller;} lobby_join; +enum {_network_game_client_state_searching, _network_game_client_connection_established_bit, + _network_game_client_join_request_sent_bit, _network_game_client_error_unknown, _network_game_client_error_none}; +struct network_game_client {struct network_game game;void *connection;int machine_index,state,flags,error, + join_in_progress,last_broadcast_search_time,next_update_number,connection_silent,seconds_to_game_start;}; +static int network_game_client_late_join_time,network_game_client_late_join_clock_pending, + network_game_client_start_pending,network_game_client_incompatibility_told,network_game_client_add_player_requested[4]; +static void network_game_invalidate(struct network_game *g){memset(g,0,sizeof(*g));} +static int network_connection_connected(void *c){(void)c;return 1;} +static int network_connection_active(void *c){(void)c;return 1;} +static int network_connection_disconnect(void *c){(void)c;return 1;} +static void network_game_client_set_error(struct network_game_client *c,int e){c->error=e;} + +''' + version + "\n" + (ROOT / "source/bungie_net/common/message_header.h").read_text().replace("#pragma once", "") + "\n" + enum_with( + (ROOT / "source/networking/network_messages.h").read_text(), + "_message_client_broadcast_game_search") + r''' +void build_message_header(word *out,word bytes,byte type,byte flags) {*out=(word)((bytes<<4)|(type<<2)|flags);} +''' + camera + "\n" + reset + "\n" + open_game + "\n" + lobby + "\n" + gate + r''' +int main(void) { + struct network_game_server server={0}; + struct network_game_client client={0}; + struct network_game_server_client_machine machine={0}; + word join[256]={0},outer[260],inner[260],size; + byte saved; + int i,bytes; + + CHECK(HALO_PORT_NETWORK_VERSION==43); + host=&server;third_person_session_host_begin();CHECK(!third_person_session_active()); + network_game_server_open_game(&server);CHECK(!third_person_session_locked()); + server.game.cooperative_flags=8; /* upstream vehicle riding survives camera policy changes */ + CHECK(third_person_session_set(1));CHECK(server.game.cooperative_flags==24); + CHECK(third_person_session_set(0));CHECK(server.game.cooperative_flags==8); + { + char const *maps[]={"maps\\bloodgulch","custom_maps\\test","mcc_maps\\test"}; + int family; + for(family=0;family<3;family++) { + CHECK(third_person_session_version(maps[family])==43); + CHECK(third_person_session_compatible(maps[family],43,1)); + CHECK(!third_person_session_compatible(maps[family],43,0)); + CHECK(third_person_session_compatible(maps[family],THIRD_PERSON_PROTOCOL_VERSION,1)); + CHECK(!third_person_session_compatible(maps[family],73,9)); + CHECK(!third_person_session_compatible(maps[family],32738,1)); + CHECK(!third_person_session_compatible(maps[family],32740,1)); + CHECK(!third_person_session_compatible(maps[family],32742,9)); + } + } + CHECK(third_person_session_set(1));CHECK(server.game.cooperative_flags==24); + CHECK(third_person_session_version("bloodgulch")==THIRD_PERSON_PROTOCOL_VERSION); + CHECK(third_person_session_version("mcc_maps\\test")==THIRD_PERSON_PROTOCOL_VERSION); + CHECK(lobby_join_reset());CHECK(!third_person_session_set(0)); + CHECK(!lobby_join.adding && lobby_join.controller==NONE); + CHECK(third_person_session_active() && third_person_session_locked()); + for(bytes=3;bytes<=512;bytes++) { + build_message_header(join,(word)bytes,_message_type_packet,0); + ((byte *)join)[bytes-1]=_message_client_join_game_request; + CHECK(third_person_protocol_join(join,(word)bytes,outer)==outer); + CHECK(third_person_protocol_unwrap(outer,(word)(bytes+8),inner,&size)); + CHECK(size==bytes && !memcmp(inner,join,bytes)); + CHECK(network_game_server_handle_client_message(&server,&machine,outer,(short)(bytes+8))); + /* Stock/main/old camera direct joins have no camera envelope. */ + CHECK(!network_game_server_handle_client_message(&server,&machine,join,(short)bytes)); + } + for(i=0;i<=521;i++) if(i!=520) CHECK(!third_person_protocol_unwrap(outer,(word)i,inner,&size)); + /* Old camera peers cannot bypass discovery by sending their envelope. */ + for(i=32720;i<=32725;i++) { + ((byte *)outer)[4]=(byte)i;((byte *)outer)[5]=(byte)(i>>8); + CHECK(!third_person_protocol_unwrap(outer,520,inner,&size)); + CHECK(!network_game_server_handle_client_message(&server,&machine,outer,520)); + } + ((byte *)outer)[4]=THIRD_PERSON_PROTOCOL_VERSION&255; + ((byte *)outer)[5]=THIRD_PERSON_PROTOCOL_VERSION>>8; + for(i=0;i<10;i++) { + saved=((byte *)outer)[i];((byte *)outer)[i]^=1; + CHECK(!third_person_protocol_unwrap(outer,520,inner,&size)); + CHECK(!network_game_server_handle_client_message(&server,&machine,outer,520)); + ((byte *)outer)[i]=saved; + } + ((byte *)outer)[519]=_message_client_game_start_request; + CHECK(!third_person_protocol_unwrap(outer,520,inner,&size)); + + /* Retired MCC and nested camera envelopes cannot pass as ordinary joins. */ + build_message_header(join,40,2,0);((byte *)join)[2]=101; + CHECK(!third_person_protocol_join(join,40,outer)); + ((byte *)join)[2]=THIRD_PERSON_PROTOCOL_JOIN_KIND; + CHECK(!third_person_protocol_join(join,40,outer)); + /* Established connections keep the ordinary dispatcher and its direction checks. */ + machine.joined=1;CHECK(network_game_server_handle_client_message(&server,&machine,join,40)); + machine.joined=0;CHECK(!network_game_server_handle_client_message(&server,&machine,join,40)); + third_person_session_host_end();host=NULL;CHECK(!third_person_session_active()); + third_person_session_client_begin(THIRD_PERSON_PROTOCOL_VERSION);CHECK(third_person_session_active()); + network_game_client_late_join_time=9;network_game_client_late_join_clock_pending=1; + network_game_client_start_pending=1;network_game_client_incompatibility_told=1; + network_game_client_reset(&client,0);CHECK(!third_person_session_active()); + CHECK(!network_game_client_late_join_time&&!network_game_client_late_join_clock_pending); + CHECK(!network_game_client_start_pending&&!network_game_client_incompatibility_told); + CHECK(resets>0&&sends>0); + third_person_session_client_begin(THIRD_PERSON_PROTOCOL_VERSION);client.connection=&client; + network_game_client_reset(&client,1);CHECK(!third_person_session_active()); + mode="gulchce_third_person";host=&server;third_person_session_host_begin(); + network_game_client_reset(&client,0);CHECK(third_person_session_active()); + third_person_session_host_end();host=NULL; + third_person_session_client_begin(41);CHECK(!third_person_session_active()); + third_person_session_client_begin(32716);CHECK(!third_person_session_active()); + third_person_session_client_begin(32717);CHECK(!third_person_session_active()); + third_person_session_client_begin(32720);CHECK(!third_person_session_active()); + third_person_session_client_begin(32721);CHECK(!third_person_session_active()); + third_person_session_client_begin(32724);CHECK(!third_person_session_active()); + third_person_session_client_begin(32725);CHECK(!third_person_session_active()); + third_person_session_client_begin(32734);CHECK(!third_person_session_active()); + third_person_session_client_begin(32736);CHECK(!third_person_session_active()); + third_person_session_client_begin(32737);CHECK(!third_person_session_active()); + build_message_header(join,3,_message_type_packet,0);((byte *)join)[2]=_message_client_join_game_request; + CHECK(network_game_server_handle_client_message(&server,&machine,join,3)); + third_person_session_client_begin(32708);CHECK(!third_person_session_active()); + CHECK(!third_person_session_set(1)); + return 0; +} +''' + path = tmp_path / "camera_admission.c" + path.write_text(code) + exe = compile_tool(tmp_path, [path]) + run = subprocess.run([str(exe)], capture_output=True, text=True) + assert run.returncode == 0, run.stdout + run.stderr + + +def test_camera_join_kind_is_reserved(): + import network_format + items = network_format.items() + kind = re.search(r"#define THIRD_PERSON_PROTOCOL_JOIN_KIND (\d+)", + (ROOT / "port/linux/game/third_person_protocol.h").read_text()).group(1) + assert kind not in [value for key, value in items.items() + if key.startswith("enum _distributed_message_")] + assert kind == "102" + + +def test_camera_and_crossplay_dispatch_admit_all_map_families(tmp_path): + """Run both envelopes through the complete dispatcher, not only its camera gate.""" + camera = (ROOT / "port/linux/game/third_person_protocol.c").read_text() + server = (ROOT / "source/networking/network_server_message_handler.c").read_text() + implementation = "\n".join(function(camera, name) for name in ( + "third_person_protocol_inner_valid", "third_person_protocol_join", + "third_person_protocol_unwrap")) + unrelated_handlers = ( + "client_add_player_request_ingame", "client_add_player_request_pregame", + "client_game_start_request", "client_graceful_game_exit_postgame", + "client_graceful_game_exit_pregame", "client_loaded", + "client_map_is_precached_pregame", "client_player_settings_request", + "client_remove_player_request_ingame", "client_remove_player_request_postgame", + "client_remove_player_request_pregame", "client_settings_request", + "client_switch_to_pregame", + ) + stubs = "\n".join( + f"#define network_game_server_handle_message_{name}(...) unexpected()" + for name in unrelated_handlers) + code = r''' +#include +#include +#include "third_person_protocol.h" +typedef unsigned char byte; +typedef unsigned short word; +typedef int boolean; +#define TRUE 1 +#define FALSE 0 +#define NUMBEROF(x) (sizeof(x)/sizeof((x)[0])) +#define HALO_PORT_MAXIMUM_NETWORK_MACHINES 4 +#define CHECK(x) do {if(!(x)){fprintf(stderr,"line %d: %s\n",__LINE__,#x);return 1;}}while(0) +#define match_assert(...) ((void)0) +#define MINIMUM_TRANSPORT_ERROR_MESSAGE_SIZE 4 +#define TRANSPORT_ERROR_MESSAGE_TEXT_LENGTH 1 +#define _network_game_server_state_ingame 1 +struct network_game {struct {char name[64];} map;}; +struct network_game_server {struct network_game game;}; +struct network_game_server_client_machine {int joined;}; +static int camera_active,join_calls,unexpected_calls; +static int unexpected(void) {unexpected_calls++;return FALSE;} +int third_person_session_active(void) {return camera_active;} +static int network_game_server_client_machine_is_joined_to_game(struct network_game_server *server, + struct network_game_server_client_machine *machine) {(void)server;return machine->joined;} +static void network_event(char const *format,...) {(void)format;} +#define network_game_server_client_machine_heard(...) ((void)unexpected()) +#define network_game_server_client_machine_is_loaded(...) unexpected() +#define network_game_server_get_client_machine(server,machine,index) (*(index)=0,unexpected()) +#define network_game_server_get_state(...) unexpected() +#define network_distributed_handle_stream_message(...) ((void)unexpected()) +#define network_voice_handles_message(...) unexpected() +#define network_voice_handle_message(...) ((void)unexpected()) +#define mcc_load_network_handles_message(...) unexpected() +#define mcc_load_network_handle_message(...) ((void)unexpected()) +#define mcc_admission_handles_message(...) unexpected() +#define mcc_admission_handle_message(...) ((void)unexpected()) +#define mcc_share_game_handles_message(...) unexpected() +#define mcc_share_game_handle_message(...) ((void)unexpected()) +#define map_share_handles_message(...) unexpected() +#define map_share_handle_message(...) ((void)unexpected()) +#define network_map_vote_handles_message(...) unexpected() +#define network_map_vote_handle_message(...) ((void)unexpected()) +#define transport_error_message_text(...) "unexpected transport error" +''' + stubs + "\n" + (ROOT / "source/bungie_net/common/message_header.h").read_text().replace( + "#pragma once", "") + "\n" + enum_with( + (ROOT / "source/networking/network_messages.h").read_text(), + "_message_client_broadcast_game_search") + "\n" + enum_with(server, "_message_type_error") + r''' +void build_message_header(word *out,word bytes,byte type,byte flags) {*out=(word)((bytes<<4)|(type<<2)|flags);} +''' + implementation + r''' +static boolean network_game_server_handle_message_client_join_game_request( + struct network_game_server *server,struct network_game_server_client_machine *machine, + word *message,short bytes) { + (void)server;(void)machine; + join_calls++; + if(bytes!=32 || GET_MESSAGE_TYPE(*message)!=_message_type_packet || + ((byte *)message)[bytes-1]!=_message_client_join_game_request)return FALSE; + return TRUE; +} +''' + function(server, "network_game_server_handle_client_message") + r''' +int main(void) { + struct network_game_server server; + struct network_game_server_client_machine machine={0}; + + word plain[16]={0},camera_join[THIRD_PERSON_PROTOCOL_JOIN_MAX/2]; + char const *maps[]={"maps\\bloodgulch","custom_maps\\test","mcc_maps\\test"}; + int family; + build_message_header(plain,sizeof(plain),_message_type_packet,0); + ((byte *)plain)[sizeof(plain)-1]=_message_client_join_game_request; + for(family=0;family<3;family++) { + strcpy(server.game.map.name,maps[family]); + camera_active=0;join_calls=unexpected_calls=0; + CHECK(network_game_server_handle_client_message(&server,&machine,plain,sizeof(plain))); + CHECK(join_calls==1 && !unexpected_calls); + camera_active=1;join_calls=0; + CHECK(!network_game_server_handle_client_message(&server,&machine,plain,sizeof(plain))); + CHECK(!join_calls); + CHECK(third_person_protocol_join(plain,sizeof(plain),camera_join)==camera_join); + CHECK(network_game_server_handle_client_message(&server,&machine,camera_join,sizeof(plain)+8)); + CHECK(join_calls==1 && !unexpected_calls); + ((byte *)camera_join)[4]^=1;join_calls=0; + CHECK(!network_game_server_handle_client_message(&server,&machine,camera_join,sizeof(plain)+8)); + CHECK(!join_calls); + } + return 0; +} +''' + source = tmp_path / "camera_mcc_admission.c" + source.write_text(code) + exe = compile_tool(tmp_path, [source]) + run = subprocess.run([str(exe)], capture_output=True, text=True) + assert run.returncode == 0, run.stdout + run.stderr diff --git a/tools/test_camera_wire.py b/tools/test_camera_wire.py new file mode 100644 index 0000000000..1a8cd2917c --- /dev/null +++ b/tools/test_camera_wire.py @@ -0,0 +1,59 @@ +"""Exercise the real shoulder input relay codec, including malformed packets.""" +from pathlib import Path +import shutil +import subprocess +import sys + +import pytest +from harness import function + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.mark.parametrize("camera", [0, 1]) +def test_shoulder_relay(tmp_path, camera): + compiler = shutil.which("clang") + if not compiler: + pytest.skip("clang required") + source = (ROOT / "port/linux/game/network_distributed.c").read_text() + start = source.index("struct distributed_relayed_action\n") + struct = source[start:source.index("\n};", start) + 3] + code = r''' +#include +#include +typedef unsigned char byte; +typedef unsigned short word; +#define DISTRIBUTED_INPUT_HISTORY 4 +static int camera_mode=CAMERA_MODE; +static int third_person_session_active(void){return camera_mode;} +#define TRUE 1 +#define TEST_FLAG(v,b) ((v)&(1u<<(b))) +#define SET_FLAG(v,b,x) ((v)=(x)?((v)|(1u<<(b))):((v)&~(1u<<(b)))) +#define csmemset memset +static byte *distributed_put(byte *p,void const *v,size_t n){memcpy(p,v,n);return p+n;} +static int distributed_take(byte const **p,byte const *end,void *v,size_t n){if((size_t)(end-*p) +typedef int boolean; +#define SHORT_MIN -32768 +#define SHORT_MAX 32767 +#define PIN(v,a,b) ((v)<(a)?(a):(v)>(b)?(b):(v)) +#define _custom_edition_behaviour_old_widescreen_fix 0 +static int ce=1,legacy=1; +static int custom_edition_cache_tags_loaded(void) {return ce;} +static int custom_edition_cache_relies_on(int flag) {return ce&&legacy;} +struct hud_placement_definition {struct {short x,y;}offset;}; +PRODUCTION +int main(void) { + struct hud_placement_definition p={{155,-210}}; + int state; + assert(!custom_edition_hud_warning(0)); /* Aim still follows FOV. */ + assert(!custom_edition_hud_warning(1)); /* Scope keeps its own path. */ + for(state=3;state<=15;state++) assert(custom_edition_hud_warning(state)); + custom_edition_hud_warning_placement(3,624,464,&p); + assert(p.offset.x==155 && p.offset.y==-210); + custom_edition_hud_warning_placement(7,724,408,&p); + assert(p.offset.x==205 && p.offset.y==-182); + p.offset.x=0;custom_edition_hud_warning_placement(3,724,408,&p);assert(!p.offset.x); + p.offset.x=-155;custom_edition_hud_warning_placement(3,724,408,&p);assert(p.offset.x==-205); + p.offset.x=155;legacy=0;custom_edition_hud_warning_placement(3,724,408,&p);assert(p.offset.x==155); + ce=0;legacy=1;custom_edition_hud_warning_placement(3,724,408,&p); + assert(p.offset.x==155 && !custom_edition_hud_warning(3)); + return 0; +} +'''.replace('PRODUCTION', body)) + + +def test_shared_meter_channels_do_not_leak_or_convert_redraws(tmp_path): + source = (ROOT / 'port/linux/src/xbox_textures.c').read_text() + body = '\n'.join(function(source, n) for n in ['halo_custom_edition_hud_meter', 'texture_entry_result', 'halo_custom_edition_texels_forget']) + run_c(tmp_path, r''' +#include +#include +#include +typedef unsigned int GLuint,GLenum; +#define TRUE 1 +#define GL_TEXTURE_2D 2 +#define _texel_p8 1 +#define _custom_edition_channels_xbox 0 +static int custom_edition_hud_meter_active,order,enabled; +static void *custom_edition_texels; +static unsigned long custom_edition_texel_count,custom_edition_texel_capacity; +struct xgpu_texture_description {unsigned long levels,width,height;int compressed,format,hires,hires_coverage,hires_point_threshold,ce_meter_channels;}; +struct texture_entry {GLuint target,texture;unsigned long data,address,size,hud_upscale_levels;int override,hud_upscale_checked;GLuint hud_upscale;struct xgpu_texture_description description;}; +#define text_hires_atlas_texture(a) 0 +#define menu_art_texture(a,b) 0 +#define hud_hires_placeholder_texture(a,b) 0 +#define hud_hires_override_texture(a,b) 99 +#define hud_hires_override_coverage(a) 1 +#define hud_hires_override_point_threshold(a) 1 +#define config_boolean(a) enabled +#define high_res_hud() enabled +#define hud_hires_upscale_at(a,b,c) 0 +static struct {int kind;} info; +#define format_information(f) info +#define custom_edition_texels_order(a) order +#define platform_is_contiguous(a) 1 +#define decode_level(a,b,c,d,e) 0 +#define hud_hires_upscale_texture(a,b,c,d,e) 0 +PRODUCTION +int main(void) { + struct texture_entry entry={0};struct xgpu_texture_description result;GLenum target; + entry.override=-1;entry.texture=7; + halo_custom_edition_hud_meter(1); + assert(texture_entry_result(&entry,&target,&result)==7 && result.ce_meter_channels); + halo_custom_edition_hud_meter(0); + assert(texture_entry_result(&entry,&target,&result)==7 && !result.ce_meter_channels); + halo_custom_edition_hud_meter(1);order=2; /* Already converted meter. */ + texture_entry_result(&entry,&target,&result);assert(!result.ce_meter_channels); + order=3; /* Explicit Xbox-order custom meter artwork. */ + texture_entry_result(&entry,&target,&result);assert(!result.ce_meter_channels); + order=0;entry.override=0; /* Stock CE high-resolution meter has Xbox channels. */ + assert(texture_entry_result(&entry,&target,&result)==99 && !result.ce_meter_channels); + entry.override=-1;enabled=1; + texture_entry_result(&entry,&target,&result);assert(result.ce_meter_channels); + halo_custom_edition_texels_forget(); + texture_entry_result(&entry,&target,&result);assert(!result.ce_meter_channels); + return 0; +} +'''.replace('PRODUCTION', body)) + + +def test_meter_scope_and_shader_are_ce_only(): + source = function((ROOT / 'source/interface/hud_draw.c').read_text(), 'hud_draw_bitmap_internal') + begin = source.index('halo_custom_edition_hud_meter(meter_parameters && custom_edition_cache_tags_loaded())') + draw = source.index('rasterizer_psuedo_dynamic_screen_quad_draw(') + end = source.index('halo_custom_edition_hud_meter(FALSE)') + assert begin < draw < end + shader = (ROOT / 'port/linux/src/nv2a_psh.c').read_text() + assert 'if (stage == 0 && key->ce_meter_channels)' in shader + assert 't0 = t0.aaar;' in shader + texture = function((ROOT / 'port/linux/src/xbox_textures.c').read_text(), 'xgpu_texture_get') + assert texture.index('xgpu_mcc_texture_get(') < texture.index('texture_entry_result(') + + +def test_authored_xbox_ammo_sheet_keeps_identity_through_static_use(tmp_path): + source = (ROOT / 'port/linux/game/custom_edition_bitmaps.c').read_text() + body = '\n'.join(function(source, n) for n in [ + 'reordered_bitmap_index', 'reordered_bitmap_mark', 'meter_bitmaps_mark', + 'custom_edition_bitmaps_dispose']) + run_c(tmp_path, r''' +#include +#include +#include +typedef int boolean; +typedef unsigned char byte; +#define TRUE 1 +#define FALSE 0 +#define NONE -1 +#define _error_silent 0 +#define error(a,b,c) ((void)0) +#define DATUM_INDEX_TO_ABSOLUTE_INDEX(i) ((i)&65535) +#define _custom_edition_channels_hud_meter 2 +#define _custom_edition_channels_hud_meter_xbox 3 +#define _custom_edition_behaviour_xbox_ammo_meter_channels 12 +struct reordered_bitmap {long handle;short bitmap_index;byte channel_order;int drawn_otherwise;}; +struct custom_edition_bitmaps_globals {struct reordered_bitmap *reordered_bitmaps; + unsigned long behaviours;long reordered_bitmap_count,reordered_bitmap_capacity;}; +static struct custom_edition_bitmaps_globals custom_edition_bitmaps_globals; +struct tag_view {int unused;}; +struct meter_hud_element_definition {struct {long index;}meter_bitmap;short sequence_index;}; +static const char *name; +static const char *view_tag_name(const struct tag_view *v,long i) {return name;} +static int forgotten; +static void halo_custom_edition_texels_forget(void) {forgotten++;} +static boolean reordered_bitmaps_mark(const struct tag_view *,long,short,short); +PRODUCTION +static boolean reordered_bitmaps_mark(const struct tag_view *v,long h,short s,short o) { + return reordered_bitmap_mark(h,s,o); +} +int main(void) { + struct tag_view view={0};struct meter_hud_element_definition meter={{100},1}; + struct custom_edition_bitmaps_globals *g=&custom_edition_bitmaps_globals; + name="bourrin\\hud\\v3\\bitmaps\\all icons wips"; + assert(meter_bitmaps_mark(&view,&meter)); + assert(g->reordered_bitmaps[0].channel_order==2); /* Legacy CE. */ + g->reordered_bitmap_count=0;g->behaviours=1UL<<12; + assert(meter_bitmaps_mark(&view,&meter)); + assert(g->reordered_bitmaps[0].channel_order==3); + reordered_bitmap_mark(100,1,NONE); /* Same sheet's static weapon icon. */ + assert(!g->reordered_bitmaps[0].drawn_otherwise); + name="other custom meter";meter.meter_bitmap.index=101; + assert(meter_bitmaps_mark(&view,&meter)); + assert(g->reordered_bitmaps[1].channel_order==2); + reordered_bitmap_mark(101,1,NONE); + assert(g->reordered_bitmaps[1].drawn_otherwise); + custom_edition_bitmaps_dispose(); + assert(!g->behaviours && !g->reordered_bitmap_count && !g->reordered_bitmaps && forgotten==1); + name="bourrin\\hud\\v3\\bitmaps\\all icons wips"; + assert(meter_bitmaps_mark(&view,&meter)); /* Next map has no exception. */ + assert(g->reordered_bitmaps[0].channel_order==2); + custom_edition_bitmaps_dispose(); + return 0; +} +'''.replace('PRODUCTION', body)) diff --git a/tools/test_ce_hud_buttons.py b/tools/test_ce_hud_buttons.py new file mode 100644 index 0000000000..edf0686935 --- /dev/null +++ b/tools/test_ce_hud_buttons.py @@ -0,0 +1,108 @@ +"""Exercise the production low-resolution CE controller resource reader.""" +from pathlib import Path +from test_hud_button_style import run_c + +ROOT = Path(__file__).resolve().parents[1] + + +def test_original_sprites_bounds_animation_and_cleanup(tmp_path): + source = (ROOT / 'port/linux/game/custom_edition_hud_buttons.h').read_text() + source = '\n'.join(line for line in source.splitlines() if not line.startswith('#include')) + run_c(tmp_path, r''' +#include +#include +#include +#include +typedef int boolean;typedef unsigned char byte;typedef float real;typedef uint32_t pixel32; +typedef struct {short x,y;}point2d; +typedef struct {short x0,y0,x1,y1;}rectangle2d; +typedef struct {float x0,x1,y0,y1;}real_rectangle2d; +struct bitmap_group_sprite {short bitmap_index,pad;uint32_t unused;real_rectangle2d bounds;float x,y;}; +struct bitmap_data {void *base_address;short width,height;}; +struct icon_hud_element_definition {short sequence_index,frame_rate,width_offset;point2d offset;int flags;pixel32 color;}; +struct cache_file_source {void *context;int (*read)(void *,uint32_t,uint32_t,void *);uint32_t size;}; +struct resource_map_item {uint32_t data_offset,size;char const *name;}; +struct resource_map {struct cache_file_source *source;int item_count;struct resource_map_item *items;}; +#define TRUE 1 +#define FALSE 0 +#define csmemset memset +#define csmemcpy memcpy +#define _hud_anchor_bottom_left 2 +static byte file[1024+65536];static int live,reads,draws,available=1,fail,players=1; +static long ticks;static float drawn_x,drawn_height,drawn_width;static pixel32 drawn_color; +static point2d drawn_point; +static int read_bytes(void *ctx,uint32_t off,uint32_t size,void *dst) { + reads++;if(fail || off>sizeof(file) || size>sizeof(file)-off)return 0; + memcpy(dst,file+off,size);return 1; +} +static struct cache_file_source src={0,read_bytes,sizeof(file)}; +static struct resource_map_item item={0,512,"ui\\hud\\bitmaps\\hud_msg_icons_sm"}; +static struct resource_map resource={&src,1,&item}; +static struct resource_map const *custom_edition_cache_bitmap_resources(void){return available?&resource:0;} +static long game_time_get(void){return ticks;} +static int local_player_count(void){return players;} +static int draw_unicode_string_capital_middle(rectangle2d const *r,void const *s){return 80;} +static struct bitmap_data *bitmap_2d_new(int w,int h,int m,int f){ + struct bitmap_data *b=calloc(1,sizeof(*b));assert(w==128&&h==128&&!m&&f==11); + b->width=w;b->height=h;b->base_address=malloc(65536);live++;return b; +} +static void bitmap_delete(struct bitmap_data *b){free(b->base_address);free(b);live--;} +static int rasterizer_bitmap_new(struct bitmap_data *b){return 1;} +static void rasterizer_bitmap_changed(struct bitmap_data *b){assert(((byte *)b->base_address)[0]==73);} +static void hud_draw_bitmap_direct(struct bitmap_data *b,int anchor,point2d *point, + real_rectangle2d *clip,float scale,float angle,pixel32 color,int crosshair){ + assert(anchor==2 && !crosshair);drawn_x=clip->x0;drawn_color=color;draws++; + drawn_point=*point;drawn_height=(clip->y1-clip->y0)*128*scale; + drawn_width=(clip->x1-clip->x0)*128*scale; +} +PRODUCTION +static void put(unsigned off,uint32_t n){memcpy(file+off,&n,4);} +static void fixture(void){ + struct bitmap_group_sprite s={0}; + memset(file,0,sizeof(file));put(84,1);put(88,108);put(96,1);put(100,256); + put(108+52,2);put(108+56,172); + s.bounds.x1=16.0f/128;s.bounds.y1=20.0f/128;memcpy(file+172,&s,32); + s.bounds.x0=0.25f;s.bounds.x1=0.375f;memcpy(file+204,&s,32); + put(260,0x00800080);put(264,1);put(268,11);put(280,1024);put(284,65536); + file[1024]=73; +} +int main(void){ + struct icon_hud_element_definition icon={0,10,-6,{-2,-5},2,0xabcdef01}; + rectangle2d cursor={100,0,0,100};int n; + fixture();assert(ce_hud_button_draw(&icon,&cursor,0)); + assert(live==1 && drawn_x==0 && drawn_color==icon.color && cursor.x0==121); + assert(drawn_point.x==104 && drawn_point.y==93 && drawn_height==26.0f); + assert(drawn_width>20.7f && drawn_width<20.9f); + n=reads;ticks=10;assert(ce_hud_button_draw(&icon,&cursor,0));assert(drawn_x==0.25f && reads==n); + ticks=20;assert(ce_hud_button_draw(&icon,&cursor,0));assert(drawn_x==0); + available=0;assert(!ce_hud_button_draw(&icon,&cursor,0));available=1; + icon.sequence_index=-1;assert(!ce_hud_button_draw(&icon,&cursor,0));icon.sequence_index=1; + assert(!ce_hud_button_draw(&icon,&cursor,0));icon.sequence_index=0; + ce_hud_buttons_forget();assert(!live);ce_hud_buttons_forget(); + put(88,0xfffffff0);assert(!ce_hud_button_draw(&icon,&cursor,0));ce_hud_buttons_forget(); + fixture();put(108+52,0xffffffff);assert(!ce_hud_button_draw(&icon,&cursor,0));ce_hud_buttons_forget(); + fixture();put(172+8,0x7fc00000);ticks=0;assert(!ce_hud_button_draw(&icon,&cursor,0));ce_hud_buttons_forget(); + fixture();put(280,sizeof(file)-1);assert(!ce_hud_button_draw(&icon,&cursor,0));ce_hud_buttons_forget(); + fixture();put(268,14);assert(!ce_hud_button_draw(&icon,&cursor,0));ce_hud_buttons_forget(); + fixture();fail=1;assert(!ce_hud_button_draw(&icon,&cursor,0));ce_hud_buttons_forget();fail=0; + fixture();players=2;icon.flags=0;assert(ce_hud_button_draw(&icon,&cursor,0x11223344)); + assert(drawn_height>19.4f && drawn_height<19.6f && drawn_point.y==89); + assert(drawn_color==0x11223344);ce_hud_buttons_forget();assert(!live); + /* Narrow buttons and wide trigger/stick cells retain their aspect ratio + and stay centered, instead of all being forced into a face-sized box. */ + { + int sizes[][2]={{13,15},{68,20},{75,20},{65,20},{71,20},{4,4}};int i; + for(i=0;i<6;i++){ + struct bitmap_group_sprite s={0}; + fixture();s.bounds.x1=sizes[i][0]/128.0f;s.bounds.y1=sizes[i][1]/128.0f; + memcpy(file+172,&s,32);ticks=0;players=1;cursor.x0=100; + assert(ce_hud_button_draw(&icon,&cursor,0)); + assert(drawn_point.x==104 && drawn_point.y-drawn_height*0.5f<=80.0f); + assert(drawn_point.y-drawn_height*0.5f>79.0f); + assert(cursor.x0>=drawn_point.x+drawn_width-4.0f); + ce_hud_buttons_forget(); + } + } + return 0; +} +'''.replace('PRODUCTION', source)) diff --git a/tools/test_ce_hud_hires.py b/tools/test_ce_hud_hires.py new file mode 100644 index 0000000000..502b752e20 --- /dev/null +++ b/tools/test_ce_hud_hires.py @@ -0,0 +1,258 @@ +"""CE HUD registration and pixel identity regression checks.""" +from pathlib import Path +import copy +import json +import struct +import zlib + +import pytest +from harness import function +from test_hud_button_style import run_c +from ce_hud_signatures import fingerprint, region +from ce_hud_assets import build_asset +from PIL import Image + +ROOT = Path(__file__).resolve().parents[1] + + +def test_stock_fallback_checks_pixels_and_bounds(tmp_path): + body = function((ROOT / 'port/linux/src/hud_hires.c').read_text(), 'hud_hires_ce_stock_matches') + run_c(tmp_path, r''' +#include +typedef unsigned char Bytef; +typedef unsigned int uInt; +static struct hud_hires_ce_stock {char const *tag;int bitmap;unsigned int width,height,size,crc;} + hud_hires_ce_stock[]={{"stock",0,4,4,16,7}}; +static unsigned int hud_hires_ce_stock_count=1; +static unsigned long crc32(unsigned long c,Bytef const *p,uInt n) {return p[0];} +PRODUCTION +int main(void) { + unsigned char pixels[16]={7}; + unsigned long address=(unsigned long)pixels; + assert(hud_hires_ce_stock_matches(0,address,4,4,16)); + pixels[0]=8; + assert(!hud_hires_ce_stock_matches(0,address,4,4,16)); + assert(!hud_hires_ce_stock_matches(-1,address,4,4,16)); + assert(!hud_hires_ce_stock_matches(1,address,4,4,16)); + assert(!hud_hires_ce_stock_matches(0,0,4,4,16)); + pixels[0]=7; + assert(!hud_hires_ce_stock_matches(0,address,8,4,16)); + assert(!hud_hires_ce_stock_matches(0,address,4,8,16)); + assert(!hud_hires_ce_stock_matches(0,address,4,4,8)); + return 0; +} +'''.replace('PRODUCTION', body)) + + +def test_ce_registers_before_mods_and_mcc_stays_separate(): + source = function((ROOT / 'source/cache/cache_files.c').read_text(), 'scenario_tags_load') + ce = source[source.index('if (custom_edition_level_name(scenario_name))'):] + ce = ce[:ce.index('if (cache_file_open')] + assert ce.index('global_tag_instances =') < ce.index('hud_hires_tags_loaded(') + assert ce.index('hud_hires_tags_loaded(') < ce.index('mods_tags_loaded(') + mcc = source[source.index('if (mcc_level_name(scenario_name))'):source.index('if (custom_edition_level_name(scenario_name))')] + assert 'hud_hires_tags_loaded(' not in mcc + unload = function((ROOT / 'source/cache/cache_files.c').read_text(), 'scenario_tags_unload') + assert 'hud_hires_tags_unloaded();' in unload + + +def test_override_identity_and_setting(tmp_path): + body = function((ROOT / 'port/linux/src/hud_hires.c').read_text(), 'hud_hires_override_find') + run_c(tmp_path, r''' +#include +#include +typedef unsigned char Bytef; +typedef unsigned int uInt; +static struct hud_hires_embedded { int title; unsigned long ce_width,ce_height,ce_size,ce_crc,crc; + char *tag; int bitmap; } hud_hires_embedded[] = {{0,4,4,16,7,9,"test",0}}; +static struct {int other_pixels_logged;} textures[1]; +static unsigned long generation; +static int enabled=1, ce=1, active=1; +static unsigned long config_changes(void) {return generation;} +static int config_boolean(char const *s) {return enabled;} +static long hud_hires_asset_at(unsigned long a,long w,long h) {return active ? 0 : -1;} +static long hud_hires_asset_count(void) {return 1;} +static int hud_hires_asset_stock_custom_edition(unsigned long a,long w,long h,long i) {return ce;} +/* Control the CRC provider independently of the production decision. */ +static unsigned long crc32(unsigned long c,Bytef const *p,uInt n) {return p[0];} +#define platform_log(...) ((void)0) +PRODUCTION +int main(void) { + unsigned char pixels[16]={7}; + unsigned long address=(unsigned long)pixels; + assert(hud_hires_override_find(address,4,4,16)==0); + enabled=0; generation++; + assert(hud_hires_override_find(address,4,4,16)==-1); + enabled=1; generation++; + assert(hud_hires_override_find(address,4,4,16)==0); + pixels[0]=8; + assert(hud_hires_override_find(address,4,4,16)==-1); + pixels[0]=7; + assert(hud_hires_override_find(address,8,4,16)==-1); + assert(hud_hires_override_find(address,4,8,16)==-1); + assert(hud_hires_override_find(address,4,4,8)==-1); + active=0; /* unload / MCC without registration */ + assert(hud_hires_override_find(address,4,4,16)==-1); + active=1; ce=0; pixels[0]=9; /* existing Xbox CRC path */ + assert(hud_hires_override_find(address,4,4,16)==0); + pixels[0]=7; + assert(hud_hires_override_find(address,4,4,16)==-1); + return 0; +} +'''.replace('PRODUCTION', body)) + + +def test_fingerprint_hardware_order_and_bounds(): + item = bytearray(0x6c + 48) + struct.pack_into(' +#include +#define MAXIMUM_HIRES_BITMAPS 128 +#define MAXIMUM_HIRES_SPRITE_BITMAPS 8 +#define NUMBEROF(a) (sizeof(a)/sizeof((a)[0])) +#define NONE -1 +#define BITMAP_GROUP_TAG 1 +#define _scenario_type_main_menu 2 +#define csmemset memset +#define platform_log(...) ((void)0) +typedef int boolean; +struct bitmap_data {short width,height;}; +static struct bitmap_data bitmap={128,32}; +static struct {int type;} scenario; +static int ce=1,resource=1,compatible=1,ce_only=0; +static long hud_hires_asset_count(void) {return 1;} +static char const *hud_hires_asset_tag(long a) {return "stock";} +static long hud_hires_asset_bitmap(long a) {return 0;} +static long tag_loaded(long group,char const *name) {return 1;} +static struct bitmap_data *bitmap_group_try_and_get_bitmap(long group,short index) {return &bitmap;} +static int custom_edition_cache_tags_loaded(void) {return ce;} +static int custom_edition_cache_stock_tag(long group) {return resource;} +static int hud_hires_asset_custom_edition(long asset) {return compatible;} +static int hud_hires_asset_ce_only(long asset) {return ce_only;} +static long hud_hires_ce_stock_count_get(void) {return 1;} +static char const *hud_hires_ce_stock_tag(long index) {return "stock";} +static long hud_hires_ce_stock_bitmap(long index) {return 0;} +static int hud_hires_asset_fits(long a,long w,long h) {return 1;} +static unsigned long hud_hires_asset_sprites(long a) {return 0;} +#define scenario_definition_get(i) (&scenario) +static void hud_hires_map_loaded(long const *a,long count) {} +GLOBALS +static void hud_hires_sprite_bitmaps_forget(void) {hires_sprite_bitmap_count=0;} +PRODUCTION +int main(void) { + hud_hires_tags_loaded(0); + assert(hires_bitmap_count==1 && hires_bitmaps[0].stock_custom_edition); + assert(upscale_bitmap_count==0); + assert(ce_stock_bitmap_count==1); + resource=0; /* Embedded custom art under a stock name. */ + hud_hires_tags_loaded(0); + assert(hires_bitmap_count==0 && upscale_bitmap_count==0); + assert(ce_stock_bitmap_count==0); + resource=1; compatible=0; /* Resource sheet with incompatible layout. */ + hud_hires_tags_loaded(0); + assert(hires_bitmap_count==0); + ce=0; resource=0; /* Xbox registration remains independent of CE eligibility. */ + hud_hires_tags_loaded(0); + assert(hires_bitmap_count==1 && !hires_bitmaps[0].stock_custom_edition); + assert(upscale_bitmap_count>0); + assert(ce_stock_bitmap_count==0); + ce_only=1; + hud_hires_tags_loaded(0); + assert(hires_bitmap_count==0); + ce_only=0; + ce=1; resource=1; compatible=1; + hud_hires_tags_loaded(0); + assert(hires_bitmap_count==1 && upscale_bitmap_count==0); + return 0; +} +'''.replace('GLOBALS', globals_).replace('PRODUCTION', body)) + + +def test_ce_meter_recipe_retains_thresholds_and_is_reproducible(): + assets = ROOT / 'port/assets/hud' + entries = json.loads((assets / 'ce_layout.json').read_text())['assets'] + entries = [entry for entry in entries if entry.get('coverage')] + assert {entry['name'] for entry in entries} == {'ce_hud_unit_meters', 'ce_hud_ammo_meters'} + for entry in entries: + generated = build_asset(entry) + with Image.open(assets / (entry['name'] + '.png')) as committed: + assert generated.tobytes() == committed.tobytes() + for cell in entry['cells']: + with Image.open(assets / (cell['source'] + '.png')) as original: + source = original.crop(cell['from']) + rect = [round(v * entry['scale']) for v in cell['to']] + result = generated.crop(rect) + expected = source.getchannel('R').resize(result.size, Image.Resampling.NEAREST) + assert result.getchannel('R').tobytes() == expected.tobytes() + malformed = copy.deepcopy(entry) + malformed['cells'][0]['to'][2] = entry['width'] + 1 + with pytest.raises(ValueError): + build_asset(malformed) + + +def test_full_size_unit_meters_preserve_screen_coordinates(): + entry = json.loads((ROOT / 'port/assets/hud/ce_layout.json').read_text())['assets'][0] + # Full-size meters are top-right anchored. CE uses twice the resolution + # with half the placement scale. Different sprite padding must translate + # the artwork, never stretch it to the stock pixel bounding box. + for index, xbox_right, xbox_top, ce_right, ce_top in ( + (0, 122, 34, 262, 132), (2, 176, 65, 258, 198)): + cell = entry['cells'][index] + for edge in (0, 2): + assert cell['from'][edge] / 8 - xbox_right == cell['to'][edge] / 2 - ce_right / 2 + for edge in (1, 3): + assert cell['from'][edge] / 8 - xbox_top == cell['to'][edge] / 2 - ce_top / 2 + + +def test_ce_prompt_guard_preserves_authored_offsets(tmp_path): + source = (ROOT / 'port/linux/game/hud_hires_tags.c').read_text() + body = function(source, 'ce_hud_buttons_stock') + run_c(tmp_path, r''' +#include +#include +#define TRUE 1 +#define FALSE 0 +#define NONE -1 +#define NUMBEROF(a) (sizeof(a)/sizeof(a[0])) +typedef int boolean; +struct icon_hud_element_definition {short sequence_index,width_offset; + struct {short x,y;} offset; unsigned long color;char frame_rate;unsigned char flags;short text_index;}; +static int ce=1; +static int custom_edition_cache_tags_loaded(void) {return ce;} +PRODUCTION +int main(void) { + struct icon_hud_element_definition icon={0,-6,{-2,-5},0,0,2,0}; + assert(ce_hud_buttons_stock(&icon,0)); + icon.offset.x++; + assert(!ce_hud_buttons_stock(&icon,0)); + icon.offset.x--; icon.sequence_index=5; + assert(!ce_hud_buttons_stock(&icon,0)); + icon.sequence_index=0; icon.text_index=99; + assert(!ce_hud_buttons_stock(&icon,0)); + icon.text_index=0; + assert(ce_hud_buttons_stock(&icon,0)); + assert(!ce_hud_buttons_stock(&icon,-1)); + assert(!ce_hud_buttons_stock(&icon,18)); + ce=0; + assert(ce_hud_buttons_stock(&icon,0)); + return 0; +} +'''.replace('PRODUCTION', body)) diff --git a/tools/test_ce_hud_scaling.py b/tools/test_ce_hud_scaling.py new file mode 100644 index 0000000000..a3c39ce76b --- /dev/null +++ b/tools/test_ce_hud_scaling.py @@ -0,0 +1,161 @@ +"""Authored CE HD scaling, separate from Xbox redraws and MCC's canvas.""" +from pathlib import Path +from harness import function +from test_hud_button_style import run_c + +ROOT = Path(__file__).resolve().parents[1] + + +def test_draw_flags_and_known_map_numbers_stay_in_ce(tmp_path): + source = (ROOT / 'port/linux/game/custom_edition_hud_draw.c').read_text() + body = '\n'.join(function(source, name) for name in [ + 'custom_edition_hud_bitmap_scale', 'custom_edition_hud_number_scale']) + flags = (ROOT / 'port/linux/game/custom_edition_hud_scale.h').read_text() + run_c(tmp_path, r''' +#include +typedef float real; +typedef int boolean; +#define FALSE 0 +#define NONE -1 +#define _custom_edition_behaviour_hud_number_scale 7 +static int ce, legacy, reads; +static struct {unsigned short flags;} bitmap; +static int custom_edition_cache_tags_loaded(void) {return ce;} +static int custom_edition_cache_relies_on(int flag) {assert(flag==7);return legacy;} +#define bitmap_group_get(index) (reads++, &bitmap) +''' + flags + body + r''' +int main(void) { + int p,b; + const unsigned short bits[4]={0,0x10,0x80,0x90}; + const float expected[2][4]={{1,.5f,.5f,.25f},{.5f,.25f,.5f,.25f}}; + ce=1; + for(p=0;p<2;p++) for(b=0;b<4;b++) { + bitmap.flags=bits[b]; + assert(custom_edition_hud_number_scale(1,p*4)==expected[p][b]); + assert(custom_edition_hud_bitmap_scale(1)==expected[0][b]); + } + /* Bigass-style metric correction already supplies the halving. */ + legacy=1;bitmap.flags=0x10; + assert(custom_edition_hud_number_scale(1,4)==.5f); + assert(custom_edition_hud_number_scale(1,0)==.5f); + /* Xbox, MCC, unload/failed loads: never look up a CE bitmap. */ + ce=0;reads=0; + assert(custom_edition_hud_number_scale(1,4)==1); + assert(custom_edition_hud_bitmap_scale(1)==1); + ce=1; + assert(custom_edition_hud_number_scale(NONE,4)==1); + assert(custom_edition_hud_bitmap_scale(NONE)==1); + assert(reads==0); + legacy=0;bitmap.flags=0; + assert(custom_edition_hud_number_scale(1,0)==1); + return 0; +} +''') + + +def test_mask_transform_scope_and_map_transitions(tmp_path): + source = (ROOT / 'port/linux/game/custom_edition_hud_draw.c').read_text() + body = source[source.index('static struct bitmap_data const *hud_mask;'):] + run_c(tmp_path, r''' +#include +#include +typedef float real; +typedef struct {float i,j;} real_vector2d; +struct bitmap_data {long tag_index;unsigned short flags;}; +#define TEST_FLAG(v,b) ((v)&(1u<<(b))) +#define _bitmap_linear_bit 4 +static int ce=1; +static float factor=.25f; +static int custom_edition_cache_tags_loaded(void) {return ce;} +static float custom_edition_hud_bitmap_scale(long index) {assert(index==7);return factor;} +''' + body + r''' +static void check(struct bitmap_data *bitmap,float width,float height,float x,float y) { + real_vector2d size={512,256},scale={1,1}; + custom_edition_hud_mask_transform(bitmap,&size,&scale); + assert(size.i==width && size.j==height && scale.i==x && scale.j==y); +} +int main(void) { + struct bitmap_data mask={7,16},other={7,16}; + check(&mask,512,256,1,1); + custom_edition_hud_mask_begin(&mask); + check(&mask,128,64,4,4); /* Linear textures use pixel coordinates. */ + check(&other,512,256,1,1); /* Viewport fallback, other effects. */ + mask.flags=0;check(&mask,128,64,1.f/128,1.f/64); + custom_edition_hud_mask_end();check(&mask,512,256,1,1); + custom_edition_hud_mask_begin(NULL);check(&mask,512,256,1,1); + ce=0;custom_edition_hud_mask_begin(&mask);check(&mask,512,256,1,1); + custom_edition_hud_mask_end(); + ce=1;factor=.5f;mask.flags=16; + custom_edition_hud_mask_begin(&mask);check(&mask,256,128,2,2); + ce=0;check(&mask,512,256,1,1); /* Failed/unloaded CE guard. */ + custom_edition_hud_mask_end(); + ce=1;check(&mask,512,256,1,1); /* Reused bitmap address in next map. */ + return 0; +} +''') + + +def test_mask_draw_is_bracketed_and_mcc_number_path_is_preserved(): + draw = function((ROOT / 'source/interface/interface.c').read_text(), 'interface_draw_screen') + assert draw.index('custom_edition_hud_mask_begin(') < draw.index('rasterizer_screen_effect(¶meters)') + assert draw.index('rasterizer_screen_effect(¶meters)') < draw.index('custom_edition_hud_mask_end()') + numbers = function((ROOT / 'source/interface/hud_draw.c').read_text(), 'hud_draw_numbers') + assert 'if (custom_edition_cache_tags_loaded())' in numbers + assert 'digit_scale *= mcc_hud_canvas_scale()' in numbers + + +def test_pickup_icon_draw_and_cursor_keep_authored_offsets(tmp_path): + source = (ROOT / 'source/interface/hud_messaging.c').read_text() + body = function(source, 'render_state_bitmap') + run_c(tmp_path, r''' +#include +#include +typedef float real; +typedef unsigned int pixel32; +typedef struct {short x,y;} point2d; +typedef struct {short x0,y0,x1,y1;} rectangle2d; +typedef struct {float x0,y0,x1,y1;} real_rectangle2d; +struct bitmap_data {short width;}; +struct icon_hud_element_definition {short frame_rate,sequence_index;point2d offset;unsigned short flags;pixel32 color;short width_offset;}; +static struct {struct {struct {long index;} messaging_icons;} messaging;} globals={{{7}}},*hud_globals=&globals; +#define FALSE 0 +#define TRUE 1 +#define TEST_FLAG(v,b) ((v)&(1u<<(b))) +#define _hud_icon_use_color_bit 0 +#define _hud_icon_absolute_width_bit 1 +#define _hud_corner_bottom_left 0 +static int mcc,button,owned,players=1,draws,reads,clipped; +static float drawn_scale,factor=.25f; +static point2d drawn_point; +static struct bitmap_data image={128}; +static real_rectangle2d region={.25f,0,.75f,1}; +static int mcc_cache_tags_loaded(void) {return mcc;} +static int hud_hires_button_draw(const struct icon_hud_element_definition *i,rectangle2d *b,pixel32 c) {return button;} +static int game_time_get(void) {return 0;} +static void hud_retrieve_bitmap_and_bounding_rect(long i,long s,long f,const struct bitmap_data **b,const real_rectangle2d **c) {*b=ℑ*c=clipped?®ion:NULL;} +static int _texture_cache_bitmap_get_hardware_format(struct bitmap_data *b,int a,int c) {return 1;} +static int mcc_hud_icon_draw(long i,const struct bitmap_data *b,const real_rectangle2d *c,rectangle2d *r,pixel32 p,const struct icon_hud_element_definition *icon,int f) {return owned;} +static const struct bitmap_data *hud_hires_sprite_bitmap(const struct bitmap_data *b,long s) {return b;} +static float custom_edition_hud_bitmap_scale(long i) {assert(i==7);reads++;return factor;} +static int local_player_count(void) {return players;} +static void hud_draw_bitmap_direct(const struct bitmap_data *b,int corner,const point2d *p,const real_rectangle2d *c,float scale,float rotation,pixel32 color,int linear) {draws++;drawn_scale=scale;drawn_point=*p;} +''' + body + r''' +int main(void) { + struct icon_hud_element_definition icon={0,0,{8,12},0,0,4}; + rectangle2d bounds={0,0,640,480},cursor={100,0,640,80}; + render_state_bitmap(&bounds,&cursor,0,&icon); + assert(draws==1 && drawn_scale==.25f && drawn_point.x==108 && drawn_point.y==68); + assert(cursor.x0==144); /* 128*.25 + 4 + (100+8). */ + clipped=1;cursor.x0=100;render_state_bitmap(&bounds,&cursor,0,&icon); + assert(cursor.x0==128); /* Sprite bounds scale, authored offset does not. */ + players=2;cursor.x0=100;render_state_bitmap(&bounds,&cursor,0,&icon); + assert(drawn_scale==.1875f && drawn_point.x==106 && drawn_point.y==71 && cursor.x0==121); + icon.flags=2;cursor.x0=100;render_state_bitmap(&bounds,&cursor,0,&icon); + assert(cursor.x0==109); /* Absolute advance does not depend on bitmap flags. */ + draws=reads=0;button=1;render_state_bitmap(&bounds,&cursor,0,&icon); + assert(draws==0 && reads==0); /* Stock replacement glyph owns its geometry. */ + button=0;mcc=owned=1;render_state_bitmap(&bounds,&cursor,0,&icon); + assert(draws==0 && reads==0); /* MCC icon ownership remains first. */ + return 0; +} +''') diff --git a/tools/test_ce_npot_bitmaps.py b/tools/test_ce_npot_bitmaps.py new file mode 100644 index 0000000000..ab39b3dd39 --- /dev/null +++ b/tools/test_ce_npot_bitmaps.py @@ -0,0 +1,262 @@ +"""Real CE admission and Xbox descriptor code, with no retail assets or GPU. + +Compile for the game's 32-bit ABI. Only tag iteration, logging and resource +registration are faked; bitmap validation, byte counts and descriptors are +extracted from the implementation. GPU/runtime checks remain separate. +""" +import re +import shutil +import subprocess +import sys + +import pytest + +from tools.harness import enum_with, function, read, structure + + +def array(source, name): + return re.search(r"static [^;{}]*\b" + name + r"\s*\[[^;]*?\n\};", source).group() + + +def implementation(): + bitmap = read("source/bitmaps/bitmaps.c") + group = read("source/bitmaps/bitmap_group.h") + ce = read("port/linux/game/custom_edition_bitmaps.c") + cache = read("source/cache/xbox_texture_cache.c") + gpu = read("port/linux/src/xbox_textures.c") + definitions = read("port/include/xdk/xdk_d3d8.h") + parts = [PREAMBLE] + parts += [enum_with(bitmap, name) for name in ( + "MAXIMUM_BITMAP_WIDTH =", "_bitmap_type_2d,", "_bitmap_format_a8,", + "_bitmap_has_power_of_two_dimensions_bit,")] + parts += [enum_with(group, "BITMAP_GROUP_TAG ="), structure(group, "bitmap_data"), + structure(read("port/linux/src/xgpu.h"), "xgpu_texture_description"), + enum_with(read("port/include/xdk/xdk_pdb.h"), "D3DFMT_DXT1 ="), + enum_with(cache, "_bitmap_d3d_format_table_regular,"), + array(bitmap, "bitmap_format_bits_per_pixel_table"), + array(cache, "bitmap_d3d_format_tables")] + parts += [ + line for line in definitions.splitlines() + if re.match(r"#define (?:D3DCOMMON|D3DFORMAT|D3DSIZE|D3DTEXTURE)_", line)] + parts += [function(gpu, "floor_log2")] + parts += [function(bitmap, name) for name in ( + "bitmap_format_type_valid_width", "bitmap_format_type_valid_height", + "bitmap_format_type_valid_depth", "bitmap_verify", "bitmap_format_get_bits_per_pixel", + "bitmap_mipmap_get_width", "bitmap_mipmap_get_height", "bitmap_mipmap_get_depth", + "bitmap_mipmap_get_pixel_count", "bitmap_get_pixel_count", "bitmap_get_pixel_data_size", + "bitmap_mipmap_get_row_pitch")] + parts += [function(ce, name) for name in ( + "power_of_two", "bitmap_format_drawable", "bitmap_readable", "bitmap_swizzle_possible", + "custom_edition_bitmap_drawable")] + parts += [WORLD, function(ce, "custom_edition_bitmaps_verify"), + function(ce, "custom_edition_bitmap_pixels_arrived"), + function(read("port/linux/game/custom_edition_cache.c"), "custom_edition_cache_contains")] + parts += [function(cache, name) for name in ( + "bitmap_format_to_d3d_format", "bitmap_format_to_d3d_linear_format", + "texture_cache_initialize_hardware_format")] + parts += [enum_with(gpu, "_texel_unknown,"), structure(gpu, "format_information")] + parts += [function(gpu, name) for name in ( + "format_information", "kind_compressed", "level_dimension", "xgpu_texture_describe", + "level_bytes", "xgpu_texture_level_offset", "xgpu_texture_face_size", "xgpu_texture_level_pitch")] + return "\n".join(parts) + + +PREAMBLE = r""" +#include +#include +#include +#include +typedef int boolean; +typedef int BOOL; +typedef unsigned long DWORD; +typedef unsigned short word; +typedef unsigned char byte; +union point2d { struct {short x, y;} coordinates; long value; }; +typedef struct { DWORD Common, Data, Lock, Format, Size; } D3DBaseTexture; +#define TRUE 1 +#define FALSE 0 +#define NONE (-1) +#define FLAG(n) (1U << (n)) +#define TEST_FLAG(value, bit) ((value) & FLAG(bit)) +#define VALID_INDEX(n, count) ((unsigned)(n) < (unsigned)(count)) +#define MAX(a,b) ((a) > (b) ? (a) : (b)) +#define match_assert(file,line,test) assert(test) +#define match_vassert(file,line,test,message) assert(test) +#define error(...) ((void)0) +#define IDirect3DBaseTexture8_Register(texture,address) ((void)0) +#define rasterizer_xbox_bitmap_get_max_mipmap_count(bitmap) ((bitmap)->mipmap_count) +""" + +WORLD = r""" +static struct custom_edition_cache_globals { + void *tag_cache; + unsigned long loaded_bytes; + int tags_loaded; +} custom_edition_cache_globals; +struct bitmap_group { struct { long count; struct bitmap_data *address; } bitmaps; }; +static struct bitmap_group group; +static int mcc_loaded; +#define mcc_cache_tags_loaded() mcc_loaded +#define TAG_BLOCK_GET_ELEMENT(block,index,type) (&(block)->address[index]) +#define custom_edition_cache_tag_name(cache,bytes,index) "fixture" +static struct bitmap_group *custom_edition_cache_tag_get( + void *cache, unsigned long bytes, unsigned long index, unsigned long tag, unsigned long size) +{ + return &group; +} +#define reordered_bitmap_index(tag,index) NONE +#define xbox_pointer(pointer) (pointer) +#define _custom_edition_channels_xbox 0 +#define halo_custom_edition_texels_channels(pointer,order) ((void)0) +static struct {struct {int channel_order;} reordered_bitmaps[1];} custom_edition_bitmaps_globals; +static int rebuilds; +#define rasterizer_xbox_bitmap_rebuild_hardware_format(bitmap) (++rebuilds) +static struct bitmap_group *custom_edition_cache_tag_next( + void *cache, unsigned long bytes, unsigned long tag, unsigned long size, int32_t *index) +{ + if (*index != NONE) return NULL; + *index = 0; + return &group; +} +""" + +CASES = r""" +static struct bitmap_data fixture(short format) +{ + struct bitmap_data bitmap; + memset(&bitmap, 0, sizeof(bitmap)); + bitmap.signature = BITMAP_GROUP_TAG; + bitmap.width = 200; bitmap.height = 112; bitmap.depth = 1; + bitmap.format = format; + bitmap.flags = FLAG(_bitmap_compressed_bit); + bitmap.pixels_size = bitmap_get_pixel_data_size(&bitmap); + return bitmap; +} +static int admitted(struct bitmap_data *bitmap) +{ + group.bitmaps.count = 1; group.bitmaps.address = bitmap; + return custom_edition_bitmaps_verify(NULL, 0); +} +static struct xgpu_texture_description describe(struct bitmap_data *bitmap) +{ + D3DBaseTexture texture; + struct xgpu_texture_description description; + texture_cache_initialize_hardware_format(bitmap, &texture); + xgpu_texture_describe(texture.Format, texture.Size, &description); + return description; +} +int main(int argc, char **argv) +{ + struct bitmap_data bitmap, other; + struct xgpu_texture_description desc; + short format; + int mode = argc > 1 ? argv[1][0] : 0; + bitmap = fixture(_bitmap_format_dxt1); + custom_edition_cache_globals.tag_cache = &bitmap; + custom_edition_cache_globals.loaded_bytes = sizeof(bitmap); + custom_edition_cache_globals.tags_loaded = TRUE; + if (mode == 'a') { + for (format = _bitmap_format_dxt1; format <= _bitmap_format_dxt5; format++) { + bitmap = fixture(format); + assert(admitted(&bitmap)); + assert(!custom_edition_bitmap_drawable(&bitmap)); + desc = describe(&bitmap); + assert(desc.width == 200 && desc.height == 112 && desc.depth == 1); + assert(desc.levels == 1 && desc.compressed && !desc.linear && !desc.cube_map); + assert(xgpu_texture_face_size(&desc) == (format == _bitmap_format_dxt1 ? 11200 : 22400)); + assert(xgpu_texture_face_size(&desc) == bitmap.pixels_size); + assert(xgpu_texture_level_pitch(&desc, 0) == (format == _bitmap_format_dxt1 ? 400 : 800)); + bitmap.width = 4096; bitmap.height = 4092; + bitmap.pixels_size = bitmap_get_pixel_data_size(&bitmap); + assert(admitted(&bitmap)); + desc = describe(&bitmap); + assert(desc.width == 4096 && desc.height == 4092); + } + } else if (mode == 'r') { + bitmap.pixels_size--; assert(!admitted(&bitmap)); + bitmap = fixture(_bitmap_format_dxt1); bitmap.mipmap_count = 1; + bitmap.pixels_size = bitmap_get_pixel_data_size(&bitmap); assert(admitted(&bitmap)); + desc = describe(&bitmap); assert(desc.levels == 1); /* upstream draws only the first NPOT level */ + bitmap = fixture(_bitmap_format_dxt1); bitmap.width = 201; assert(!admitted(&bitmap)); + bitmap = fixture(_bitmap_format_dxt1); bitmap.height = 111; assert(admitted(&bitmap)); + bitmap = fixture(_bitmap_format_dxt1); bitmap.width = MAXIMUM_BITMAP_WIDTH + 1; + assert(!admitted(&bitmap)); + bitmap = fixture(_bitmap_format_dxt1); bitmap.flags |= FLAG(_bitmap_linear_bit); + assert(!admitted(&bitmap)); + bitmap = fixture(_bitmap_format_dxt1); bitmap.flags = 0; assert(!admitted(&bitmap)); + bitmap = fixture(_bitmap_format_p8_bump); bitmap.flags = 0; + bitmap.pixels_size = bitmap_get_pixel_data_size(&bitmap); assert(admitted(&bitmap)); + bitmap = fixture(_bitmap_format_dxt1); bitmap.type = _bitmap_type_cube_map; + bitmap.width = bitmap.height = 96; + bitmap.pixels_size = bitmap_get_pixel_data_size(&bitmap); assert(admitted(&bitmap)); + bitmap.type = _bitmap_type_3d; bitmap.depth = 4; + bitmap.pixels_size = bitmap_get_pixel_data_size(&bitmap); assert(admitted(&bitmap)); + } else if (mode == 'o') { + assert(custom_edition_cache_contains(&bitmap, sizeof(bitmap))); + assert(!custom_edition_cache_contains(&bitmap, sizeof(bitmap) + 1)); + assert(!custom_edition_cache_contains((char *)&bitmap + sizeof(bitmap), 1)); + assert(!custom_edition_cache_contains((void *)~0UL, 2)); + other = bitmap; assert(!custom_edition_cache_contains(&other, sizeof(other))); + desc = describe(&other); assert(desc.width == 200 && desc.height == 112); + mcc_loaded = TRUE; desc = describe(&bitmap); + assert(desc.width == 200 && desc.height == 112); + mcc_loaded = FALSE; custom_edition_cache_globals.tags_loaded = FALSE; + assert(!custom_edition_cache_contains(&bitmap, sizeof(bitmap))); + desc = describe(&bitmap); assert(desc.width == 200 && desc.height == 112); + custom_edition_cache_globals.tags_loaded = TRUE; + desc = describe(&bitmap); assert(desc.width == 200 && desc.height == 112); + } else if (mode == 'p') { + bitmap.base_address = &other; + group.bitmaps.count = 1; group.bitmaps.address = &bitmap; + custom_edition_bitmap_pixels_arrived(NULL, 0, 0, 0, &other); + assert(!rebuilds); + bitmap.width = 128; bitmap.height = 64; + custom_edition_bitmap_pixels_arrived(NULL, 0, 0, 0, &other); + assert(rebuilds == 1); + bitmap = fixture(_bitmap_format_a8r8g8b8); + bitmap.base_address = &other; bitmap.flags = FLAG(_bitmap_linear_bit); + bitmap.pixels_size = bitmap_get_pixel_data_size(&bitmap); + custom_edition_bitmap_pixels_arrived(NULL, 0, 0, 0, &other); + assert(rebuilds == 2); + } else if (mode == 'l') { + bitmap.width = 256; bitmap.height = 128; bitmap.mipmap_count = 3; + bitmap.pixels_size = bitmap_get_pixel_data_size(&bitmap); + assert(admitted(&bitmap) && custom_edition_bitmap_drawable(&bitmap)); + desc = describe(&bitmap); + assert(desc.width == 256 && desc.height == 128 && desc.levels == 4 && !desc.linear); + bitmap = fixture(_bitmap_format_a8r8g8b8); + bitmap.flags = FLAG(_bitmap_linear_bit); + bitmap.pixels_size = bitmap_get_pixel_data_size(&bitmap); + assert(admitted(&bitmap) && custom_edition_bitmap_drawable(&bitmap)); + desc = describe(&bitmap); + assert(desc.width == 200 && desc.height == 112 && desc.linear && !desc.compressed); + assert(desc.pitch == 832 && xgpu_texture_face_size(&desc) == 832 * 112); + } else return 2; + puts("bitmap contract passed"); + return 0; +} +""" + + +@pytest.fixture(scope="module") +def bitmap_probe(tmp_path_factory): + clang = shutil.which("clang") + if not clang: + pytest.skip("clang is required for the 32-bit bitmap probe") + directory = tmp_path_factory.mktemp("ce-npot") + source = directory / "probe.c" + source.write_text(implementation() + CASES) + executable = directory / ("probe.exe" if sys.platform == "win32" else "probe") + target = (["--target=i686-pc-windows-msvc", "-fuse-ld=lld"] + if sys.platform == "win32" else ["-m32"]) + result = subprocess.run([clang, *target, "-std=gnu89", "-O1", + "-fsanitize=undefined", "-fsanitize-trap=undefined", + str(source), "-o", str(executable)], capture_output=True, text=True) + assert result.returncode == 0, result.stderr + return executable + + +@pytest.mark.parametrize("case", ["admission", "rejections", "ownership", "pixels", "legacy"]) +def test_bitmap_contract(bitmap_probe, case): + result = subprocess.run([str(bitmap_probe), case], capture_output=True, text=True, timeout=30) + assert result.returncode == 0, result.stdout + result.stderr diff --git a/tools/test_changelog_layout.py b/tools/test_changelog_layout.py new file mode 100644 index 0000000000..c5aabe60d9 --- /dev/null +++ b/tools/test_changelog_layout.py @@ -0,0 +1,97 @@ +"""Exercise the real changelog layout module with the generated main menu.""" +import json +import os +from pathlib import Path +import shutil +import subprocess +import xml.etree.ElementTree as ET + +import pytest + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.fixture(scope="session") +def layout_tool(tmp_path_factory): + cc = os.environ.get("CC") or shutil.which("clang") or shutil.which("cc") + if not cc: + pytest.skip("a C compiler is needed for the changelog layout test") + tree = ET.parse(ROOT / "port/assets/menus/ce/main_menu.xml") + rows = tree.find("widget[@name='main_menu/main_menu']").findall("child") + assert any(row.get("widget") == "main_menu/changelog_corner" for row in rows) + setup = "\n".join( + f"children[{i}].widget = {json.dumps(row.get('widget'))}; " + f"children[{i}].x = {row.get('x', 0)}; children[{i}].y = {row.get('y', 0)};" + for i, row in enumerate(rows) + ) + folder = tmp_path_factory.mktemp("changelog-layout") + source = folder / "layout.c" + binary = folder / ("layout.exe" if os.name == "nt" else "layout") + source.write_text(r''' +#include "halo_menus.h" +#include "changelog_menu.h" +#include +#include +int main(int argc, char **argv) +{ + struct halo_menus menus = {0}; + struct halo_menu_widget widget = {0}; + struct halo_menu_child children[32] = {0}, before[32]; + long i; + int enabled; + if (argc != 2) return 2; + enabled = !strcmp(argv[1], "on") || !strcmp(argv[1], "repeat"); + menus.widgets = &widget; menus.widget_count = 1; + menus.children = children; menus.child_count = ROWCOUNT; + widget.name = "main_menu/main_menu"; widget.first_child = 0; + for (i = 0; i < ROWCOUNT; i++) { + children[i].nested = HALO_MENU_NONE; + children[i].next = i == ROWCOUNT - 1 ? HALO_MENU_NONE : i + 1; + } +'''.replace('ROWCOUNT', str(len(rows))) + setup + r''' + if (!strcmp(argv[1], "other")) widget.name = "main_menu/mods/mods_list"; + memcpy(before, children, sizeof(children)); + changelog_menu_configure(&menus, enabled); + changelog_menu_configure(&menus, enabled); + if (enabled || !strcmp(argv[1], "other")) { + if (memcmp(before, children, sizeof(children))) return 3; + } + for (i = widget.first_child; i != HALO_MENU_NONE; i = children[i].next) + printf("%s %ld %ld\n", children[i].widget, children[i].x, children[i].y); + return 0; +} +''') + command = [cc, "-std=c89", "-Wall", "-Wextra", "-Werror", + "-iquote", str(ROOT / "port/linux/include"), + "-iquote", str(ROOT / "port/linux/src"), str(source), + str(ROOT / "port/linux/src/changelog_menu.c"), "-o", str(binary)] + if os.name == "nt": + command.insert(1, "--target=i686-pc-windows-msvc") + built = subprocess.run(command, capture_output=True, text=True) + assert built.returncode == 0, built.stdout + built.stderr + return binary + + +def run_layout(tool, mode): + output = subprocess.run([str(tool), mode], check=True, capture_output=True, text=True).stdout + return [line.rsplit(" ", 2) for line in output.splitlines()] + + +def test_corner_is_separate_from_original_six_rows(layout_tool): + rows = run_layout(layout_tool, "on") + assert [row for row in rows if row[0].endswith("changelog_corner")] == [ + ["main_menu/changelog_corner", "447", "438"]] + tree = ET.parse(ROOT / "port/assets/menus/ce/main_menu.xml") + central = tree.find("widget[@name='main_menu/main_menu_select_list']").findall("child") + assert len(central) == 6 + assert [int(row.get("y")) for row in central] == [247, 283, 319, 355, 391, 427] + + +def test_disabled_removes_only_corner_and_preserves_build_label(layout_tool): + on, off = run_layout(layout_tool, "on"), run_layout(layout_tool, "off") + assert off == [row for row in on if row[0] != "main_menu/changelog_corner"] + assert any(row[0] == "main_menu/gulch_build_number" for row in off) + + +def test_unrelated_menu_is_unchanged(layout_tool): + assert run_layout(layout_tool, "other") == run_layout(layout_tool, "on") diff --git a/tools/test_changelog_menu.py b/tools/test_changelog_menu.py new file mode 100644 index 0000000000..93a413a900 --- /dev/null +++ b/tools/test_changelog_menu.py @@ -0,0 +1,588 @@ +"""Check changelog packaging, navigation and the generated presentation.""" + +import json +import copy +import os +from pathlib import Path +import shutil +import subprocess +import sys +import xml.etree.ElementTree as ET + +from PIL import Image, ImageFont +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import changelog_menu + +MENUS = Path(__file__).resolve().parents[1] / "port/assets/menus" +ROOT = MENUS.parents[2] + + +def feature(): + return ET.parse(MENUS / "ce" / changelog_menu.FILE).getroot() + + +def notes_data(notes=None): + return {"schema_version": 2, "head": "a" * 40, "entries": [ + {"build": 12, "date": "2026-10-18", "commit": "a" * 40, + "notes": notes if notes is not None else ["A change for players."]}]} + + +def widgets_for(data): + root = ET.fromstring("" + "\n".join(changelog_menu.widget_lines(data)) + "") + return {node.get("name"): node for node in root.findall("widget")} + + +def test_focused_generation_needs_no_pc_tags(monkeypatch): + import ce_menus + calls = [] + monkeypatch.setattr(sys, "argv", ["ce_menus.py", "--changelog-only"]) + monkeypatch.setattr(changelog_menu, "regenerate", lambda: calls.append(True)) + ce_menus.main() + assert calls == [True] + + +def test_shipped_widgets_match_generator(): + expected = ET.fromstring("" + "\n".join(changelog_menu.widget_lines()) + "") + actual = feature() + for root in (expected, actual): + for node in root.iter(): + node.tail = None + for element in ("widget", "strings"): + assert [ET.tostring(widget) for widget in actual.findall(element)] == [ + ET.tostring(widget) for widget in expected.findall(element)] + + +def test_full_generation_uses_the_same_real_data(monkeypatch, tmp_path): + (tmp_path / "ce").mkdir() + monkeypatch.setattr(changelog_menu, "MENUS", tmp_path) + monkeypatch.setattr(changelog_menu.port_settings, "menu_item_frames", lambda *args: []) + + class Art: + redraws = None + + def port_picture(self, name, frames): + return f'' + + def title(self, name, text): + return f'' + + data = notes_data(["Recorded player improvement."]) + changelog_menu.generate(Art(), data) + actual = ET.parse(tmp_path / "ce" / changelog_menu.FILE).getroot() + expected = widgets_for(data) + assert {node.get("name"): node.get("text") for node in actual.findall("widget")} == { + name: node.get("text") for name, node in expected.items()} + + +def test_feature_files_are_embedded_and_navigation_resolves(): + manifest = json.loads((MENUS / "menus.json").read_text())["files"] + assert f"ce/{changelog_menu.FILE}" in manifest + assert len(manifest) == len(set(manifest)) + widgets, bitmaps = {}, {} + for file in manifest: + if not file.endswith(".xml"): + continue + root = ET.parse(MENUS / file).getroot() + for node in root.findall("widget"): + assert node.get("name") not in widgets + widgets[node.get("name")] = node + for node in root.findall("bitmap"): + assert node.get("name") not in bitmaps + bitmaps[node.get("name")] = node + for node in feature().findall("widget"): + if node.get("bitmap"): + assert node.get("bitmap") in bitmaps + for child in node: + for attribute in ("widget", "open", "replace"): + if child.get(attribute): + assert child.get(attribute) in widgets + assert child.get("run") in (None, "mouse emit accept event", "port changelog init", + "port changelog up", "port changelog down", "port gulch build label") + for bitmap in feature().findall("bitmap"): + for frame in bitmap: + assert frame.get("png") in manifest + with Image.open(MENUS / frame.get("png")) as image: + assert image.mode == "RGBA" + assert image.width == int(frame.get("width")) * 4 + assert image.height == int(frame.get("height")) * 4 + assert image.getchannel("A").getbbox() + + +def test_builds_have_real_labels_back_and_history_preserving_navigation(): + data = notes_data([f"Player change {i}." for i in range(30)]) + data["entries"] += [dict(data["entries"][0], build=11), dict(data["entries"][0], build=10)] + widgets = widgets_for(data) + for number in range(1, 4): + name = f"{changelog_menu.BASE}/build_{number}" + page = widgets[name] + events = {event: handler for handler in page.findall("on") for event in handler.get("event").split()} + assert events["b"].get("back") == "true" + assert events["back"].get("back") == "true" + assert events["start"].get("back") == "true" + if number < 3: + assert events["left"].get("open") == f"{changelog_menu.BASE}/build_{number + 1}" + else: + assert "left" not in events + if number > 1: + assert events["right"].get("open") == f"{changelog_menu.BASE}/build_{number - 1}" + else: + assert "right" not in events + assert "no_history" in page.get("flags").split() + assert widgets[f"{name}/label"].get("text") == "PLAYER NOTES" + assert widgets[f"{name}/heading"].get("text") == f"BUILD {13 - number}" + assert widgets[f"{name}/date"].get("text") == "2026-10-18" + assert widgets[f"{name}/button_back"].find("on").get("back") == "true" + assert "pass_unhandled_to_focused_child" in widgets[f"{name}/buttons"].get("flags") + assert "tabs" not in widgets[f"{name}/buttons"].get("flags") + for direction in ("up", "down"): + assert events[direction].get("run") == f"port changelog {direction}" + assert events[f"stick_{direction}"].get("run") == f"port changelog {direction}" + assert events[direction].get("open") is None + assert events["created"].get("run") == "port changelog init" + for node in [widgets[child.get("widget")] for child in page.findall("child")]: + if node.get("text"): + assert node.get("font") in ("ui\\small_ui", "ui\\large_ui") + # ui_widget_load_by_name_or_tag (source/interface/ui_widget.c, + # invoking_widget_tag history decision) tests the invoking root's + # no_history flag. Open plus no_history preserves the original main + # menu history entry across any number of page changes. + assert all(handler.get("replace") is None for handler in page.findall("on")) + for node in widgets.values(): + if node.get("name", "").startswith(name + "/"): + assert all(handler.get("replace") is None for handler in node.findall("on")) + for handler in node.findall("on"): + if handler.get("open"): + assert handler.get("open") in ( + f"{changelog_menu.BASE}/build_{number - 1}", + f"{changelog_menu.BASE}/build_{number + 1}") + main = ET.parse(MENUS / "ce/main_menu.xml").getroot().find("widget[@name='main_menu/main_menu']") + assert "no_history" not in main.get("flags", "").split() + + +def test_reading_area_and_controls_fit_the_menu_canvas(): + data = notes_data(["W" * 100, "Fixed " + "a" * 94] * 10) + widgets = widgets_for(data) + + def visit(name, x=0, y=0): + node = widgets[name] + left = x + int(node.get("left", 0)) + top = y + int(node.get("top", 0)) + assert 0 <= left < left + int(node.get("width", 640)) <= 640 + assert 0 <= top < top + int(node.get("height", 480)) <= 480 + for child in node.findall("child"): + visit(child.get("widget"), left + int(child.get("x", 0)), top + int(child.get("y", 0))) + + visit(f"{changelog_menu.BASE}/build_1") + + +def test_long_notes_are_complete_in_one_build_with_fixed_visible_rows(): + notes = ["W" * 100, "Fixed " + "a" * 94, "a " * 49 + "a"] * 3 + data = notes_data(notes) + contents = changelog_menu.reading_lines(data["entries"][0]) + assert len(contents) > 8 + assert "".join(line[2:] for line in contents if line).replace(" ", "") == "".join(notes).replace(" ", "") + assert all(sum(2 if c.isupper() or c in "mw@%&#" else 1 for c in line) <= changelog_menu.NOTE_COLUMNS for line in contents) + widgets = widgets_for(data) + assert f"{changelog_menu.BASE}/build_2" not in widgets + for row in range(changelog_menu.VISIBLE_LINES): + node = widgets[f"{changelog_menu.BASE}/build_1/row_{row}"] + assert node.get("string_list") == f"{changelog_menu.BASE}/build_1/lines" + assert int(node.get("string_index")) == row + assert int(node.get("height")) == changelog_menu.NOTE_LINE_HEIGHT + + +def test_reading_width_and_bottom_right_arrow_pair(): + # ui.map's small_ui capitals are 10 logical pixels; use the bundled + # font without the runtime's 98% narrowing for a conservative bound. + font = ImageFont.truetype(str(ROOT / "port/assets/fonts/Overpass-750.ttf"), 1000) + box = font.getbbox("H") + scale = 10 / (box[3] - box[1]) + per_column = max(font.getlength(chr(c)) * scale / + (2 if chr(c).isupper() or chr(c) in "mw@%&#" else 1) for c in range(32, 127)) + assert per_column * changelog_menu.NOTE_COLUMNS <= 420 + assert max(font.getlength(c) for c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") * 24 * scale <= 420 + data = notes_data(["0" * 100, "W" * 100]) + data["entries"][0]["categories"] = ["W" * 24, ""] + widgets = widgets_for(data) + screen = widgets[f"{changelog_menu.BASE}/build_1"] + children = {child.get("widget").rsplit("/", 1)[-1]: child for child in screen.findall("child")} + controls = children["scroll_controls"] + assert controls.get("x") == "480" and controls.get("y") == "314" + column = widgets[f"{changelog_menu.BASE}/build_1/scroll_controls"] + assert column.get("type") == "column_list" + assert "tabs" not in column.get("flags") + up, down = column.findall("child") + assert int(up.get("y", 0)) == 0 and down.get("y") == "28" + assert int(down.get("y")) - int(up.get("y", 0)) - 24 == 4 + for name in ("scroll_up", "scroll_down"): + assert widgets[f"{changelog_menu.BASE}/build_1/{name}"].get("width") == "128" + + +@pytest.mark.parametrize("empty_entries", [True, False]) +def test_empty_notes_are_truthful(empty_entries): + data = notes_data([]) + if empty_entries: + data["entries"] = [] + text = "\n".join(changelog_menu.widget_lines(data)) + assert "No player-facing changes recorded." in text + assert "SAMPLE" not in text + assert "build_2" not in text + + +def test_notes_are_xml_escaped(): + data = notes_data(['Improved & "controls".']) + root = ET.fromstring("" + "\n".join(changelog_menu.widget_lines(data)) + "") + assert next(node.get("text") for node in root.find("strings") if node.get("text")) == '- Improved & "controls".' + + +def test_categories_are_blue_grouped_and_notes_have_no_blank_separator(): + data = notes_data(["First interface change.", "A convenience.", "Second interface change.", "Another change."]) + data["entries"][0]["categories"] = ["INTERFACE", "QUALITY OF LIFE", "INTERFACE", ""] + rows = changelog_menu.reading_rows(data["entries"][0]) + assert rows == [("", "INTERFACE"), ("- First interface change.", ""), + ("- Second interface change.", ""), ("", ""), + ("", "QUALITY OF LIFE"), ("- A convenience.", ""), ("", ""), + ("", "GENERAL"), ("- Another change.", "")] + widgets = widgets_for(data) + for row in range(changelog_menu.VISIBLE_LINES): + body = widgets[f"{changelog_menu.BASE}/build_1/row_{row}"] + heading = widgets[f"{changelog_menu.BASE}/build_1/heading_row_{row}"] + assert body.get("top") == heading.get("top") + assert body.get("string_index") == heading.get("string_index") + assert heading.get("color") == "#FF2896FF" + assert heading.get("string_list").endswith("/headings") + + +def test_oversized_wrapped_build_is_rejected_before_serializing_widgets(): + data = notes_data([("W" * 22 + " ") * 4] * 4096) + # Strip the trailing separator; every accepted note remains under100 chars. + data["entries"][0]["notes"] = [note.strip() for note in data["entries"][0]["notes"]] + data["entries"][0]["categories"] = [f"GROUP {index}" for index in range(4096)] + with pytest.raises(ValueError, match="32767-line"): + changelog_menu.widget_lines(data) + + +@pytest.mark.parametrize("change", [ + lambda d: d.update(schema_version=1), + lambda d: d.update(schema_version=True), + lambda d: d.update(head="bad"), + lambda d: d.update(entries={}), + lambda d: d.update(extra="unsupported"), + lambda d: d["entries"][0].update(notes=["Too many notes."] * 4097), + lambda d: d["entries"][0].update(build="12"), + lambda d: d["entries"][0].update(build=True), + lambda d: d["entries"][0].update(build=0), + lambda d: d["entries"][0].update(build=-1), + lambda d: d["entries"].append(dict(d["entries"][0])), + lambda d: d["entries"][0].update(commit="bad"), + lambda d: d["entries"][0].update(date="2026-02-30"), + lambda d: d["entries"][0].update(date="20261018"), + lambda d: d["entries"][0].update(notes="not a list"), + *[lambda d, labels=labels: d["entries"][0].update(categories=labels) for labels in + ("FIXES", [], ["lowercase"], [" FIXES"], ["A B"], ["0FIXES"], ["A" * 25], ["A\\n"], [1])], + *[lambda d, note=note: d["entries"][0].update(notes=[note]) for note in + ("", "x" * 101, "newline\nhere", "tab\there", "a\\n", "a|b", "caf\u00e9", " leading", "trailing ", "\x00")], +]) +def test_malformed_notes_are_rejected(change): + data = copy.deepcopy(notes_data()) + change(data) + with pytest.raises(ValueError): + changelog_menu.widget_lines(data) + + +def test_text_only_cli_uses_no_art_dependencies_and_preserves_bitmap_xml(tmp_path): + # A fresh isolated interpreter makes accidental heavy imports fail, + # even when the surrounding pytest process already loaded Pillow. + menus = tmp_path / "menus" + (menus / "ce").mkdir(parents=True) + target = menus / "ce" / changelog_menu.FILE + original = (MENUS / "ce" / changelog_menu.FILE).read_text(encoding="utf-8") + target.write_text(original, encoding="utf-8") + notes = tmp_path / "notes.json" + notes.write_text(json.dumps(notes_data()), encoding="utf-8") + script = r''' +import importlib.abc, sys +from pathlib import Path +class BlockArt(importlib.abc.MetaPathFinder): + def find_spec(self, fullname, path=None, target=None): + if fullname.split('.')[0] in ('ce_menus', 'numpy', 'PIL', 'fontTools'): + raise AssertionError('art dependency imported: ' + fullname) +sys.meta_path.insert(0, BlockArt()) +sys.path.insert(0, sys.argv[1]) +import changelog_menu +changelog_menu.MENUS = Path(sys.argv[2]) +sys.argv = ['changelog_menu.py', '--notes', sys.argv[3], '--text-only'] +# Exercise the CLI with its module globals redirected to an isolated tree. +code = Path(changelog_menu.__file__).read_text() +exec(compile(code[code.index('if __name__ == "__main__":'):], changelog_menu.__file__, 'exec'), + dict(vars(changelog_menu), __name__='__main__')) +''' + command = [sys.executable, "-S", "-c", script, str(Path(changelog_menu.__file__).parent), str(menus), str(notes)] + subprocess.run(command, check=True, capture_output=True, text=True) + first = target.read_text(encoding="utf-8") + assert changelog_menu.re.findall(r'\t]*>.*?', first, changelog_menu.re.DOTALL) == changelog_menu.re.findall( + r'\t]*>.*?', original, changelog_menu.re.DOTALL) + subprocess.run(command, check=True, capture_output=True, text=True) + assert target.read_text(encoding="utf-8") == first + + +def test_insertion_preserves_legacy_menu_and_is_idempotent(): + main = (MENUS / "ce/main_menu.xml").read_text() + baseline = main.replace("\t\t" + changelog_menu.CHILD + "\n", "") + assert changelog_menu.insert_item(baseline) == main + assert changelog_menu.insert_item(main) == main + rows = ET.fromstring(main).find("widget[@name='main_menu/main_menu_select_list']").findall("child") + assert [row.get("widget") for row in rows[-2:]] == [ + "main_menu/main_menu_item_mods", "main_menu/main_menu_item_quit_game"] + assert [int(row.get("y")) for row in rows] == [247, 283, 319, 355, 391, 427] + root = ET.fromstring(main).find("widget[@name='main_menu/main_menu']") + assert root.find(f"child[@widget='{changelog_menu.CORNER}']").attrib == { + "widget": changelog_menu.CORNER, "x": "447", "y": "438"} + label = root.find(f"child[@widget='{changelog_menu.BUILD_LABEL}']") + assert label.get("x") == "424" and label.get("y") == "420" + label_widget = feature().find(f"widget[@name='{changelog_menu.BUILD_LABEL}']") + assert label_widget.get("align") == "center" and label_widget.get("width") == "150" + assert int(label.get("x")) + 150 / 2 == 499 + assert 447 + changelog_menu.CORNER_WIDTH / 2 == 499 + corner = feature().find(f"widget[@name='{changelog_menu.CORNER}']") + assert corner.get("type") == "column_list" + assert corner.find("child").get("widget") == changelog_menu.ITEM + assert corner.get("width") == "104" and corner.get("height") == "21" + item = feature().find(f"widget[@name='{changelog_menu.ITEM}']") + assert item.get("width") == "104" and item.get("height") == "21" + + +def test_corner_art_scales_the_whole_design_without_changing_its_groups(): + frames = changelog_menu.corner_frames(MENUS / "svg") + assert len(frames) == 2 + for index, (svg, width, height) in enumerate(frames): + root = ET.fromstring(svg) + assert (width, height) == (104, 21) + assert root.get("viewBox") == "0 0 160 32" + assert root.get("preserveAspectRatio") == "xMinYMin meet" + # Keeping both design groups unchanged scales the caption, outline + # and glow together; fitting the outline separately would restyle it. + groups = list(root) + assert [group.get("transform") for group in groups] == [ + "translate(0,3) scale(1.25,1)", "translate(2,4) scale(0.6)"] + expected_border = ET.parse(MENUS / f"svg/shell/bitmaps/text_button_background__{index}.svg").getroot() + expected_caption = ET.fromstring(changelog_menu.port_settings.menu_item_frames( + "CHANGELOG", MENUS / "svg", changelog_menu.SPACING)[index][0]) + for actual, expected in zip(groups, (expected_border, expected_caption)): + for node in (*actual.iter(), *expected.iter()): + node.tail = None + if node.text and not node.text.strip(): + node.text = None + assert [ET.tostring(child) for child in actual] == [ET.tostring(child) for child in expected] + + +def c_function(source, name): + """Take the real function body for asset-free input routing checks.""" + start = source.rindex(name) + opening = source.index("{", start) + depth = 1 + end = opening + 1 + while depth: + depth += (source[end] == "{") - (source[end] == "}") + end += 1 + return source[start:end] + + +def test_real_scroll_runtime_and_existing_wheel_route(tmp_path): + cc = os.environ.get("CC") or shutil.which("clang") or shutil.which("cc") + if not cc: + pytest.skip("a C compiler is needed for the scroll runtime test") + engine = (ROOT / "source/interface/ui_widget.c").read_text() + wheel = c_function(engine, "static struct widget_instance *ui_mouse_wheel_widget(") + directions = c_function(engine, "static void ui_mouse_list_directions(") + mouse_item = c_function(engine, "static boolean ui_mouse_widget_is_item(") + code = r''' +#include +#include +#include +#include +typedef int boolean; +#define FALSE 0 +#define TRUE 1 +#define NONE (-1) +#define MAX(a,b) ((a) > (b) ? (a) : (b)) +#define MIN(a,b) ((a) < (b) ? (a) : (b)) +#define PIN(a,b,c) MIN(MAX(a,b),c) +#define NUMBEROF(a) (sizeof(a)/sizeof((a)[0])) +#define FLAG(a) (1L << (a)) +#define TEST_FLAG(a,b) ((a) & FLAG(b)) +#define UNICODE_STRING_LIST_TAG 1 +enum { _widget_dpad_updown_tabs_thru_children_bit=3, + _widget_dpad_leftright_tabs_thru_children_bit, + _widget_dpad_updown_tabs_thru_list_items_bit, + _widget_dpad_leftright_tabs_thru_list_items_bit, + _widget_pass_unhandled_events_to_children_bit }; +enum { _ui_widget_type_spinner_list=2, _ui_widget_type_column_list=3 }; +enum { _widget_event_dpad_up=8, _widget_event_dpad_down, + _widget_event_dpad_left, _widget_event_dpad_right }; +struct widget_instance { + long definition_tag_index; char const *name; short type; boolean disabled; + struct widget_instance *parent, *child, *next, *focused_child; + union { struct { short selected_index; void *list_items; long number_of_items; } list; + struct { short string_list_index; } text_box; } parameters; + struct { short current_frame_index, number_of_sprite_frames; } animation; +}; +struct ui_widget_definition { long flags; struct { long count; } event_handlers; } definitions[6]; +struct string_list { struct { long count; } strings; } strings, headings; +static struct ui_widget_definition *ui_widget_definition_get(long n) { return &definitions[n]; } +static boolean ui_mouse_list_shows_several(struct widget_instance *w) { (void)w; return FALSE; } +static long ui_mouse_child_index(struct widget_instance *w) { return w && w->parent ? 0 : NONE; } +static boolean widget_instance_can_receive_events(struct widget_instance *w) { return !w->disabled; } +char *tag_get_name(long n) { + return n==1 ? "pc\\main_menu\\changelog\\build_1" : n==2 ? "pc\\main_menu\\changelog\\build_2" : n==4 ? "pc\\main_menu\\main_menu" : "pc\\main_menu\\settings"; +} +static int missing_tag, missing_heading; +static long heading_count=-1; +static long tag_loaded(long type, char const *name) { + (void)type; + if(strstr(name,"\\headings")) return missing_heading ? NONE : 2; + assert(strstr(name,"\\lines")); return missing_tag ? NONE : 1; +} +static struct string_list *test_strings(long n) { + if(n==1) return &strings; + assert(n==2); headings.strings.count=heading_count<0 ? strings.strings.count : heading_count; return &headings; +} +#define unicode_string_list_definition_get(n) test_strings(n) +static wchar_t position[64]; +static struct widget_instance *named(struct widget_instance *root, char const *name, long nth) { + struct widget_instance *child; + if(!root) return NULL; + for(child=root->child;child;child=child->next) + if(!strcmp(child->name,name) && nth--==0) return child; + return NULL; +} +static void text_set(struct widget_instance *text, wchar_t const *value) { + long n=0; if(text) do { position[n]=value[n]; } while(value[n++]); +} +static int position_is(char const *value) { + long n=0; do { if(position[n]!=(unsigned char)value[n]) return 0; } while(value[n++]); return 1; +} +static long halo_menus_utf16(char const *text, unsigned short *out, long capacity) { + long n=0; while(text[n] && n+1child;p;p=p->next)if(!strcmp(p->name,name))return p; return 0; @@ -143,15 +142,11 @@ def test_pending_menu_filter_visibility_and_focus(tmp_path): styles[0].parameters.list.selected_index=-1;controller_button_rows_show(&list);assert(!bumper.visible); styles[0].parameters.list.selected_index=12;controller_button_rows_show(&list);assert(!bumper.visible); automatic.parameters.list.selected_index=0;family=99;controller_button_rows_show(&list);assert(r[0].visible); - keyboard=1;keyboard_option.parameters.list.selected_index=1;controller_button_rows_show(&list);assert(r[0].visible&&!detected.visible); - keyboard_option.parameters.list.selected_index=0;list.focused_child=&r[0];controller_button_rows_show(&list); + keyboard=1;list.focused_child=&r[0];controller_button_rows_show(&list); assert(detected.visible&&!bumper.visible&&list.focused_child==&detected); for(i=0;i<4;i++)assert(!r[i].visible); automatic.parameters.list.selected_index=1;controller_button_rows_show(&list); assert(!detected.visible&&r[0].visible&&list.focused_child==&r[0]); - automatic.parameters.list.selected_index=0;controller_button_rows_show(&list);assert(detected.visible); - keyboard_option.parameters.list.selected_index=1;controller_button_rows_show(&list);assert(r[0].visible&&!detected.visible); - automatic.parameters.list.selected_index=1;styles[0].parameters.list.selected_index=11;controller_button_rows_show(&list);assert(!bumper.visible); return 0; } ''' @@ -185,10 +180,12 @@ def test_menu_generated_and_default_on(): menu = ET.parse(ROOT / f'port/assets/menus/ce/{prefix}.controller_appearance.xml') labels = [w for w in menu.getroot().findall('widget') if '/hud_button_style' in w.get('name', '') and w.get('name', '').endswith('_label')] + assert not any(w.get('setting') in ('display.keyboard_glyphs', 'display.detected_button_style') for w in menu.getroot().findall('widget')) assert len(labels) == 4 assert all('string_list' not in w.attrib and 'string_index' in w.attrib for w in labels) rows = port_settings.SCREENS['controller_appearance']['rows'] assert len(next(r[2] for r in rows if r[1] == 'display.hud_button_style')) == 12 + assert next(r[2] for r in rows if r[1] == 'display.hud_button_style')[-1] == ('KEYBOARD', 'keyboard') assert next(r[2] for r in rows if r[1] == 'display.hud_bumper_style') == [('ORIGINAL XBOX', 'original'), ('MODERN XBOX', 'modern')] parent = ET.parse(ROOT / f'port/assets/menus/ce/{prefix}.gamepad_setup.xml') assert any('controller_appearance_screen' in e.get('open', '') for e in parent.iter('on')) @@ -214,9 +211,8 @@ def test_real_glyph_geometry_opacity_cache_and_teardown(tmp_path): #define NONE (-1) #define TRUE 1 #define FALSE 0 -typedef int boolean;typedef float real;typedef unsigned long pixel32; +typedef int boolean;typedef float real;typedef struct {real x0,y0,x1,y1;}real_rectangle2d;typedef unsigned long pixel32; typedef struct {short x0,y0,x1,y1;}rectangle2d; -typedef struct {real x0,y0,x1,y1;}real_rectangle2d; struct bitmap_data {unsigned long *hardware_format;}; struct icon_hud_element_definition {short frame_rate;unsigned flags;pixel32 color;}; struct dynamic_screen_vertex {struct {real x,y;}position,texture_coordinates;pixel32 color;}; @@ -231,8 +227,7 @@ def test_real_glyph_geometry_opacity_cache_and_teardown(tmp_path): static int controller_button_style_for_port(short p){observed_port=p;return 4;} static char const *bumper_style="original"; static char const *config_string(char const *s){assert(!strcmp(s,"display.hud_bumper_style"));return bumper_style;} -static int players=1,allocations,live,draws,fail,unbound;static long ticks,last_asset; -static void unbind(unsigned long const *p){assert(p);unbound++;} +static int players=1,allocations,live,draws,unbound,fail;static long ticks,last_asset; static struct dynamic_screen_vertex drawn[4]; static long game_time_get(void){return ticks;} static int local_player_count(void){return players;} @@ -243,6 +238,7 @@ def test_real_glyph_geometry_opacity_cache_and_teardown(tmp_path): } static int rasterizer_bitmap_new(struct bitmap_data *b){b->hardware_format=(unsigned long*)b;return fail!=2;} static void bitmap_delete(struct bitmap_data *b){free(b);live--;} +static void unbind(unsigned long const *p){assert(p);unbound++;} static void rasterizer_psuedo_dynamic_screen_quad_draw(struct rasterizer_dynamic_screen_geometry_parameters *p, struct dynamic_screen_vertex *v){assert(p->framebuffer_blend_function==0);memcpy(drawn,v,sizeof(drawn));draws++;} ''' @@ -259,8 +255,8 @@ def test_real_glyph_geometry_opacity_cache_and_teardown(tmp_path): bumper_style="modern"; for(players=1;players<=2;players++)for(style=0;style<11;style++)for(index=0;index<18;index++)for(frame=0;frame<3;frame++){ cursor.x0=100;cursor.y0=50;cursor.x1=500;cursor.y1=150;ticks=frame*10; - if((style<3 && index!=4 && index!=5) || (index>=8 && index<14)){before=draws;assert(!controller_glyph_draw(style,index,&icon,&cursor,0x7fffffff));assert(draws==before&&cursor.x0==100);continue;} - assert(controller_glyph_draw(style,index,&icon,&cursor,0x7fffffff));assert(drawn[0].color==0x7fffffff); + if((style<3 && index!=4 && index!=5) || (index>=8 && index<14)){before=draws;assert(!controller_glyph_draw_with_release(style,index,&icon,&cursor,0x7fffffff,unbind));assert(draws==before&&cursor.x0==100);continue;} + assert(controller_glyph_draw_with_release(style,index,&icon,&cursor,0x7fffffff,unbind));assert(drawn[0].color==0x7fffffff); scale=players==1?1:.75f; bounds=controller_glyph_assets[controller_glyph_asset_index(style,index<6?index:hud_button_control_slot(index,frame))].bounds; w=drawn[2].position.x-drawn[0].position.x;h=drawn[2].position.y-drawn[0].position.y; @@ -271,37 +267,47 @@ def test_real_glyph_geometry_opacity_cache_and_teardown(tmp_path): assert((bounds[2]-bounds[0])*w/512<=cellw+.001f && (bounds[3]-bounds[1])*h/512<=cellh+.001f); assert(cursor.x0==100+(short)((index<4?22:index<6?20:index<8?45:33)*scale)); before=allocations;icon.flags=2;icon.color=0x40123456; - assert(controller_glyph_draw(style,index,&icon,&cursor,0xffffffff));assert(drawn[0].color==0x40ffffff&&before==allocations);icon.flags=0; + assert(controller_glyph_draw_with_release(style,index,&icon,&cursor,0xffffffff,unbind));assert(drawn[0].color==0x40ffffff&&before==allocations);icon.flags=0; + } + /* Menu layout uses the same assets but a smaller footer cell, independent + * of split-screen HUD scale, with at least six units before its caption. */ + for(players=1;players<=2;players++)for(style=3;style<11;style++)for(index=0;index<18;index++){ + if(index>3&&index!=16)continue; + cursor.x0=100;assert(controller_glyph_draw_menu(style,index,&cursor,0x7fffffff)); + bounds=controller_glyph_assets[controller_glyph_asset_index(style,index==16?8:index)].bounds; + w=drawn[2].position.x-drawn[0].position.x;h=drawn[2].position.y-drawn[0].position.y; + x=drawn[0].position.x+bounds[2]*w/512; + y=drawn[0].position.y+(bounds[1]+bounds[3])*h/1024; + near(y,100);assert(cursor.x0-x>=5.99f); + assert((bounds[3]-bounds[1])*h/512<=22.001f); } - assert(live==62 && allocations==62);controller_glyphs_dispose();assert(!live); - controller_glyphs_dispose();assert(!live); + assert(live==62 && allocations==62);controller_glyphs_dispose();assert(!live && unbound==62); + controller_glyphs_dispose();assert(unbound==62); /* Only black/RB and white/LB change. All three styles share the modern * artwork cache, including after preference changes and map teardown. */ for(i=0;i<10;i++)for(style=0;style<3;style++)for(index=0;index<18;index++){ - bumper_style="original";assert(!controller_glyph_draw(style,index,&icon,&cursor,0)); + bumper_style="original";assert(!controller_glyph_draw_with_release(style,index,&icon,&cursor,0,unbind)); bumper_style="modern";before=draws; - assert(controller_glyph_draw(style,index,&icon,&cursor,0)==(index==4||index==5)); + assert(controller_glyph_draw_with_release(style,index,&icon,&cursor,0,unbind)==(index==4||index==5)); if(index==4||index==5){assert(draws==before+1);assert(controller_glyph_asset_index(style,index)==32+index-4);} } assert(live==2);controller_glyphs_dispose();assert(!live); - bumper_style="invalid";assert(!controller_glyph_draw(0,4,&icon,&cursor,0)); + bumper_style="invalid";assert(!controller_glyph_draw_with_release(0,4,&icon,&cursor,0,unbind)); bumper_style="original"; - for(i=1;i<=2;i++){fail=i;assert(!controller_glyph_draw(4,0,&icon,&cursor,0));assert(!live);controller_glyphs_dispose();} - fail=0;assert(controller_glyph_draw(4,0,&icon,&cursor,0));assert(drawn[0].color==0xffffff); - for(style=-1;style<3;style++)assert(!controller_glyph_draw(style,0,&icon,&cursor,0)); - assert(!controller_glyph_draw(11,0,&icon,&cursor,0));controller_glyphs_dispose();assert(!live); - /* A menu can allocate first; MCC's later binding must survive ordinary draws - * until the shared cache unbinds it before deleting the bitmap. */ - {real_rectangle2d uv; - assert(controller_glyph_bitmap(4,0,&uv));before=allocations; + for(i=1;i<=2;i++){fail=i;assert(!controller_glyph_draw_with_release(4,0,&icon,&cursor,0,unbind));assert(!live);controller_glyphs_dispose();} + fail=0;assert(controller_glyph_draw_with_release(4,0,&icon,&cursor,0,unbind));assert(drawn[0].color==0xffffff); + for(style=-1;style<3;style++)assert(!controller_glyph_draw_with_release(style,0,&icon,&cursor,0,unbind)); + assert(!controller_glyph_draw_with_release(11,0,&icon,&cursor,0,unbind));controller_glyphs_dispose();assert(!live); + /* A PC-menu allocation is reused by modern menus and later MCC gameplay; + * the late binding must still be released at map teardown. */ + { + real_rectangle2d uv;struct bitmap_data *shared;int saved_unbound=unbound; + shared=controller_glyph_bitmap(4,0,&uv);assert(shared&&live==1); + before=allocations;assert(controller_glyph_draw_menu(4,0,&cursor,0)); assert(controller_glyph_draw_with_release(4,0,&icon,&cursor,0,unbind)); - assert(controller_glyph_bitmap(4,0,&uv)); - assert(controller_glyph_draw(4,0,&icon,&cursor,0)); - assert(allocations==before&&!unbound); - controller_glyphs_dispose();assert(!live&&unbound==1); - controller_glyphs_dispose();assert(unbound==1); - assert(controller_glyph_bitmap(4,0,&uv)); - controller_glyphs_dispose();assert(!live&&unbound==1); + assert(controller_glyph_bitmap(4,0,&uv)==shared&&allocations==before); + assert(uv.x0>=0&&uv.x1<=1&&uv.x1>uv.x0); + controller_glyphs_dispose();assert(!live&&unbound==saved_unbound+1); } return 0; diff --git a/tools/test_controller_remap.py b/tools/test_controller_remap.py index 13a5cec5d6..6f87917dd4 100644 --- a/tools/test_controller_remap.py +++ b/tools/test_controller_remap.py @@ -82,12 +82,15 @@ def test_camera_cycle_layout_versions_and_conflicts(tmp_path): unsigned char a[CONTROLLER_REMAP_ACTIONS],b[CONTROLLER_REMAP_ACTIONS]; char old[512],text[512];char *last;int port; controller_remap_defaults(a);controller_remap_format(a,text,sizeof(text)); - assert(!strncmp(text,"v3:",3));assert(controller_remap_parse(text,b) && b[PAD_CAMERA_CYCLE]==4); - strcpy(old,text);old[1]='2';last=strrchr(old,',');assert(last);*last=0; + assert(!strncmp(text,"v4:",3));assert(controller_remap_parse(text,b) && b[PAD_CAMERA_CYCLE]==4); + strcpy(old,text);old[1]='3';*strrchr(old,',')=0;*strrchr(old,',')=0; + assert(controller_remap_parse(old,b) && !memcmp(a,b,sizeof(a))); + old[1]='2';last=strrchr(old,',');assert(last);*last=0; assert(controller_remap_parse(old,b) && !memcmp(a,b,sizeof(a))); /* Existing debug RB bindings win over the newly introduced default. */ controller_remap_assign(a,PAD_CAMERA_UP,4);assert(a[PAD_CAMERA_CYCLE]==255); - controller_remap_format(a,text,sizeof(text));text[1]='2';*strrchr(text,',')=0; + controller_remap_format(a,text,sizeof(text));text[1]='2'; + *strrchr(text,',')=0;*strrchr(text,',')=0;*strrchr(text,',')=0; assert(controller_remap_parse(text,b) && b[PAD_CAMERA_UP]==4 && b[PAD_CAMERA_CYCLE]==255); assert(!memcmp(a,b,sizeof(a))); /* Modern layouts must not receive the ten-action P2-P4 movement migration. */ @@ -175,6 +178,66 @@ def test_physical_remap_preserves_pressure_profile_menu_and_other_inputs(tmp_pat ''') +def test_camera_perspective_physical_input_and_host_policy(tmp_path): + common = COMMON.replace('config_string(', 'layout_string(').replace('config_write(', 'layout_write(') + update = function((ROOT / 'port/linux/game/third_person_policy.c').read_text(), 'third_person_input_update') + run_c(tmp_path, common + r''' +static int perspective,shoulder,policy,writes; +static char const *config_string(char const *name){return layout_string(name);} +static int config_write(char const *name,char const *value){ + if(!strcmp(name,"display.third_person"))perspective=!strcmp(value,"true"); + else if(!strcmp(name,"display.third_person_left_shoulder"))shoulder=!strcmp(value,"true"); + else return layout_write(name,value); + writes++;return 1; +} +static int config_boolean(char const *name){return !strcmp(name,"display.third_person")?perspective:shoulder;} +enum {_third_person_player_choice=0}; +static int third_person_policy(void){return policy;} +static int third_person_enabled(void){return policy==1 || (!policy && perspective);} +static unsigned long keys; +static unsigned long halo_keyboard_actions(short p){return keys;} +''' + POLICY + INPUT + source('port/linux/src/controller_remap_input.c') + + source('port/linux/include/halo_keyboard.h') + update + r''' +static void poll(short port,int button,int connected){ + XINPUT_GAMEPAD pad={0}; + if(button>=0){if(button<8)pad.bAnalogButtons[button]=255;else pad.wButtons=digital_masks[button-8];} + controller_remap_input(port,&pad,connected);third_person_input_update(); +} +int main(void){ + unsigned char b[CONTROLLER_REMAP_ACTIONS];char text[512];int port,saved; + for(port=0;port<4;port++){ + controller_remap_defaults(b); + assert(b[PAD_TOGGLE_PERSPECTIVE]==255 && b[PAD_SWAP_SHOULDER]==255); + controller_remap_assign(b,PAD_TOGGLE_PERSPECTIVE,0); + controller_remap_assign(b,PAD_SWAP_SHOULDER,1); + assert(b[PAD_JUMP]==255 && b[PAD_MELEE]==255); + controller_remap_assign(b,PAD_CAMERA_SWITCH,0); /* Debug may share the physical button. */ + assert(b[PAD_TOGGLE_PERSPECTIVE]==0); + controller_remap_format(b,text,sizeof(text));config_write(controller_remap_setting(port),text); + perspective=shoulder=0;poll(port,-1,1); + poll(port,0,1);assert(perspective==1);saved=writes; + poll(port,0,1);third_person_input_update();assert(writes==saved); + poll(port,-1,1);poll(port,1,1);assert(shoulder==1); + poll(port,-1,1);policy=2;saved=writes;poll(port,0,1);poll(port,1,1);assert(writes==saved); + policy=0;poll(port,-1,1);poll(port,0,1);assert(!perspective); + poll(port,-1,1);saved=writes;poll(port,1,1);assert(writes==saved); /* No shoulder swap in first person. */ + menu[port]=1;poll(port,0,1);assert(writes==saved); + menu[port]=0;poll(port,0,1);assert(writes==saved); /* Release after menus. */ + poll(port,-1,1);poll(port,0,1);assert(perspective); + poll(port,-1,1);camera[port]=2;poll(port,-1,1);saved=writes; + poll(port,0,1);poll(port,1,1);assert(writes==saved); /* Debug controls cannot change perspective. */ + camera[port]=1;poll(port,-1,1);poll(port,0,1);assert(writes==saved); /* Debug switch takes priority. */ + camera[port]=0;poll(port,-1,1);poll(port,0,0);poll(port,0,1);assert(writes==saved); + poll(port,-1,1);poll(port,0,1);assert(!perspective); + poll(port,-1,1); + } + /* Simultaneous keyboard/controller presses toggle once, not twice. */ + keys=1UL< +#include +#include +#include +#include +#include +/* Exercise the portable SDL backend, also on Linux CI. */ +#undef __linux__ +''' +SDL = r''' +typedef unsigned long long Uint64; +typedef unsigned int SDL_JoystickID, SDL_PropertiesID; +typedef int SDL_SpinLock; +typedef struct SDL_Gamepad { unsigned id; int vendor, product, wireless, index; } SDL_Gamepad; +static SDL_Gamepad devices[2]={{1,0x054c,0x0ce6,1,2},{2,0x054c,0x0df2,0,-1}}; +static Uint64 now; +static int triggers=1, lights, fail, fail_led, attempts, sent, rgb[3]; +static unsigned long changes; +static unsigned char reports[1000][47]; +static Uint64 sent_at[1000]; +static unsigned long config_changes(void){return changes;} +static int config_boolean(char const *key){return triggers;} +static char const *config_string(char const *key){return !strcmp(key,"input.lightbar")?(lights?"player_color":"off"):"normal";} +static void platform_log(char const *fmt,...){(void)fmt;} +static void SDL_LockSpinlock(SDL_SpinLock *l){(void)l;} +static void SDL_UnlockSpinlock(SDL_SpinLock *l){(void)l;} +static Uint64 SDL_GetTicks(void){return now;} +static void SDL_Delay(unsigned ms){now+=ms;} +static SDL_JoystickID SDL_GetGamepadID(SDL_Gamepad *g){return g->id;} +static SDL_Gamepad *SDL_GetGamepadFromID(SDL_JoystickID id){return id==1?devices:id==2?devices+1:NULL;} +static char const *SDL_GetGamepadName(SDL_Gamepad *g){return "simulated";} +static SDL_PropertiesID SDL_GetGamepadProperties(SDL_Gamepad *g){return 1;} +#define SDL_PROP_GAMEPAD_CAP_RGB_LED_BOOLEAN "led" +static int SDL_GetBooleanProperty(unsigned p,char const *key,int fallback){return 1;} +static int SDL_GetGamepadVendor(SDL_Gamepad *g){return g->vendor;} +static int SDL_GetGamepadProduct(SDL_Gamepad *g){return g->product;} +#define SDL_JOYSTICK_CONNECTION_WIRELESS 1 +static int SDL_GetGamepadConnectionState(SDL_Gamepad *g){return g->wireless;} +#define SDL_GAMEPAD_AXIS_RIGHT_TRIGGER 0 +#define SDL_GAMEPAD_AXIS_LEFT_TRIGGER 1 +static int SDL_GetGamepadAxis(SDL_Gamepad *g,int axis){return 0;} +static int SDL_GetGamepadPlayerIndex(SDL_Gamepad *g){return g->index;} +static int SDL_SendGamepadEffect(SDL_Gamepad *g,void const *body,int size){ + attempts++; if(fail)return 0; assert(size==47 && sent<1000); + memcpy(reports[sent],body,47);sent_at[sent++]=now;return 1; +} +static int SDL_SetGamepadLED(SDL_Gamepad *g,unsigned char r,unsigned char v,unsigned char b){ + rgb[0]=r;rgb[1]=v;rgb[2]=b;return !fail && !fail_led; +} +static int SDL_SetGamepadPlayerIndex(SDL_Gamepad *g,int index){g->index=index;return !fail;} +static char const *SDL_GetError(void){return "simulated busy";} +''' +HELPERS = r''' +static struct dualsense_wish pistol(void){ + struct dualsense_wish w={0};struct dualsense_weapon_state state={0}; + state.kind=DUALSENSE_WEAPON_SEMI;w.playing=1;w.context=1;w.kick_trigger=1; + dualsense_right_held(w.right,&state,100);dualsense_effect_off(w.left); + w.kick_ms=dualsense_event(w.kick,state.kind,DUALSENSE_EVENT_SHOT,100);return w; +} +static void frame(int port,struct dualsense_wish *w,Uint64 time){now=time;dualsense_wish_set(port,w);dualsense_frame();} +static void connect(void){dualsense_port(0,devices,0,0);now=900;dualsense_frame();sent=attempts=0;} +''' + + +@pytest.mark.parametrize('offset', [1, 10, 34, 49]) +def test_bluetooth_kick_waits_for_delivery(tmp_path, offset): + run_c(tmp_path, COMMON + RULES + HEADER + SDL + PLATFORM + HELPERS + r''' +int main(void){struct dualsense_wish w=pistol();connect(); + frame(0,&w,1000);w.kicks=1;frame(0,&w,1000+OFFSET); + frame(0,&w,1049);assert(sent==1); + frame(0,&w,1050);assert(sent==2 && !memcmp(reports[1]+10,w.kick,11)); + assert(pads[0].kick_until==1085 && !pads[0].kick_pending); + frame(0,&w,1086);assert(sent==2);frame(0,&w,1100); + assert(sent==3 && !memcmp(reports[2]+10,w.right,11));return 0;} +'''.replace('OFFSET', str(offset))) + + +@pytest.mark.parametrize('cancel', ['pause', 'context', 'stale', 'disable']) +def test_pending_kicks_cancel_on_context_change(tmp_path, cancel): + action = { + 'pause': 'w.playing=0;frame(0,&w,1050);assert(reports[sent-1][10]==5);', + 'context': 'w.context++;frame(0,&w,1050);', + 'stale': 'now=1400;dualsense_frame();assert(reports[sent-1][10]==5);', + 'disable': 'triggers=0;changes++;now=1020;dualsense_frame();assert(reports[sent-1][10]==5);' + }[cancel] + run_c(tmp_path, COMMON + RULES + HEADER + SDL + PLATFORM + HELPERS + r''' +int main(void){struct dualsense_wish w=pistol();connect();frame(0,&w,1000); + w.kicks++;frame(0,&w,1001);assert(pads[0].kick_pending); + ACTION + assert(!pads[0].kick_pending && !pads[0].kick_until);return 0;} +'''.replace('ACTION', action)) + + +def test_busy_retry_left_trigger_and_reset(tmp_path): + run_c(tmp_path, COMMON + RULES + HEADER + SDL + PLATFORM + HELPERS + r''' +int main(void){struct dualsense_wish w=pistol();unsigned char held[11];connect(); + w.kick_trigger=2;memcpy(held,w.right,11);memcpy(w.left,held,11);dualsense_effect_off(w.right); + frame(0,&w,1000);w.kicks++;fail=1;frame(0,&w,1050); + assert(pads[0].kick_pending && !pads[0].kick_until && sent==1); + frame(0,&w,1099);assert(attempts==2);fail=0;frame(0,&w,1100); + assert(sent==2 && reports[1][10]==5 && !memcmp(reports[1]+21,w.kick,11)); + assert(pads[0].kick_until==1135); + fail=1;triggers=0;changes++;now=1101;dualsense_frame();assert(pads[0].reset_pending); + fail=0;now=1102;dualsense_frame();assert(!pads[0].reset_pending && reports[sent-1][21]==5); + triggers=1;changes++;now=1103;dualsense_frame();assert(!pads[0].kick_until);return 0;} +''') + + +def test_no_replay_on_rebinding_or_clear_and_restore_lights(tmp_path): + run_c(tmp_path, COMMON + RULES + HEADER + SDL + PLATFORM + HELPERS + r''' +int main(void){struct dualsense_wish w=pistol();connect();lights=1;changes++; + w.red=100;w.player_lights=dualsense_player_lights(1);frame(0,&w,1000); + assert(devices[0].index==0 && rgb[0]==100); + w.kicks++;frame(0,&w,1001);dualsense_port(1,devices,0,0); + assert(!shared.wished[0] && !shared.wished[1] && !shared.bound[0]); + now=1050;dualsense_frame();assert(!pads[0].kick_pending && !pads[0].kick_until); + frame(1,&w,1100);assert(!pads[0].kick_until); + dualsense_clear();now=1150;dualsense_frame();now=1151;dualsense_frame(); + assert(reports[sent-1][10]==5 && devices[0].index==2 && rgb[0]==0 && rgb[1]==64 && rgb[2]==0); + dualsense_removed(devices);assert(!shared.wished[1] && !shared.active[1]);return 0;} +''') + + +def test_busy_light_restore_keeps_original_player_index(tmp_path): + run_c(tmp_path, COMMON + RULES + HEADER + SDL + PLATFORM + HELPERS + r''' +int main(void){struct dualsense_wish w=pistol();connect();lights=1;changes++; + w.red=100;w.player_lights=dualsense_player_lights(1);frame(0,&w,1000); + assert(devices[0].index==0);dualsense_clear();now=1050;dualsense_frame(); + fail=1;now=1100;dualsense_frame();assert(pads[0].reset_pending && pads[0].lights_owned); + assert(devices[0].index==2);fail=0;now=1150;dualsense_frame(); + assert(!pads[0].lights_owned && devices[0].index==2 && rgb[1]==64); + now=1200;dualsense_frame();assert(!pads[0].reset_pending && devices[0].index==2);return 0;} +''') + + +def test_partial_first_batch_keeps_reset_while_other_feature_runs(tmp_path): + run_c(tmp_path, COMMON + RULES + HEADER + SDL + PLATFORM + HELPERS + r''' +int main(void){struct dualsense_wish w=pistol();lights=1;fail_led=1; + dualsense_port(0,devices,0,0);w.player_lights=dualsense_player_lights(1); + frame(0,&w,1000);assert(sent==1 && !pads[0].link.known); + triggers=0;changes++;fail=1;now=1050;dualsense_frame(); + assert(pads[0].reset_pending & DUALSENSE_FIELD_TRIGGERS); + fail=fail_led=0;now=1100;dualsense_frame(); + assert(!pads[0].reset_pending && sent==2 && reports[1][10]==5);return 0;} +''') + + +def test_other_controllers_and_default_off_are_untouched(tmp_path): + run_c(tmp_path, COMMON + RULES + HEADER + SDL + PLATFORM + HELPERS + r''' +int main(void){struct dualsense_wish w=pistol();triggers=0;connect();frame(0,&w,1000);assert(!sent && !attempts); + triggers=1;changes++;devices[0].vendor=123;now=1001;dualsense_frame();frame(0,&w,1100); + assert(!sent && !attempts && !dualsense_port_active(0));return 0;} +''') + + +GAME_SOURCE = (ROOT / 'port/linux/game/dualsense_game.c').read_text() +GAME_STATE = GAME_SOURCE[GAME_SOURCE.index('/* Game-thread history'):GAME_SOURCE.index('static void clear_round')] +GAME = GAME_STATE + '\n'.join(function(GAME_SOURCE, name) for name in ( + 'channel', 'clear_round', 'dualsense_game_reset', 'mapped_effect', 'dualsense_player', 'dualsense_game_update')) +GAME_FAKE = r''' +#define NONE (-1) +#define MAXIMUM_LOCAL_PLAYERS 4 +typedef float real; +typedef struct {float red,green,blue;} real_rgb_color; +struct player_datum {long unit_index;short local_player_index;}; +struct unit_datum {struct {short current_weapon_index,current_grenade_index,grenade_throw_state;} unit;}; +struct weapon_datum {struct {long game_time_last_fired;} weapon;}; +enum {_unit_grenade_throw_wind_up=1,_unit_grenade_throw_in_hand=2}; +static struct player_datum players[4]={{10,0},{11,1},{12,2},{13,3}}; +static struct unit_datum units[4]; +static struct weapon_datum weapons[4]; +static struct dualsense_weapon_state states[4]; +static unsigned char mappings[4][CONTROLLER_REMAP_ACTIONS]; +static struct dualsense_wish wishes[4]; +static struct dualsense_settings settings={1,100,0}; +static int paused,menu,inhibited,blocked[4],live[4]={1,1,1,1},active[4]={1,1,1,1},custom=1,cleared; +static int ticks=100; +static struct player_datum *player_get(long id){assert(id>=0 && id<4);return players+id;} +static struct unit_datum *unit_get(long id){assert(id>=10 && id<14);return units+id-10;} +static struct weapon_datum *weapon_get(long id){assert(id>=20 && id<24);return weapons+id-20;} +static long local_player_get_player_index(short local){return live[local]?local:NONE;} +static short controller_remap_local_player(short port){return live[port]?port:NONE;} +static int controller_remap_playing(short port){return !blocked[port];} +static int controller_remap_read(short port,unsigned char *layout){if(!custom)return 0;memcpy(layout,mappings[port],CONTROLLER_REMAP_ACTIONS);return 1;} +static void controller_remap_profile(short port,unsigned char *layout){memcpy(layout,mappings[port],CONTROLLER_REMAP_ACTIONS);} +static void controller_device_get(short port,struct controller_device *device){memset(device,0,sizeof(*device));device->instance=port+1;} +static struct dualsense_settings dualsense_settings_get(void){return settings;} +static int dualsense_port_active(int port){return active[port];} +static void dualsense_wish_set(int port,struct dualsense_wish const *wish){wishes[port]=*wish;} +static void dualsense_clear(void){memset(wishes,0,sizeof(wishes));cleared++;} +static int game_time_initialized(void){return 1;} +static int game_in_progress(void){return 1;} +static int main_menu_is_active(void){return menu;} +static int game_time_get_paused(void){return paused;} +static int game_time_get(void){return ticks;} +static int director_inhibited_input(short local){return inhibited;} +static int game_engine_running(void){return 0;} +static void game_engine_player_get_change_color(real_rgb_color *color,long player){assert(0);} +static short player_control_get_zoom_level(short local){return NONE;} +static long unit_inventory_get_weapon(long id,short slot){return id+10;} +static long seated_weapon(long unit,long weapon){return weapon;} +static int unit_get_grenade_count(long unit,int type){return 2;} +static void weapon_state(long weapon,struct dualsense_weapon_state *state){*state=states[weapon-20];} +static void setup(void){int i;for(i=0;i<4;i++){ + memset(mappings[i],255,CONTROLLER_REMAP_ACTIONS);mappings[i][PAD_FIRE]=7;mappings[i][PAD_GRENADE]=6; + states[i].kind=DUALSENSE_WEAPON_SEMI;weapons[i].weapon.game_time_last_fired=10; +}} +''' +# The header's public declarations apply to the fake engine definitions too. +GAME_FAKE = GAME_FAKE.replace('static struct dualsense_settings dualsense_settings_get', + 'struct dualsense_settings dualsense_settings_get') +for _name in ('dualsense_port_active', 'dualsense_wish_set', 'dualsense_clear', + 'controller_remap_local_player', 'controller_remap_playing', 'controller_remap_read', + 'controller_remap_profile', 'controller_device_get'): + GAME_FAKE = GAME_FAKE.replace('static int ' + _name, 'int ' + _name).replace( + 'static short ' + _name, 'short ' + _name).replace('static void ' + _name, 'void ' + _name) + + +def game_code(): + return COMMON + RULES + HEADER + source('port/linux/include/controller_remap.h') + \ + source('port/linux/include/controller_buttons.h') + GAME_FAKE + GAME + + +@pytest.mark.parametrize('reason', ['pause', 'menu', 'director', 'widgets', 'death', 'disconnect']) +def test_gameplay_suppression_cancels_history(tmp_path, reason): + block = { + 'pause': 'paused=1;', 'menu': 'menu=1;', 'director': 'inhibited=1;', + 'widgets': 'blocked[0]=1;', 'death': 'players[0].unit_index=NONE;', 'disconnect': 'active[0]=0;' + }[reason] + run_c(tmp_path, game_code() + r''' +int main(void){setup();dualsense_game_update();assert(wishes[0].playing && !wishes[0].kicks); + weapons[0].weapon.game_time_last_fired++;dualsense_game_update();assert(wishes[0].kicks==1); + BLOCK + dualsense_game_update();assert(!wishes[0].playing && !rounds[0].valid); + if(!menu)assert(wishes[0].right[0]==5 && wishes[0].left[0]==5); + paused=menu=inhibited=blocked[0]=0;players[0].unit_index=10;active[0]=1; + weapons[0].weapon.game_time_last_fired++;dualsense_game_update(); + assert(wishes[0].playing && !wishes[0].kicks);return 0;} +'''.replace('BLOCK', block)) + + +@pytest.mark.parametrize('custom', [0, 1]) +def test_physical_mapping_and_independent_ports(tmp_path, custom): + run_c(tmp_path, game_code() + r''' +int main(void){setup();custom=CUSTOM;mappings[0][PAD_FIRE]=6;mappings[0][PAD_GRENADE]=7; + mappings[1][PAD_FIRE]=0;mappings[1][PAD_GRENADE]=1; + dualsense_game_update();assert(wishes[0].kick_trigger==2 && wishes[0].left[0]==0x25); + assert(wishes[1].kick_trigger==0 && wishes[1].right[0]==5 && wishes[1].left[0]==5); + assert(wishes[2].kick_trigger==1 && wishes[2].right[0]==0x25); + weapons[0].weapon.game_time_last_fired++;dualsense_game_update();assert(wishes[0].kicks==1); + mappings[0][PAD_FIRE]=0;dualsense_game_update();assert(wishes[0].right[0]!=0x25 && wishes[0].left[0]==5); + assert(!wishes[0].kick_trigger && !wishes[0].kicks);return 0;} +'''.replace('CUSTOM', str(custom))) + + +def test_map_checkpoint_and_setting_resets_do_not_replay_shots(tmp_path): + run_c(tmp_path, game_code() + r''' +int main(void){unsigned long context;setup();dualsense_game_update();context=wishes[0].context; + weapons[0].weapon.game_time_last_fired++;dualsense_game_update();assert(wishes[0].kicks==1); + dualsense_game_reset();assert(cleared && !rounds[0].valid);dualsense_game_update(); + assert(wishes[0].context!=context && !wishes[0].kicks); + settings.triggers=0;dualsense_game_update();weapons[0].weapon.game_time_last_fired++; + settings.triggers=1;dualsense_game_update();assert(!wishes[0].kicks); + settings.triggers=0;settings.lights=1;dualsense_game_update();assert(!wishes[0].playing && wishes[0].player_lights); + settings.triggers=1;weapons[0].weapon.game_time_last_fired++;dualsense_game_update();assert(!wishes[0].kicks); + return 0;} +''') diff --git a/tools/test_frontend_menu.py b/tools/test_frontend_menu.py new file mode 100644 index 0000000000..ca859d2f2b --- /dev/null +++ b/tools/test_frontend_menu.py @@ -0,0 +1,781 @@ +"""Exercise the production frontend boundary and callbacks without retail maps.""" +from pathlib import Path +import json +import re +import xml.etree.ElementTree as ET + +import pytest + +import frontend_menu +import frontend_legacy +from harness import function +from test_hud_button_style import run_c + +ROOT = Path(__file__).resolve().parents[1] + + +def without_includes(path): + source = (ROOT / path).read_text() + for name in ('frontend_navigation.inl','frontend_multiplayer.inl','frontend_network_routes.inl','frontend_legacy_footers.inl'): + source = source.replace('#include "'+name+'"', (ROOT/'port/linux/game'/name).read_text()) + return re.sub(r'^#include .*$', '', source, flags=re.M) + + +HEADER = (ROOT / 'port/linux/game/frontend_menu.h').read_text() +POLICY = without_includes('port/linux/game/frontend_menu.c') + + +def test_policy_map_lifetime_and_fallback(tmp_path): + run_c(tmp_path, r''' +#include +#include +#include +#define NONE -1 +static char const *choice="off"; +static char const *legacy_choice="pc"; +static int tags, main_menu=1, network; +typedef int boolean; +boolean main_menu_is_active(void) {return main_menu;} +boolean network_game_is_active(void) {return network;} +static char const *tag_get_name(long tag) {return tag==4?"pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\player_profile_edit_screen":tag==2?"pc\\main_menu\\multiplayer_type_select\\multiplayer_type_select_screen":"unrelated";} +static int csstrcasecmp(char const *a,char const *b) { + while(*a&&tolower((unsigned char)*a)==tolower((unsigned char)*b)){a++;b++;} + return tolower((unsigned char)*a)-tolower((unsigned char)*b); +} +static char const *config_string(char const *key) {return !strcmp(key,"display.menus")?legacy_choice:choice;} +static long tag_loaded(long group,char const *name) {(void)group;(void)name;return tags ? 1 : NONE;} +void frontend_input_enable(int enabled) {(void)enabled;} +static int keyboard_disposals; +void keyboard_glyphs_dispose(void) {keyboard_disposals++;} +void frontend_menu_text_end(void) {} +void frontend_panel_end(void) {} +void frontend_menu_session_reset(void) {} +''' + HEADER + POLICY + r''' +int main(void) { + int i; + frontend_menu_map_loaded("ui",0);tags=1; + assert(!frontend_menu_available()); + choice="modern";assert(frontend_menu_reload_required()); + frontend_menu_map_loaded("ui",0);assert(!frontend_menu_reload_required()); + choice="xbox";assert(!frontend_menu_reload_required()); + choice="off";assert(frontend_menu_reload_required()); + frontend_menu_map_loaded("ui",0);assert(!frontend_menu_reload_required()); + frontend_menu_map_loaded("custom_maps\\test",0);choice="modern"; + assert(!frontend_menu_reload_required()); + frontend_menu_map_loaded("ui",1);assert(!frontend_menu_reload_required()); + choice="off";frontend_menu_map_loaded("ui",0); + assert(!strcmp(frontend_menu_root("stock"),"stock")); + for(i=0;i<100;i++) { + choice="modern";frontend_menu_map_loaded("ui",0); + assert(frontend_menu_available()); + assert(!strcmp(frontend_menu_root("stock"),"stock")); + assert(frontend_menu_destination(2)==1&&frontend_menu_destination(3)==3); + main_menu=0;assert(frontend_menu_destination(2)==2);main_menu=1; + network=1;assert(frontend_menu_destination(2)==2);network=0; + choice="xbox";assert(frontend_menu_destination(2)==2);assert(!strcmp(frontend_menu_root("stock"),FRONTEND_MENU_XBOX)); + choice="pc";assert(!strcmp(frontend_menu_root("stock"),FRONTEND_MENU_PC)); + tags=0;assert(!strcmp(frontend_menu_root("stock"),"stock"));tags=1; + legacy_choice="xbox";tags=0; + assert(!strcmp(frontend_menu_root(FRONTEND_MENU_PC),FRONTEND_MENU_XBOX)); + legacy_choice="XBOX";assert(!strcmp(frontend_menu_root(FRONTEND_MENU_PC),FRONTEND_MENU_XBOX)); + legacy_choice="pc";tags=1; + frontend_menu_unloaded();assert(!frontend_menu_available()); + frontend_menu_map_loaded("a10",0);assert(frontend_menu_available()); + choice="modern";assert(!strcmp(frontend_menu_style(),"pc")); + frontend_menu_map_loaded("custom_maps\\test",0);assert(frontend_menu_available()); + frontend_menu_map_loaded("ui",1);assert(!frontend_menu_available()&&frontend_menu_destination(2)==2); + frontend_menu_map_loaded("mcc_maps\\a10",1);assert(frontend_menu_available()); + frontend_menu_map_loaded("ui",0);assert(frontend_menu_available()); + } + assert(keyboard_disposals==100); + /* A paused save survives map-family transitions without changing live UI. */ + choice="modern";frontend_menu_map_loaded("ui",0);frontend_menu_unloaded();main_menu=0; + frontend_menu_map_loaded("a10",0);assert(frontend_menu_destination(4)==1); + choice="xbox";assert(!strcmp(frontend_menu_style(),"modern")); + assert(frontend_menu_destination(4)==1&&!frontend_menu_reload_required()); + frontend_menu_unloaded();frontend_menu_map_loaded("custom_maps\\test",0); + assert(!strcmp(frontend_menu_style(),"modern")); + frontend_menu_unloaded();frontend_menu_map_loaded("mcc_maps\\test",1); + assert(!strcmp(frontend_menu_style(),"modern")&&frontend_menu_destination(4)==1); + frontend_menu_unloaded();main_menu=1;frontend_menu_map_loaded("ui",0); + assert(!strcmp(frontend_menu_style(),"xbox")); + choice="off";frontend_menu_unloaded();main_menu=0;frontend_menu_map_loaded("a10",0); + assert(!frontend_menu_available()&&frontend_menu_destination(4)==4); + choice="modern";assert(!frontend_menu_requested()); + frontend_menu_unloaded();main_menu=1;frontend_menu_map_loaded("ui",0); + assert(frontend_menu_available()); + choice="invalid";frontend_menu_map_loaded("ui",0);assert(!frontend_menu_available()); + return 0; +} +''') + + +def test_runtime_guards_staging_cancel_failure_and_reentry(tmp_path): + source = without_includes('port/linux/game/frontend_menu_runtime.inl') + pages = (ROOT / 'port/linux/game/frontend_pages.inl').read_text() + run_c(tmp_path, RUNTIME_STUBS + HEADER + pages + source + r''' +int main(void) { + struct widget_instance root={0},spinner={0},child={0},item={0},list={0},rows[20]={{0}}; + struct event_record event={0};int deleted=0,i; + root.definition_tag_index=1;root.child=&child;child.parent=&root;child.name="legacy"; + frontend_menu_attach(&root);assert(!child.next&&!opens); /* starting menu stays untouched */ + child.type=3;child.child=&item; + event.type=3;event.data.button.index=3;event.data.button.value=1; + assert(frontend_menu_shortcut(&root,&event)); + event.data.button.value=2;assert(!frontend_menu_shortcut(&root,&event));event.data.button.value=1; + root.definition_tag_index=2;assert(frontend_menu_shortcut(&root,&event)); + root.definition_tag_index=4;assert(!frontend_menu_shortcut(&root,&event)); + root.definition_tag_index=3;root.child=&spinner;spinner.parent=&root;spinner.type=2;spinner.definition_tag_index=5; + spinner.parameters.list.selected_index=2; + assert(frontend_capture(&root));assert(frontend_session.count==1&&!writes); + /* Recreated page gets its pending value, including Cancel after a tab switch. */ + spinner.parameters.list.selected_index=0;frontend_restore(&spinner,&setting); + assert(spinner.parameters.list.selected_index==2); + assert(frontend_menu_event(&spinner,"port frontend cancel",&deleted)); + assert(!writes&&transitions==1&&!deleted&&!frontend_session.count); + fail=1;assert(!frontend_menu_event(&spinner,"port frontend apply",&deleted)); + assert(message==1&&transitions==1&&!display&&frontend_session.count==1); + fail=0;assert(frontend_menu_event(&spinner,"port frontend apply",&deleted)); + assert(transitions==2&&display==1&&!frontend_session.count); + /* Returning a choice to its baseline must not rewrite config. */ + spinner.parameters.list.selected_index=2;assert(frontend_capture(&root)); + spinner.parameters.list.selected_index=0;assert(frontend_capture(&root)); + i=writes;assert(frontend_commit()&&writes==i);frontend_menu_session_reset(); + spinner.parameters.list.selected_index=9;assert(!frontend_capture(&root)); + /* Keyboard focus can reach all 20 rows; rendering and pointer targets + contain only the eight-row window, including after a reverse/wrap. */ + root.child=&list;list.parent=&root;list.name="options";list.child=rows; + for(i=0;i<20;i++){rows[i].name="row_test";rows[i].visible=1;rows[i].parent=&list;rows[i].next=i<19?&rows[i+1]:0;} + list.focused_child=&rows[0];frontend_menu_help(&list); + assert(rows[0].vertical_offset==137&&frontend_menu_row_drawable(&rows[7])&&!frontend_menu_row_drawable(&rows[8])); + list.focused_child=&rows[19];frontend_menu_help(&list); + assert(frontend_session.first[0]==12&&!frontend_menu_row_drawable(&rows[11])&&frontend_menu_row_drawable(&rows[19])); + list.focused_child=&rows[2];frontend_menu_help(&list);assert(frontend_session.first[0]==2); + list.focused_child=&rows[0];frontend_menu_help(&list);assert(!frontend_session.first[0]); + /* Per-page offsets and pending values cannot leak past unload/reset. */ + frontend_session.first[1]=5;frontend_session.owns_profile=1;frontend_menu_session_reset(); + assert(!frontend_session.first[1]&&ended==1); + for(i=0;i<3;i++) { + available=0;main_menu=i!=1;network=i==2; + assert(!frontend_menu_event(&spinner,"port frontend apply",&deleted)); + root.definition_tag_index=1;assert(!frontend_menu_shortcut(&root,&event)); + root.definition_tag_index=3; + } + assert(writes==2&&transitions==2); + available=1;main_menu=0;network=1;root.child=&spinner; + spinner.parameters.list.selected_index=2;deleted=0; + assert(frontend_menu_event(&spinner,"port frontend apply",&deleted)); + assert(writes==3&&transitions==2&&backs==1&&deleted); + deleted=0;assert(frontend_menu_event(&spinner,"port frontend cancel",&deleted)); + assert(writes==3&&transitions==2&&backs==2&&deleted); + return 0; +} +''') + + +def test_paused_online_restrictions_keep_navigation_and_buttons(tmp_path): + stubs = RUNTIME_STUBS.replace('return id==1?', + 'return id==8?"pc\\\\modern\\\\paused\\\\online\\\\settings":id==1?') + stubs = stubs.replace('(void)root;(void)name;(void)n;return 0;', ''' + struct widget_instance *child,*found;(void)n; + if(!root)return 0; + if(root->name&&!strcmp(root->name,name))return root; + for(child=root->child;child;child=child->next){found=named(child,name,0);if(found)return found;} + return 0;''') + run_c(tmp_path, stubs + HEADER + (ROOT/'port/linux/game/frontend_pages.inl').read_text() + + without_includes('port/linux/game/frontend_menu_runtime.inl') + r''' +int main(void){ + struct widget_instance root={0},list={0},rows[7]={{0}};int i; + char const *names[]={"tabs","row_network_online0","row_link_9","row_link_10","row_link_11","button_bar","row_discord"}; + root.definition_tag_index=8;root.child=&list;list.parent=&root;list.name="options";list.child=rows; + for(i=0;i<7;i++){rows[i].name=names[i];rows[i].visible=1;rows[i].parent=&list;rows[i].next=i<6?rows+i+1:0;} + main_menu=0;list.focused_child=rows+1;frontend_menu_help(&list); + assert(rows[0].visible&&rows[5].visible); /* tab and footer navigation survive */ + assert(!rows[1].visible&&!rows[4].visible&&!rows[6].visible&&rows[2].visible&&rows[3].visible); + assert(list.focused_child==rows&&list.parameters.list.selected_index==0); + return 0; +} +''') + + +RUNTIME_STUBS = r''' +#define PIN(x,a,b) ((x)<(a)?(a):(x)>(b)?(b):(x)) +#include +#include +#include +#include +#include +#define NONE -1 +#define TRUE 1 +#define FALSE 0 +#define NUMBEROF(a) (sizeof(a)/sizeof((a)[0])) +#define MIN(a,b) ((a)<(b)?(a):(b)) +#define MAX(a,b) ((a)>(b)?(a):(b)) +#define ROW_TEXT_LENGTH 64 +#define _gamepad_analog_button_y 3 +typedef int boolean; +struct widget_instance { + long definition_tag_index;short local_player_index,horizontal_offset,vertical_offset,type; + char const *name;int visible,disabled;float alpha_modifier; + struct widget_instance *parent,*previous,*next,*child,*focused_child; + struct {struct {short selected_index;struct widget_instance *extended_description;} list; + struct {short string_list_index;wchar_t *text;} text_box;} parameters; + struct {short current_frame_index;} animation; +}; +struct controller_device {int family;}; +static int test_device=0; +static int frontend_input_device(void) {return test_device;} +static short controller_of(struct widget_instance *w) {(void)w;return 0;} +static void controller_device_get(short port,struct controller_device *d) {(void)port;d->family=0;} +static int controller_button_style_index(char const *name) {return strcmp(name,"classic")?3:0;} +struct event_record {short type,controller_index;struct {struct {unsigned char index,value;} button;} data;}; +/* MCC routing is covered independently by test_mcc_xbox_menu.py. */ +static void mcc_xbox_reset(void) {} +static void mcc_xbox_attach(struct widget_instance *w) {(void)w;} +static int mcc_xbox_shortcut(struct widget_instance *w,struct event_record *e) {(void)w;(void)e;return 0;} +struct pc_menu_setting {short value_count,loaded_index;char const *setting;char const *values[3];}; +static int available=1,main_menu=1,network=0,writes=0,transitions=0,opens=0,message=0,fail=0,display=0,ended=0; +static char const *config_string(char const *key) {(void)key;return "modern";} +static struct widget_instance entry={0}; +static struct pc_menu_setting setting={3,0,"display.menu_frontend",{"modern","pc","xbox"}}; +int frontend_menu_available(void) {return available;} +static int main_menu_is_active(void) {return main_menu;} +boolean network_game_is_active(void) {return network;} +static char const *tag_get_name(long id) {return id==1?"pc\\main_menu\\main_menu":id==2?"ui\\shell\\main_menu\\main_menu":id==3?"pc\\modern\\settings":id==7?"pc\\modern\\audio\\settings":"pc\\lobby";} +static struct widget_instance *ui_widget_load_by_name_or_tag(char const *name,long id,struct widget_instance *parent,short player,long a,long b,short c) { + (void)name;(void)id;(void)player;(void)a;(void)b;(void)c;opens++;entry.parent=parent;return &entry; +} +static int spinner_item(struct widget_instance *widget) {(void)widget;return 0;} +static struct pc_menu_setting *pc_menu_setting_get(long id) {return id==5?&setting:0;} +static int setting_write(char const *key,char const *value) {assert(!strcmp(key,"display.menu_frontend"));assert(!strcmp(value,"xbox"));writes++;return !fail;} +static struct widget_instance *screen_of(struct widget_instance *widget) {while(widget->parent)widget=widget->parent;return widget;} +static struct widget_instance *named(struct widget_instance *root,char const *name,int n) { + struct widget_instance *row;(void)n; + for(row=root->child;row;row=row->next) if(row->name&&!strcmp(row->name,name))return row; + return 0; +} +static void text_set(struct widget_instance *widget,wchar_t const *text) {(void)widget;if(wcsstr(text,L"Save failed"))message++;} +static void text_set_length(struct widget_instance *widget,wchar_t const *text,short length) {(void)length;text_set(widget,text);} +static void platform_display_apply(void) {display++;} +static void main_goto_main_menu(void) {transitions++;} +static int backs; +void ui_widget_port_go_back(struct widget_instance *w) {(void)w;backs++;} +static void *player_ui_get_edit_player_profile(void) {return 0;} +char const *frontend_menu_style(void) {return config_string("display.menu_frontend");} +static void visible_set(struct widget_instance *w,int v) {if(w)w->visible=v;} +static void player_ui_end_editing_profile(void) {ended++;} +static int player_ui_edit_profile_is_dirty(void) {return 0;} +static int player_ui_save_profile(void) {return 1;} +static int pc_menu_profile_edit_begin(void) {return 1;} +static int setting_load(struct widget_instance *widget) {widget->parameters.list.selected_index=0;setting.loaded_index=0;return 1;} +static boolean setting_default_show(struct widget_instance *widget,struct pc_menu_setting *s) {(void)widget;(void)s;return 1;} +static void settings_each(struct widget_instance *widget,boolean(*visit)(struct widget_instance *,struct pc_menu_setting *)) {(void)widget;(void)visit;} +static int game_function(char const *s,struct widget_instance *w,struct event_record *e,boolean *d) {(void)s;(void)w;(void)e;(void)d;return 1;} +boolean ui_widget_port_open(struct widget_instance *w,char const *s,boolean *d) {(void)w;(void)s;(void)d;return 1;} +boolean ui_widget_port_dispatch_event(struct widget_instance *w,short e,short c,boolean *d) {(void)w;(void)e;(void)c;(void)d;return 1;} +static void settings_help(struct widget_instance *w) {(void)w;} +static void master_servers_show(struct widget_instance *w) {(void)w;} +static int usnprintf(wchar_t *out,int n,wchar_t const *format,...) {(void)n;(void)format;out[0]=0;return 0;} +static long tag_loaded(long group,char const *path) {(void)group;(void)path;return -1;} +static wchar_t const *unicode_string_list_get_string(long tag,short i) {(void)tag;(void)i;return L"";} +''' + + +@pytest.mark.parametrize('broken', [0, 1]) +def test_separate_parser_cache_and_failure(tmp_path, broken): + legacy = function((ROOT / 'port/linux/src/menu_files.c').read_text(), 'halo_menus_load') + frontend = function((ROOT / 'port/linux/src/frontend_menu_files.inl').read_text(), 'frontend_menu_files_load') + run_c(tmp_path, r''' +#include +#include +#include +#include +struct halo_menus {int widget_count;char const *root;}; +struct reader {struct halo_menus menus;int failed;void *last_child,*last_handler,*last_input,*last_conditional,*last_replace;}; +struct menu_file {char const *path;}; +static struct menu_file files[]={{"ce/main.xml"},{"modern/settings.xml"},{"modern/panel.png"}}; +static int file_count=3,gathers=0,modern_reads=0,reads=0; +static void files_gather(void) {gathers++;} +static void read_file(struct reader *reader,struct menu_file *file) { + reads++;reader->menus.widget_count++;reader->menus.root="main_menu/main_menu"; + if(!strncmp(file->path,"modern/",7)) {modern_reads++;reader->failed=BROKEN;} +} +static void platform_log(char const *text) {(void)text;} +static int config_boolean(char const *key) {(void)key;return 1;} +static void changelog_menu_configure(struct halo_menus *menus,int enabled) {(void)menus;(void)enabled;} +'''.replace('BROKEN', str(broken)) + legacy + frontend + r''' +int main(void) { + struct halo_menus const *legacy=halo_menus_load(),*frontend; + assert(legacy&&legacy->widget_count==1&&!modern_reads); + frontend=frontend_menu_files_load();assert(frontend); + assert(gathers==1&&modern_reads==1&&reads==3); + assert(frontend_menu_files_load()==frontend&&halo_menus_load()==legacy&&reads==3); + assert(legacy->widget_count==1); + assert(frontend->widget_count==EXPECTED); + return 0; +} +'''.replace('EXPECTED', '1' if broken else '2')) + + +def test_interface_pending_hud_gate_family_changes_and_focus(tmp_path): + source = (ROOT / 'port/linux/game/frontend_menu_runtime.inl').read_text() + stubs = RUNTIME_STUBS.replace('d->family=0;', 'd->family=test_family;') + stubs = 'static int test_family;\n' + stubs.replace( + 'return id==5?&setting:0;', 'return id>=10&&id<19?&options[id-10]:id==5?&setting:0;') + stubs = stubs.replace('static int available=1', 'static struct pc_menu_setting options[9];\nstatic int available=1') + run_c(tmp_path, stubs + ''.join(function(source, name) for name in + ('frontend_setting_row', 'frontend_row_value', 'frontend_button_rows_show')) + r''' +int main(void) { + struct widget_instance list={0},rows[9]={{0}},spinners[9]={{0}}; + char const *keys[]={"display.high_res_hud","input.auto_button_detection", + "display.hud_button_style","display.hud_button_style_xbox","display.hud_button_style_ps", + "display.hud_button_style_switch","display.hud_bumper_style","unused","display.menu_button_glyphs"}; + int i,family,repeat; + list.child=rows; + for(i=0;i<9;i++) { + rows[i].child=&spinners[i];rows[i].visible=1;rows[i].next=i<8?&rows[i+1]:0; + spinners[i].type=2;spinners[i].definition_tag_index=10+i; + options[i].setting=keys[i];options[i].value_count=2; + options[i].values[0]=i<2?"true":"classic"; + options[i].values[1]=i<2?"false":"keyboard"; + } + options[8].values[0]="false";options[8].values[1]="true"; + rows[7].name="row_detected_button_style";spinners[7].type=1; + for(repeat=0;repeat<10;repeat++) for(family=-1;family<5;family++) { + int selected=family>0&&family<=3?family:0; + test_family=family;spinners[0].parameters.list.selected_index=0; + spinners[1].parameters.list.selected_index=0;list.focused_child=&rows[2]; + frontend_button_rows_show(&list); + assert(rows[1].visible&&!rows[7].visible&&rows[6].visible); + for(i=0;i<4;i++) assert(rows[2+i].visible==(i==selected)); + assert(list.focused_child==&rows[2+selected]); + assert(list.parameters.list.selected_index==2+selected); + /* Keyboard activity shows a read-only result, leaving pending choices intact. */ + test_device=-1;frontend_button_rows_show(&list); + assert(rows[7].visible&&!rows[6].visible&&list.focused_child==&rows[7]); + for(i=2;i<6;i++)assert(!rows[i].visible); + assert(!writes&&spinners[2].parameters.list.selected_index==0); + test_device=2;frontend_button_rows_show(&list); + assert(!rows[7].visible&&rows[2+selected].visible); + /* Manual mode restores its own choice, including Keyboard. */ + spinners[1].parameters.list.selected_index=1; + spinners[2].parameters.list.selected_index=1; + frontend_button_rows_show(&list); + assert(rows[2].visible&&!rows[7].visible&&!rows[6].visible); + for(i=3;i<6;i++) assert(!rows[i].visible); + /* Pending HUD off hides all dependent rows and recovers focus. */ + spinners[0].parameters.list.selected_index=1; + frontend_button_rows_show(&list); + for(i=1;i<8;i++) assert(!rows[i].visible); + assert(!rows[8].visible); + assert(list.focused_child==rows&&!list.parameters.list.selected_index); + assert(spinners[2].parameters.list.selected_index==1&&!writes); + /* A saved menu preference cannot bypass the pending High-Res HUD gate. */ + spinners[8].parameters.list.selected_index=1; + frontend_button_rows_show(&list); + assert(!rows[8].visible&&!rows[1].visible&&!rows[2].visible&&!writes); + spinners[8].parameters.list.selected_index=0; + /* Restoring HUD does not discard the pending manual choice. */ + spinners[0].parameters.list.selected_index=0; + frontend_button_rows_show(&list); + assert(rows[1].visible&&rows[2].visible&&!rows[6].visible); + assert(rows[8].visible); + spinners[2].parameters.list.selected_index=0; + } + return 0; +} +''') + + +def test_interface_rendering_order_and_unique_placement(): + doc = ET.fromstring(frontend_menu.document()) + settings = [w.get('setting') for w in doc.findall('widget') + if w.get('name', '').startswith('modern/interface/') and w.get('setting')] + assert settings.count('display.menu_button_glyphs') == 1 + assert 'display.keyboard_glyphs' not in settings + assert 'display.detected_button_style' not in settings + detected = next(w for w in doc.findall('widget') if w.get('name') == 'modern/interface/detected_button_style_value') + assert detected.get('type') == 'text' and detected.get('text') == 'KEYBOARD' + assert settings[:4] == ['display.menu_frontend', 'display.high_res_text', + 'display.high_res_hud', 'input.auto_button_detection'] + for key in ('display.high_res_text', 'display.high_res_hud'): + matches = [w for w in doc.findall('widget') if w.get('setting') == key] + assert len(matches) == 1 + assert matches[0].get('name').startswith('modern/interface/') + + +def test_generated_assets_routes_and_platform_filter(tmp_path): + menus = ROOT / 'port/assets/menus' + (tmp_path / 'menus.json').write_text('{"files": ["ce/untouched.xml"]}') + frontend_menu.generate(tmp_path) + frontend_menu.generate(tmp_path) + for path in (tmp_path / 'modern').iterdir(): + expected = menus / 'modern' / path.name + if path.suffix == '.png': + # PNG compression differs between the runner's Pillow/zlib builds; + # compare the artwork, not its container encoding. + with frontend_menu.Image.open(path) as actual, frontend_menu.Image.open(expected) as reference: + assert actual.size == reference.size, path.name + assert actual.convert('RGBA').tobytes() == reference.convert('RGBA').tobytes(), path.name + else: + assert path.read_text() == expected.read_text(), path.name + manifest = json.loads((menus / 'menus.json').read_text())['files'] + doc = ET.parse(menus / 'modern/settings.xml').getroot() + widgets = {node.get('name'): node for node in doc.findall('widget')} + destinations = set(widgets) + for file in (menus / 'ce').glob('*.xml'): + destinations.update(node.get('name') for node in ET.parse(file).getroot().findall('widget')) + assert doc.get('root') is None # must not override the legacy root + # MCC wrappers use unchanged native profile and difficulty services/art. + destinations.update('ui\\shell\\main_menu\\'+name for name in ( + 'player_profiles_select\\player_profile_select_list', + 'player_profiles_select\\header_select_profile', 'button_key', 'y_butn', '=create_new', + 'settings_select\\player_setup\\create_and_edit_player_profile_screen')) + for node in doc.findall('.//child'): + assert node.get('widget') in destinations + for node in doc.findall('.//on'): + if node.get('open'): + assert node.get('open') in destinations + for node in doc.findall('.//frame'): + assert node.get('png') in manifest + for node in doc.findall('widget'): + if 'pause_game' in node.get('flags', ''): + assert '/paused/' in node.get('name') + assert node.find("on[@run='main menu intialize']") is None + spinners = [w for w in widgets.values() if w.get('setting') and not w.get('name').startswith('modern/network/')] + assert len(spinners) >= 90 + for page, spec in enumerate(frontend_menu.PAGES): + base = frontend_menu.page_base(page) + screen = widgets[base + '/settings'] + assert screen.find("on[@event='y']").get('run') == 'port frontend next tab' + assert widgets[base + '/button_defaults'].find("on[@event='a']").get('run') == 'port frontend defaults' + assert widgets[base + '/button_cancel'].find("on[@event='a']").get('run') == 'port frontend cancel' + assert len(widgets[base + '/tabs'].findall('child')) == 6 + for name in ('help_value', 'status'): + assert widgets[base + '/' + name].get('text') is None + assert widgets[base + '/' + name].get('string_list') is None + for spinner in spinners: + path = spinner.get('name') + row = widgets[path.replace('/spinner_', '/row_')] + children = row.findall('child') + assert int(children[0].get('y')) == int(children[1].get('y')) == 3 + assert spinner.get('text_y') is None + arrows = [list(map(int, spinner.get(name).split())) for name in ('header_bounds', 'footer_bounds')] + assert sum(a[1] + a[3] for a in arrows) / 4 == int(spinner.get('width')) / 2 + assert all((a[0] + a[2]) / 2 + 3 == int(row.get('height')) / 2 for a in arrows) + assert 'nifty_fx' in row.get('flags') + fps = next(w for w in spinners if w.get('setting') == 'display.max_fps') + assert widgets[fps.get('name').replace('/spinner_', '/row_')].get('platform') == 'desktop web' + style = next(w for w in spinners if w.get('setting') == 'display.menu_frontend') + assert style.get('values') == 'modern|pc|xbox|off' + # The generated C routes and XML must agree, including every subpage. + routes = (ROOT / 'port/linux/game/frontend_pages.inl').read_text() + for index in range(len(frontend_menu.PAGES)): + path = "pc\\" + (frontend_menu.page_base(index) + "/settings").replace("/", "\\") + assert json.dumps(path) in routes + + +def test_labels_and_values_fit_narrow_layout(): + doc = ET.fromstring(frontend_menu.document()) + widgets = {w.get('name'): w for w in doc.findall('widget')} + strings = {s.get('name'): [v.get('text') for v in s] for s in doc.findall('strings')} + for w in widgets.values(): + if w.get('name').startswith('modern/network/'): + continue # Multiplayer contract and geometry have their own tests. + if w.get('setting') or '/label_' in w.get('name'): + assert w.get('font') == 'ui\\large_ui' + if '/label_' in w.get('name') and int(w.get('width')) == 152: + caption = strings[w.get('string_list')][int(w.get('string_index'))] + size = 10 # The entire narrow viewport uses the same option face. + assert frontend_menu.text_width(caption, size) <= 152, caption + if w.get('setting'): + size = 10 # The entire narrow viewport uses the same option face. + for caption in w.get('strings').split('|'): + assert frontend_menu.text_width(caption, size) <= int(w.get('width')) - 4, caption + + +def test_shoulder_camera_settings_are_reachable_and_use_pending_edits(): + doc = ET.fromstring(frontend_menu.document()) + widgets = {w.get('name'): w for w in doc.findall('widget')} + page = next(i for i, spec in enumerate(frontend_menu.PAGES) if spec[0] == 'third_person') + assert widgets[f'modern/row_link_{page}'].find("on[@event='a']").get('run') == 'port frontend page' + settings = {w.get('setting') for w in widgets.values() if w.get('name').startswith('modern/third_person/')} + assert settings - {None} == {'display.third_person'} | {row[1] for row in frontend_menu.SCREENS['video_settings/shoulder_camera']['rows']} + assert widgets['modern/third_person/button_cancel'].find("on[@event='a']").get('run') == 'port frontend cancel' + assert widgets['modern/third_person/button_apply'].find("on[@event='a']").get('run') == 'port frontend apply' + + +def test_mcc_packages_have_modern_navigation_and_platform_scoping(): + doc = ET.fromstring(frontend_menu.document()) + widgets = {w.get('name'): w for w in doc.findall('widget')} + page = next(i for i, spec in enumerate(frontend_menu.PAGES) if spec[0] == 'mcc_packages') + assert frontend_menu.PAGES[page][1:3] == (3, 10) + assert widgets[f'modern/sharing/row_link_{page}'].find("on[@event='a']").get('run') == 'port frontend page' + settings = {w.get('setting'): w for path, w in widgets.items() + if path.startswith('modern/mcc_packages/') and w.get('setting')} + assert set(settings) == {'game.workshop_maps', 'game.mcc_campaigns', 'game.mcc_collections'} + for key, spinner in settings.items(): + row = widgets[spinner.get('name').replace('/spinner_', '/row_')] + assert row.get('platform') == ('desktop' if key == 'game.workshop_maps' else None) + for button, callback in [('apply', 'apply'), ('cancel', 'cancel')]: + assert widgets[f'modern/mcc_packages/button_{button}'].find("on[@event='a']").get('run') == f'port frontend {callback}' + assert widgets['modern/mcc_packages/row_link_10'].find("on[@event='a']").get('run') == 'port frontend page' + + +def reachable_menu_widgets(widgets, start, platform): + runtime = (ROOT / 'port/linux/game/frontend_menu_runtime.inl').read_text() + editors = dict(re.findall(r'!strcmp\(key, "([^"]+)"\)\) target = "([^"]+)"', + function(runtime, 'frontend_editor'))) + pending, reached = [start], set() + visible = lambda node: platform in node.get('platform', 'desktop android web').split() + while pending: + name = pending.pop() + if name in reached or name not in widgets or not visible(widgets[name]): + continue + reached.add(name) + for node in widgets[name]: + if not visible(node): + continue + if node.tag == 'child': + pending.append(node.get('widget')) + elif node.get('open'): + pending.append(node.get('open')) + elif node.get('run') == 'port frontend page': + leaf = name.rsplit('/', 1)[1] + assert leaf.startswith(('row_link_', 'tab_')) + page = int(leaf.rsplit('_', 1)[1]) + pending.append(frontend_menu.page_base(page) + '/settings') + elif node.get('run') == 'port frontend editor': + target = editors.get(name.rsplit('/', 1)[1]) + if target: + pending.append('main_menu/settings_select/player_setup/player_profile_edit/' + + target.replace('\\\\', '/')) + return reached + + +@pytest.mark.parametrize('platform', ['desktop', 'android', 'web']) +def test_modern_network_menu_reaches_sharing(platform): + widgets = {w.get('name'): w for w in ET.fromstring(frontend_menu.document()).findall('widget')} + reached = reachable_menu_widgets(widgets, 'modern/online/settings', platform) + settings = {widgets[name].get('setting') for name in reached} + assert {'network.mcc_map_share', 'network.map_download', 'network.map_seed', + 'game.mcc_campaigns', 'game.mcc_collections'} <= settings + assert ('game.workshop_maps' in settings) == (platform == 'desktop') + assert 'modern/sharing/row_mcc_downloads' in reached + + +@pytest.mark.parametrize('platform', ['desktop', 'android', 'web']) +def test_modern_settings_match_stock_functionality(platform): + stock = {w.get('name'): w for file in (ROOT / 'port/assets/menus/ce').glob('*.xml') + for w in ET.parse(file).getroot().findall('widget')} + modern = {**stock, **{w.get('name'): w for w in ET.fromstring(frontend_menu.document()).findall('widget')}} + stock_route = reachable_menu_widgets(stock, + 'main_menu/settings_select/player_setup/player_profile_edit/player_profile_edit_screen', platform) + modern_route = reachable_menu_widgets(modern, 'modern/settings', platform) + settings = lambda widgets, route: {widgets[n].get('setting') for n in route if widgets[n].get('setting')} + assert settings(stock, stock_route) == settings(modern, modern_route) + + +def test_stock_editors_preserve_pending_modern_settings(tmp_path): + stubs = RUNTIME_STUBS.replace(function(RUNTIME_STUBS, 'ui_widget_port_open'), r''' +static char const *opened; +boolean ui_widget_port_open(struct widget_instance *w,char const *s,boolean *d) { + (void)w;assert(strstr(s,opened));opens++;*d=1;return 1; +} +''') + run_c(tmp_path, stubs + HEADER + (ROOT/'port/linux/game/frontend_pages.inl').read_text() + + without_includes('port/linux/game/frontend_menu_runtime.inl') + r''' +int main(void) { + struct widget_instance root={0},spinner={0},action={0};int deleted=0,i; + char const *names[]={"row_dead_zones","row_discord"}; + char const *targets[]={"gamepad_setup\\dead_zones\\dead_zone_settings_screen", + "network_setup\\discord_account\\discord_account_settings_screen"}; + root.definition_tag_index=3;root.child=&spinner;spinner.parent=&root; + spinner.type=2;spinner.definition_tag_index=5;spinner.parameters.list.selected_index=2; + spinner.next=&action;action.parent=&root; + for(i=0;i<2;i++) { + action.name=names[i];opened=targets[i];deleted=0; + assert(frontend_menu_event(&action,"port frontend editor",&deleted)&&deleted); + assert(frontend_session.count==1&&frontend_session.pending[0].index==2); + assert(!frontend_session.owns_profile&&!writes); + } + assert(opens==2); + assert(frontend_menu_event(&action,"port frontend cancel",&deleted)); + assert(!frontend_session.count&&!writes&&transitions==1); + return 0; +} +''') + + +def test_scroll_hook_precedes_pointer_registration(): + render = function((ROOT / 'source/interface/ui_widget.c').read_text(), 'widget_instance_render_recursive') + assert render.index('frontend_menu_row_drawable(widget)') < render.index('ui_mouse_note_target(widget, definition, offset)') + + + +def test_xbox_added_links_keep_native_description_indices(tmp_path): + runtime = (ROOT / 'port/linux/game/frontend_menu_runtime.inl').read_text() + stubs = RUNTIME_STUBS.replace('return "modern";', 'return "xbox";') + old = function(stubs, 'tag_get_name') + stubs = stubs.replace(old, r""" +static char const *tag_get_name(long id) { + if(id==50)return "ui\\shell\\main_menu\\settings_select\\player_setup\\player_profile_edit\\profile_edit_select_list"; + if(id>=3&&id<=5)return id==3?"pc\\frontend_legacy\\audio":id==4?"pc\\frontend_legacy\\video":"pc\\frontend_legacy\\network"; + if(id==60)return "pc\\frontend_legacy\\description"; + return "native"; +} +""") + run_c(tmp_path, stubs + function(runtime,'frontend_menu_can_edit') + + function(runtime,'frontend_menu_legacy_description_index') + r""" +int main(void) { + struct widget_instance list={0},rows[8]={{0}},description={0},details[3]={{0}}; + int i; + list.definition_tag_index=50;list.child=rows;list.parameters.list.extended_description=&description; + description.child=details; + for(i=0;i<3;i++){details[i].next=i<2?details+i+1:0;details[i].definition_tag_index=i==2?60:0;} + for(i=0;i<8;i++){rows[i].next=i<7?rows+i+1:0;rows[i].definition_tag_index=i;} + for(i=0;i<8;i++){ + list.focused_child=rows+i; + assert(frontend_menu_legacy_description_index(&list,i)==(i<3?i:i<6?-1:i-3)); + assert(details[0].visible==(i<3||i>=6));assert(details[1].visible==details[0].visible); + assert(details[2].visible==!details[0].visible); + } + network=1;assert(frontend_menu_legacy_description_index(&list,7)==7);network=0; + main_menu=0;assert(frontend_menu_legacy_description_index(&list,7)==7);main_menu=1; + available=0;assert(frontend_menu_legacy_description_index(&list,7)==7); + return 0; +} +""") + + +def test_pending_third_person_visibility_preserves_choices_and_focus(tmp_path): + runtime = (ROOT / 'port/linux/game/frontend_menu_runtime.inl').read_text() + stubs = RUNTIME_STUBS.replace('return id==5?&setting:0;', 'return id>=10&&id<13?&options[id-10]:0;') + stubs = stubs.replace('static int available=1', 'static struct pc_menu_setting options[3];\nstatic int available=1') + run_c(tmp_path, stubs + ''.join(function(runtime, name) for name in + ('frontend_setting_row','frontend_row_value','frontend_button_rows_show','frontend_rows_show')) + r""" +int main(void) { + struct widget_instance list={0},rows[3]={{0}},spinners[3]={{0}}; + char const *keys[]={"display.third_person","display.third_person_camera","display.third_person_left_shoulder"}; + int i; + list.child=rows;list.focused_child=rows+2; + for(i=0;i<3;i++){ + rows[i].child=spinners+i;rows[i].next=i<2?rows+i+1:0; + spinners[i].type=2;spinners[i].definition_tag_index=10+i; + options[i].setting=keys[i];options[i].value_count=2; + options[i].values[0]="false";options[i].values[1]="true"; + spinners[i].parameters.list.selected_index=i?1:0; + } + frontend_rows_show(&list); + assert(!rows[1].visible&&!rows[2].visible&&list.focused_child==rows); + assert(list.parameters.list.selected_index==0&&spinners[2].parameters.list.selected_index==1&&!writes); + spinners[0].parameters.list.selected_index=1;frontend_rows_show(&list); + assert(rows[1].visible&&rows[2].visible&&spinners[2].parameters.list.selected_index==1&&!writes); + return 0; +} +""") + + +def test_xbox_editor_actions_bypass_spinner_help_and_accept_close(tmp_path): + runtime = (ROOT / 'port/linux/game/frontend_menu_runtime.inl').read_text() + stubs = RUNTIME_STUBS.replace('return "modern";', 'return "xbox";') + stubs = stubs.replace(function(stubs, 'tag_get_name'), r''' +static char const *tag_get_name(long id) { + if(id==50)return "ui\\shell\\main_menu\\settings_select\\player_setup\\player_profile_edit\\advanced_controls\\advanced_controls_menu"; + if(id==51)return "pc\\frontend_legacy\\keyboard"; + if(id==52)return "pc\\frontend_legacy\\controller"; + if(id==53)return "pc\\frontend_legacy\\glyphs"; + return "native"; +} +''') + + stubs = stubs.replace(function(stubs, 'ui_widget_port_open'), r''' +boolean ui_widget_port_open(struct widget_instance *w,char const *s,boolean *d) { + (void)d;opens++; + assert(strstr(s,w->definition_tag_index==51?"controls_setup":w->definition_tag_index==52?"controller_remapping":"controller_appearance")); + return 1; +} +''') + run_c(tmp_path, stubs + HEADER + ''.join(function(runtime, name) for name in + ('frontend_menu_can_edit', 'frontend_menu_legacy_root', 'frontend_menu_legacy_footer_action', 'frontend_menu_shortcut', 'frontend_menu_legacy_controls_help')) + r''' +int main(void) { + struct widget_instance root={0},list={0},action={0},help={0}; + struct event_record event={0};int i; + root.focused_child=&list;list.parent=&root;list.focused_child=&action; + list.definition_tag_index=50;action.parent=&list;list.parameters.list.extended_description=&help; + event.type=3;event.data.button.value=1; + for(i=51;i<=53;i++){ + action.definition_tag_index=i;event.data.button.index=0; + assert(frontend_menu_legacy_controls_help(&list)&&!help.visible); + assert(frontend_menu_shortcut(&root,&event)); + event.data.button.index=12;assert(frontend_menu_shortcut(&root,&event)); + event.data.button.value=2;assert(!frontend_menu_shortcut(&root,&event));event.data.button.value=1; + } + action.definition_tag_index=0; + assert(!frontend_menu_legacy_controls_help(&list)&&help.visible); + assert(!frontend_menu_shortcut(&root,&event)); + action.definition_tag_index=51; + for(i=0;i<3;i++){ + available=0;main_menu=i!=1;network=i==2; + assert(!frontend_menu_legacy_controls_help(&list)); + assert(!frontend_menu_shortcut(&root,&event)); + } + assert(opens==6);return 0; +} +''') + + +def test_xbox_footers_keep_callbacks_and_use_native_glyph_tags(tmp_path): + doc = ET.Element('menus') + routes = frontend_legacy.append(doc) + widgets = {w.get('name'): w for w in doc.findall('widget')} + native = frontend_legacy.inventory() + for old, new, glyph in routes: + assert [e.attrib for e in widgets[new].findall('on')] == [e.attrib for e in native[old].findall('on')] + assert widgets[new].get('bitmap') is None + assert widgets['frontend_legacy/footer_glyph_'+glyph].get('bitmap') == 'ui\\shell\\bitmaps\\'+glyph+'_butn' + old, new, _ = next(r for r in routes if r[0].endswith('/audio_settings/button_defaults')) + old, new = ('pc\\'+p.replace('/', '\\') for p in (old, new)) + stubs = RUNTIME_STUBS.replace('return "modern";', 'return style;') + stubs = stubs.replace('static int available=1', 'static char const *style="xbox";\nstatic int available=1') + stubs = stubs.replace(function(stubs, 'tag_get_name'), + 'static char const *tag_get_name(long id) {return id==100?'+json.dumps(old)+ + ':id==102?'+json.dumps(old.rsplit('\\',1)[0]+'\\audio_settings_screen')+':"native";}') + stubs = stubs.replace(function(stubs, 'tag_loaded'), + 'static long tag_loaded(long g,char const *p) {(void)g;return !strcmp(p,'+json.dumps(new)+')?101:-1;}') + runtime = (ROOT / 'port/linux/game/frontend_menu_runtime.inl').read_text() + run_c(tmp_path, stubs + HEADER + (ROOT/'port/linux/game/frontend_legacy_footers.inl').read_text() + + function(runtime, 'frontend_menu_can_edit') + function(runtime, 'frontend_menu_attach') + r''' +int main(void) { + struct widget_instance widget={0},root={0};int i; + char const *styles[]={"off","pc","modern"}; + root.definition_tag_index=102;widget.parent=&root; + widget.definition_tag_index=100;widget.parameters.text_box.string_list_index=3; + frontend_menu_attach(&widget); + assert(widget.definition_tag_index==101&&widget.parameters.text_box.string_list_index==0); + assert(widget.child==&entry&&entry.parent==&widget&&opens==1); + for(i=0;i<3;i++){ + widget.definition_tag_index=100;widget.child=0;style=styles[i];frontend_menu_attach(&widget); + assert(widget.definition_tag_index==100&&!widget.child&&opens==1); + } + style="xbox"; + main_menu=0;network=1;frontend_menu_attach(&widget); + assert(widget.definition_tag_index==101&&widget.child==&entry&&opens==2); + widget.definition_tag_index=100;widget.child=0;main_menu=1;network=0;opens=1; + root.definition_tag_index=0;frontend_menu_attach(&widget); + assert(widget.definition_tag_index==100&&!widget.child&&opens==1); /* browser/native roots */ + root.definition_tag_index=102; + for(i=0;i<3;i++){ + available=0;main_menu=i!=1;network=i==2;frontend_menu_attach(&widget); + assert(widget.definition_tag_index==100&&!widget.child&&opens==1); + } + return 0; +} +''') + + +def test_new_install_defaults_follow_active_input(): + config = (ROOT / "port/linux/src/port_config.c").read_text() + assert r'"display.menu_frontend", _config_string, "\"modern\""' in config + assert '"display.keyboard_glyphs"' not in config + assert '"input.auto_button_detection", _config_boolean, "true"' in config diff --git a/tools/test_frontend_multiplayer.py b/tools/test_frontend_multiplayer.py new file mode 100644 index 0000000000..4fa5095696 --- /dev/null +++ b/tools/test_frontend_multiplayer.py @@ -0,0 +1,258 @@ +"""Modern views preserve native multiplayer services and viewport navigation.""" +import xml.etree.ElementTree as ET + +import frontend_multiplayer +from frontend_menu import text_width +from test_frontend_menu import ROOT, HEADER, RUNTIME_STUBS, without_includes +from test_frontend_presentation import source +from test_hud_button_style import run_c +from harness import function + + +def test_service_contracts_and_routes(): + doc = ET.Element('menus') + roles, routes = frontend_multiplayer.append(doc) + widgets = {w.get('name'): w for w in doc.findall('widget')} + legacy = frontend_multiplayer.inventory() + assert len(routes) == len(frontend_multiplayer.PAGES) + for old, new in routes: + service = next((w for path,w in widgets.items() if path.startswith(new.rsplit('/',1)[0]+'/') and path.endswith('/'+old.rsplit('/',1)[-1])), widgets[new]) + assert [n.attrib for n in service.findall('on')] == [n.attrib for n in legacy[old].findall('on')] + assert new.startswith('modern/network/') + assert 'pause_game' not in widgets[new].get('flags', '') + # Preserve child order and count for the native paged services. Presentation + # must not change what index the service treats as a map/gametype/player. + lists = ('mp_map_select_list_2', 'gametype_select_list_2', 'lobby_list') + for name in lists: + old = next(w for path,w in legacy.items() if path.endswith('/'+name)) + new = next(w for path,w in widgets.items() if path.endswith('/'+name)) + assert [c.get('widget').rsplit('/',1)[-1] for c in new.findall('child')] == [c.get('widget').rsplit('/',1)[-1] for c in old.findall('child')] + assert new.findall('data')[-1].get('input') == 'port frontend multiplayer update' + assert not any('/browser/' in n or '/filters/' in n for n in widgets) + assert not any('join_game_screen' in old for old,_ in routes) + # Every dependency is in the isolated generated set or an existing service. + for w in widgets.values(): + assert sum(key in w.attrib for key in ('text', 'strings', 'string_list')) <= 1 + if w.get('text') is not None: + assert int(w.get('string_index', '0')) == 0 + for c in w.findall('child'): + assert c.get('widget') in widgets + for c in w.findall('on'): + if c.get('open'): assert c.get('open') in legacy + assert not any('main_menu/main_menu' == old for old,_ in routes) + assert not any(w.get('bitmap') in ('bitmaps/gradient', 'bitmaps/gradient_big') for w in widgets.values()) + assert not any(path.rsplit('/', 1)[-1] == 'header' or path.rsplit('/', 1)[-1].startswith('header_') for path in widgets) + assert len(dict(roles)) < len(widgets) + + +def test_embedded_difficulty_replaces_detail_and_restores_rows(tmp_path): + stubs = RUNTIME_STUBS.replace('return id==1?', + 'return id==8?"pc\\\\modern\\\\network\\\\maps\\\\screen":id==9?"pc\\\\modern\\\\network\\\\maps\\\\list_item_text":id==10?"pc\\\\modern\\\\network\\\\maps\\\\list_item_text_centered":id==1?') + stubs = stubs.replace('(void)group;(void)path;return -1;', + '(void)group;return strstr(path,"_centered")?10:9;') + stubs = stubs.replace('(void)root;(void)name;(void)n;return 0;', ''' + struct widget_instance *child,*found;(void)n; + if(!root)return 0; + if(root->name&&!strcmp(root->name,name))return root; + for(child=root->child;child;child=child->next){found=named(child,name,0);if(found)return found;} + return 0;''') + code = (ROOT/'port/linux/game/frontend_multiplayer.inl').read_text() + run_c(tmp_path, stubs + ''.join(function(code, n) for n in + ('frontend_multiplayer_root', 'frontend_multiplayer_difficulty')) + r''' +int main(void){ + struct widget_instance root={0},list={0},description={0},icon={0},text={0},map={0},row={0},label={0}; + int i; + root.definition_tag_index=8;list.parent=&root;list.child=&row;row.child=&label; + label.name="list_item_text";label.definition_tag_index=9; + list.parameters.list.extended_description=&description;description.child=&icon; + icon.name="difficulty_options";icon.next=&text;text.name="difficulty_extended_description"; + text.next=↦map.name="mp_map_right_item"; + for(i=0;i<4;i++){ + map.visible=1;frontend_multiplayer_difficulty(&list,i); + assert(!map.visible&&icon.visible&&text.visible); + assert(icon.animation.current_frame_index==i&&text.parameters.text_box.string_list_index==i); + assert(label.definition_tag_index==10); + } + map.visible=1;frontend_multiplayer_difficulty(&list,NONE); + assert(map.visible&&!icon.visible&&!text.visible&&label.definition_tag_index==9); + available=0;frontend_multiplayer_difficulty(&list,2);assert(map.visible&&!icon.visible); + available=1;root.definition_tag_index=1;frontend_multiplayer_difficulty(&list,2); + assert(map.visible&&!icon.visible&&label.definition_tag_index==9); + return 0; +} +''') + + +def test_pregame_routes_and_style_switch_guard(tmp_path): + run_c(tmp_path,r''' +#include +#include +#define NONE -1 +typedef int boolean; +static char const *choice="modern",*name; +static int main_menu=1,network=1,tags=1; +boolean main_menu_is_active(void){return main_menu;} +boolean network_game_is_active(void){return network;} +static char const *config_string(char const *key){(void)key;return choice;} +static char const *tag_get_name(long tag){(void)tag;return name;} +static int csstrcasecmp(char const *a,char const *b){return strcmp(a,b);} +static long tag_loaded(long g,char const *n){(void)g;(void)n;return tags?91:NONE;} +void frontend_input_enable(int x){(void)x;} +void keyboard_glyphs_dispose(void){} +void frontend_menu_text_end(void){} +void frontend_panel_end(void){} +void frontend_menu_session_reset(void){} +''' + HEADER + without_includes('port/linux/game/frontend_menu.c') + r''' +int main(void){ + unsigned int i; + frontend_menu_map_loaded("ui",0); + for(i=0;i= 396 + assert int(help.get('top')) + int(help.get('height')) <= 390 + voice = next(w for name, w in widgets.items() if name.endswith('/voice_mode_spinner')) + assert voice.get('strings').split('|') == ['OFF', 'TEAM NEAR', 'ANYONE NEAR', 'TEAM', 'TEAM + NEARBY'] + assert all(text_width(s, 10) <= int(voice.get('width')) for s in voice.get('strings').split('|')) + label = next(w for name, w in widgets.items() if name.endswith('/voice_proximity_label')) + assert text_width(label.get('text'), 10) <= int(label.get('width')) + + +def test_scroll_preserves_service_indices_visibility_and_lifetime(tmp_path): + stubs=RUNTIME_STUBS.replace('return id==1?', 'return id==8?"pc\\\\modern\\\\network\\\\lobby\\\\0\\\\lobby_screen":id==1?') + run_c(tmp_path,stubs + HEADER + without_includes('port/linux/game/frontend_multiplayer.inl') + r''' +int main(void){ + struct widget_instance root={0},list={0},rows[30]={{0}}; + int i; + root.definition_tag_index=8;root.child=&list;list.parent=&root; + list.name="lobby_list";list.type=3;list.child=rows;network=1; + for(i=0;i<30;i++){ + rows[i].name="list_item_1";rows[i].parent=&list;rows[i].visible=1; + rows[i].vertical_offset=110+30*i;rows[i].next=i<29?rows+i+1:0; + } + list.focused_child=rows+29;frontend_multiplayer_update(&list); + assert(rows[29].vertical_offset==350&&frontend_multiplayer_drawable(rows+29)); + assert(!frontend_multiplayer_drawable(rows)); + for(i=0;i<30;i++)assert(rows[i].visible&&rows[i].next==(i<29?rows+i+1:0)); + list.focused_child=rows;frontend_multiplayer_update(&list); + assert(rows[0].vertical_offset==110&&rows[8].vertical_offset==350); + rows[0].visible=0;list.focused_child=rows+1;frontend_multiplayer_update(&list); + assert(rows[1].vertical_offset==110&&!rows[0].visible); + main_menu=0;list.focused_child=rows+29;frontend_multiplayer_update(&list); + assert(rows[1].vertical_offset==110);main_menu=1; + available=0;frontend_multiplayer_update(&list);assert(rows[1].vertical_offset==110); + return 0; +} +''') + + +def test_geometry_contains_rows_at_all_aspects(tmp_path): + run_c(tmp_path,r''' +#include +#include +#include +#define NONE -1 +static int frontend_menu_available(void){return 1;} +static long tag_loaded(long g,char const *n){(void)g;(void)n;return 0;} +static char const *tag_name=""; +static char const *tag_get_name(long t){(void)t;return tag_name;} +static long halo_screen_width(void){return 852;} +''' + HEADER + source('port/linux/game/frontend_layout.c') + r''' +int main(void){ + int sizes[]={640,768,852,1120,1706},i,j; + short left,right,shift; + for(i=0;i<5;i++)for(j=0;j<(int)(sizeof(frontend_network_widgets)/sizeof(frontend_network_widgets[0]));j++){ + int role=frontend_network_widgets[j].role; + tag_name=frontend_network_widgets[j].name; + assert(frontend_menu_stretch_bitmap(0)==(role!=FRONTEND_NET_DETAIL_FIXED)); + left=0;right=336;shift=0; + frontend_layout_geometry(frontend_network_widgets[j].name,sizes[i],&left,&right,&shift); + if(role==FRONTEND_NET_ROW){ + int extra=frontend_layout_width(sizes[i])-640; + assert(28+shift>=-(sizes[i]-640)/2); + assert(28+shift+right==364-extra/2+extra*3/5); + } + if(role==FRONTEND_NET_FULL)assert(right-left==sizes[i]); + } + return 0; +} +''') + + +def test_difficulty_native_order_and_background_layer(): + doc = ET.Element('menus') + _, routes = frontend_multiplayer.append(doc) + widgets = {w.get('name'): w for w in doc.findall('widget')} + root = widgets[dict(routes)[frontend_multiplayer.PAGES['difficulty'][0]]] + children = [c.get('widget') for c in root.findall('child')] + service = next(n for n in children if n.endswith('/difficulty_select_list_screen')) + panel = next(n for n in children if n.endswith('/help_panel')) + assert children.index(panel) < children.index(service) + assert 'nifty_fx' in widgets[panel].get('flags') + assert widgets[service].get('bitmap') is None + native_children = [c.get('widget') for c in widgets[service].findall('child')] + assert native_children[0].endswith('/difficulty_select_list') + assert native_children[1].endswith('/warning_message') + warning = widgets[native_children[1]] + assert warning.get('align') == 'center' + assert int(warning.get('width')) == 312 + desc = next(w for n,w in widgets.items() if n.startswith('modern/network/difficulty/') and n.endswith('/difficulty_extended_description')) + assert desc.get('align') == 'center' + assert desc.get('text_x') == desc.get('text_y') == '0' + + +def test_campaign_list_keeps_native_updates_and_modern_layout(): + doc = ET.Element('menus') + roles, _ = frontend_multiplayer.append(doc) + widgets = {w.get('name'): w for w in doc.findall('widget')} + campaign = next(w for name, w in widgets.items() + if name.startswith('modern/network/campaign/') and name.endswith('/solo_level_select_list')) + assert campaign.find("on[@event='created']").get('run') == 'initialize sp level list solo' + assert [n.get("input") for n in campaign.findall("data")] == ["solo map list update", "port frontend multiplayer update"] + rows = [widgets[c.get('widget')] for c in campaign.findall('child') + if '/list_item_' in c.get('widget')] + assert len(rows) == 11 + assert all(dict(roles)[row.get('name')] == 'row' for row in rows) + assert all(row.get('width') == '336' for row in rows) diff --git a/tools/test_frontend_navigation.py b/tools/test_frontend_navigation.py new file mode 100644 index 0000000000..57bdaa3be0 --- /dev/null +++ b/tools/test_frontend_navigation.py @@ -0,0 +1,81 @@ +"""Landing-screen routes and the production scrolling/lifecycle helpers.""" +import xml.etree.ElementTree as ET + +import frontend_menu +import frontend_navigation +from test_frontend_menu import HEADER, ROOT, RUNTIME_STUBS, without_includes +from test_hud_button_style import run_c + + +def test_routes_use_existing_services_and_profile_gate(): + doc = ET.fromstring(frontend_menu.document()) + widgets = {w.get('name'): w for w in doc.findall('widget')} + for page, (_, _, rows) in frontend_navigation.SCREENS.items(): + base = 'modern/' + page + root = widgets[base + '/screen'] + assert root.get('width') == '640' + assert root.find("on[@event='created']").get('run') == 'main menu intialize' + assert widgets[base + '/help_panel'].get('flags') == 'nifty_fx' + for _, _, key, destination, callbacks, _ in rows: + row = widgets[base + '/row_' + key] + assert len('row_' + key) <= 31 + assert row.get('height') == '26' + assert row.find('child').get('y') == '3' + for event in ('a', 'start'): + handlers = row.findall(f"on[@event='{event}']") + assert [h.get('run') for h in handlers if h.get('run')] == callbacks + assert handlers[-1].get('open') == destination + assert 'mcc' not in ET.tostring(root).decode().lower() + # Native mode dispatch distinguishes LAN, invite and public internet by + # instance name; losing these tokens silently selects the wrong transport. + for key in ('join_lan_item', 'join_direct_item'): + row = widgets['modern/multiplayer/row_' + key] + assert row.find("on[@event='a']").get('run') == 'mp type set mode' + for key in ('create_lan_item', 'create_internet_item'): + row = widgets['modern/host/row_' + key] + handlers = row.findall("on[@event='a']") + assert handlers[0].get('run') == 'join controller to mp game' + assert handlers[1].get('run') == 'mp type set mode' + assert handlers[1].get('branch') == 'true' + assert not any(name.startswith("modern/main/") for name in widgets) + + + +def test_navigation_focus_scroll_reset_and_gameplay_guards(tmp_path): + stubs = RUNTIME_STUBS.replace('return id==1?', 'return id==8?"pc\\\\modern\\\\multiplayer\\\\screen":id==1?') + stubs = stubs.replace('(void)root;(void)name;(void)n;return 0;', + 'struct widget_instance *child,*found;(void)n;' + 'if(root->name&&!strcmp(root->name,name))return root;' + 'for(child=root->child;child;child=child->next){found=named(child,name,0);if(found)return found;}return 0;') + run_c(tmp_path, stubs + HEADER + + (ROOT / 'port/linux/game/frontend_pages.inl').read_text() + + without_includes('port/linux/game/frontend_menu_runtime.inl') + r''' +int main(void) { + struct widget_instance root={0},list={0},section={0},rows[20]={{0}}; + int i,deleted=0; + root.definition_tag_index=8;root.child=&list;list.parent=&root;list.name="options"; + list.child=§ion;section.name="section_0";section.parent=&list;section.vertical_offset=82; + section.next=rows; + for(i=0;i<20;i++) { + rows[i].name="row_test";rows[i].visible=1;rows[i].parent=&list; + rows[i].next=i<19?&rows[i+1]:0;rows[i].vertical_offset=110+30*i; + } + assert(frontend_menu_event(&root,"port frontend navigation init",&deleted)); + assert(list.focused_child==rows); + frontend_navigation_update(&list); + assert(frontend_menu_row_drawable(rows)&&!frontend_menu_row_drawable(rows+9)); + list.focused_child=rows+19;frontend_navigation_update(&list); + assert(rows[19].vertical_offset==356&&frontend_menu_row_drawable(rows+19)); + assert(!frontend_menu_row_drawable(rows)&&!frontend_menu_row_drawable(§ion)); + list.focused_child=rows;frontend_navigation_update(&list); + assert(rows[0].vertical_offset==110&§ion.vertical_offset==82); + for(i=0;i<3;i++) { + available=i!=0;main_menu=i!=1;network=i==2; + list.focused_child=rows+19; + frontend_navigation_update(&list); + assert(rows[0].vertical_offset==110); + assert(!frontend_menu_event(rows,"port frontend navigation init",&deleted)); + } + return 0; +} +''') diff --git a/tools/test_frontend_presentation.py b/tools/test_frontend_presentation.py new file mode 100644 index 0000000000..9c70d8cec9 --- /dev/null +++ b/tools/test_frontend_presentation.py @@ -0,0 +1,443 @@ +"""Production layout, input-source and binding contracts, independent of maps.""" +from pathlib import Path +import re + +from harness import function +from test_hud_button_style import run_c + +ROOT = Path(__file__).resolve().parents[1] + + +def source(name): + text = (ROOT / name).read_text().replace('#include "frontend_network_layout.inl"', + (ROOT / 'port/linux/game/frontend_network_layout.inl').read_text()) + return re.sub(r'^#include .*$', '', text, flags=re.M) + + +def test_description_reflow_joins_native_split_words(tmp_path): + implementation = function((ROOT / 'port/linux/game/frontend_layout.c').read_text(), 'frontend_menu_reflow_text') + run_c(tmp_path, r''' +#include +#include +''' + implementation + r''' +int main(void) { + wchar_t text[256] = L"|cReactivate the wea-\r\npon at the heart of\r\nHalo...and learn the truth."; + wchar_t marked[64] = L"|lwea-|npon|nready|r"; + wchar_t plain[64] = L"Co-op campaign |"; + wchar_t empty[1] = {0}; + frontend_menu_reflow_text(text); + assert(!wcscmp(text,L"Reactivate the weapon at the heart of Halo...and learn the truth.")); + frontend_menu_reflow_text(text); + assert(!wcscmp(text,L"Reactivate the weapon at the heart of Halo...and learn the truth.")); + frontend_menu_reflow_text(marked);assert(!wcscmp(marked,L"weapon ready")); + frontend_menu_reflow_text(plain);assert(!wcscmp(plain,L"Co-op campaign |")); + frontend_menu_reflow_text(empty);assert(!empty[0]); + return 0; +} +''') + + +def test_wide_geometry_resize_and_scoped_text_clip(tmp_path): + run_c(tmp_path, r''' +#include +#include +#include +#define NONE -1 +static long tag_loaded(long group,char const *name){(void)group;(void)name;return 9;} +static int available=1,screen=852; +int frontend_menu_available(void) {return available;} +char const *tag_get_name(long tag) {return tag==1?"pc\\modern\\help":"pc\\main_menu\\main_menu";} +long halo_screen_width(void) {return screen;} +''' + source('port/linux/game/frontend_layout.c') + r''' +int main(void) { + int sizes[]={640,768,852,1120,1706,640},i,extra,rows,origin; + short l,r,shift,cl,cr; + for(i=0;i<6;i++) { + screen=sizes[i];extra=frontend_layout_width(screen)-640;rows=extra*3/5;origin=-extra/2; + l=0;r=640;shift=0; + assert(frontend_layout_geometry("pc\\modern\\settings",screen,&l,&r,&shift)); + assert(l==-(screen-640)/2&&r-l==screen&&shift==0); + l=0;r=364;assert(frontend_layout_geometry("pc\\modern\\row_style",screen,&l,&r,&shift)); + assert(shift==origin&&r==364+rows); + /* Hit targets receive this same definition and accumulated origin. */ + assert(24+shift>=-(screen-640)/2&&24+shift+r<=400+origin+rows); + l=0;r=152;assert(frontend_layout_geometry("pc\\modern\\spinner_style",screen,&l,&r,&shift)); + assert(shift==rows-rows/3&&r==152+rows/3); + l=412;r=610;assert(frontend_layout_geometry("pc\\modern\\help",screen,&l,&r,&shift)); + assert(shift==origin+rows&&r-l==198+extra-rows); + cl=0;cr=640;frontend_menu_clip_text(-1000,2000,&cl,&cr);assert(cl==0&&cr==640); + frontend_menu_text_begin(1);frontend_menu_clip_text(-1000,2000,&cl,&cr); + assert(cl==-(screen-640)/2&&cr==cl+screen);frontend_menu_text_end(); + cl=0;cr=640;frontend_menu_text_begin(2);frontend_menu_clip_text(-1000,2000,&cl,&cr);assert(cl==0&&cr==640); + l=0;r=640;shift=0;assert(!frontend_layout_geometry("ui\\shell\\main_menu",screen,&l,&r,&shift)); + assert(l==0&&r==640&&shift==0); + assert(!frontend_layout_geometry("pc\\modern\\entry",screen,&l,&r,&shift)); + l=0;r=272;shift=0; + assert(frontend_layout_geometry("pc\\modern\\multiplayer\\row_host",screen,&l,&r,&shift)); + assert(shift==origin&&r==272+extra*9/20); + l=0;r=302;shift=0; + assert(frontend_layout_geometry("pc\\modern\\host\\help_panel",screen,&l,&r,&shift)); + assert(shift==origin+extra*9/20&&r==302+extra-extra*9/20); + } + available=0;cl=0;cr=640;frontend_menu_text_begin(1);frontend_menu_clip_text(-1000,2000,&cl,&cr); + assert(cl==0&&cr==640);assert(!frontend_menu_geometry(1,&cl,&cr,&shift)); + return 0; +} +''') + + +def test_option_font_is_uniform_across_rows_pages_and_resize(tmp_path): + run_c(tmp_path, r''' +#include +#include +#include +#define NONE -1 +static int available=1,screen=640,fonts_loaded=1; +static char const *current_name; +static long tag_loaded(long group,char const *name){ + (void)group; + if(!fonts_loaded)return NONE; + return !strcmp(name,"ui\\small_ui")?10:20; +} +int frontend_menu_available(void){return available;} +char const *tag_get_name(long tag){(void)tag;return current_name;} +long halo_screen_width(void){return screen;} +''' + source('port/linux/game/frontend_layout.c') + r''' +int main(void){ + char const *names[]={"pc\\modern\\interface\\label_auto", + "pc\\modern\\interface\\label_manual","pc\\modern\\interface\\spinner_manual", + "pc\\modern\\lighting\\label_glow","pc\\modern\\browser\\master_servers_value"}; + int sizes[]={640,768,831,832,852,1120,1706,640},i,j; + for(i=0;i<8;i++){ + screen=sizes[i]; + for(j=0;j<5;j++){ + current_name=names[j]; + assert(frontend_menu_font(1,7)==(screen<832?10:20)); + } + } + current_name="pc\\modern\\help_title";assert(frontend_menu_font(1,7)==7); + current_name="pc\\main_menu\\label_auto";assert(frontend_menu_font(1,7)==7); + current_name=names[0];available=0;assert(frontend_menu_font(1,7)==7); + available=1;fonts_loaded=0;assert(frontend_menu_font(1,7)==7); + current_name=NULL;assert(frontend_menu_font(1,7)==7); + return 0; +} +''') + + +def test_input_edges_hotplug_touch_and_teardown(tmp_path): + run_c(tmp_path, '#include \n#include \n' + source('port/linux/src/frontend_input.c') + r''' +int main(void) { + unsigned char keys[512]={0};int i; + frontend_input_enable(1);assert(frontend_input_device()==-1); + frontend_input_pad(0,0,1);assert(frontend_input_device()==-1); + frontend_input_pad(2,1,1);assert(frontend_input_device()==2); + keys[4]=1;frontend_input_keys(keys,512);assert(frontend_input_device()==-1); + frontend_input_pad(2,1,1);assert(frontend_input_device()==-1); /* held is not new activity */ + frontend_input_pad(2,0,1);frontend_input_pad(2,2,1);assert(frontend_input_device()==2); + frontend_input_keys(keys,512);assert(frontend_input_device()==2); + frontend_input_pointer(0,0);assert(frontend_input_device()==2); + frontend_input_pointer(1,1);assert(frontend_input_device()==-2); + frontend_input_pad(3,4,1);assert(frontend_input_device()==3); + frontend_input_pad(3,0,0);assert(frontend_input_device()==-2); + frontend_input_pad(3,0,1);assert(frontend_input_device()==-2); /* reconnect idle */ + frontend_input_pad(-1,1,1);frontend_input_pad(4,1,1);assert(frontend_input_device()==-2); + frontend_input_pointer(0,1);assert(frontend_input_device()==-1); + for(i=0;i<100;i++) { + frontend_input_enable(0);frontend_input_pad(0,1,1);frontend_input_pointer(1,1); + assert(frontend_input_device()==-1);frontend_input_enable(1); + frontend_input_pad(0,1,1);assert(frontend_input_device()==0); + } + return 0; +} +''') + + +def test_detached_help_retains_viewport_clip(tmp_path): + text = (ROOT / 'source/interface/ui_widget.c').read_text() + integration = text.split('/* port: a local modern definition supplies identical drawing and pointer bounds. */', 1)[1] + integration = integration.split('if (!use_nifty_plasma_fx', 1)[0] + run_c(tmp_path, r''' +#include +#include +#include +typedef int boolean; +typedef struct {short x0,y0,x1,y1;} rectangle2d; +struct ui_widget_definition {rectangle2d bounds,list_footer_bounds;struct {long index;}text_font;}; +struct widget_instance {int type;void *parent;long definition_tag_index;}; +enum {_ui_widget_type_container,_ui_widget_type_text_box,_ui_widget_type_spinner_list}; +static char const *current_name; +static int frontend_menu_available(void){return 1;} +static char const *tag_get_name(long tag){return current_name;} +static long halo_screen_width(void){return 852;} +#define NONE -1 +static long tag_loaded(long group,char const *name){(void)group;(void)name;return 9;} +''' + source('port/linux/game/frontend_layout.c') + r''' +static void check(int type,short left,short right,short expected_right){ + struct widget_instance w={0,0,1},*widget=&w; + struct ui_widget_definition original={{left,0,right,480}},*definition=&original; + rectangle2d incoming={-106,0,746,480},*clip_rect=&incoming; + struct {short x,y;}offset={0,0}; +''' + integration.replace('frontend_layout = frontend_menu_geometry', 'w.type = type; frontend_layout = frontend_menu_geometry') + r''' + assert(clip_rect->x1==expected_right); + assert(original.bounds.x0==left&&original.bounds.x1==right); +} +int main(void){ + current_name="pc\\modern\\settings";check(_ui_widget_type_container,0,640,746); + /* Extended descriptions have no parent but their local bounds are not a viewport. */ + current_name="pc\\modern\\help";check(_ui_widget_type_text_box,396,596,746); + return 0; +} +''') + + +def test_panel_caps_preserve_shape_plasma_and_scope(tmp_path): + run_c(tmp_path, r''' +#include +#include +typedef float real; +struct dynamic_screen_vertex {struct {real x,y;}position,texture_coordinates;unsigned long color;}; +struct rasterizer_dynamic_screen_geometry_parameters {int plasma;}; +static int available=1,calls; +static char const *name="pc\\modern\\row_style"; +static struct dynamic_screen_vertex drawn[3][4]; +static struct rasterizer_dynamic_screen_geometry_parameters *expected; +static int frontend_menu_available(void){return available;} +static char const *tag_get_name(long tag){return name;} +static void rasterizer_psuedo_dynamic_screen_quad_draw(struct rasterizer_dynamic_screen_geometry_parameters *p,struct dynamic_screen_vertex *v){ + assert(p==expected&&p->plasma==1&&calls<3);memcpy(drawn[calls++],v,sizeof(drawn[0])); +} +''' + source('port/linux/game/frontend_panel.c') + r''' +int main(void){ + struct rasterizer_dynamic_screen_geometry_parameters p={1}; + struct dynamic_screen_vertex v[4]={{{-80,100},{0,0},0x55ffffff},{{256,100},{1,0},0x55ffffff}, + {{256,120},{1,1},0x55ffffff},{{-80,120},{0,1},0x55ffffff}}; + int widths[]={336,463,720},i,j,k; + expected=&p; + assert(!frontend_panel_draw(&p,v,336)); + for(i=0;i<3;i++){ + calls=0;v[1].position.x=v[2].position.x=v[0].position.x+widths[i]; + frontend_panel_begin(1);assert(frontend_panel_draw(&p,v,336)&&calls==3); + assert(drawn[0][1].position.x-drawn[0][0].position.x==18); + assert(drawn[2][1].position.x-drawn[2][0].position.x==18); + assert(drawn[0][0].position.x==v[0].position.x&&drawn[2][1].position.x==v[1].position.x); + assert(drawn[0][1].texture_coordinates.x==18.0f/336); + for(j=0;j<2;j++){ + assert(drawn[j][1].position.x==drawn[j+1][0].position.x); + assert(drawn[j][1].texture_coordinates.x==drawn[j+1][0].texture_coordinates.x); + } + for(j=0;j<3;j++)for(k=0;k<4;k++){ + assert(drawn[j][k].position.y==v[k].position.y); + assert(drawn[j][k].texture_coordinates.y==v[k].texture_coordinates.y); + assert(drawn[j][k].color==v[k].color); + } + frontend_panel_end();assert(!frontend_panel_draw(&p,v,336)); + } + name="pc\\modern\\help_panel";calls=0;frontend_panel_begin(1);assert(frontend_panel_draw(&p,v,232)); + name="ui\\shell\\main_menu";frontend_panel_begin(1);assert(!frontend_panel_draw(&p,v,336)); + name="pc\\modern\\title";frontend_panel_begin(1);assert(!frontend_panel_draw(&p,v,336)); + name="pc\\modern\\row_style";available=0;frontend_panel_begin(1);assert(!frontend_panel_draw(&p,v,336)); + available=1;frontend_panel_begin(1);assert(!frontend_panel_draw(&p,v,24)); + v[1].position.x=v[0].position.x+24;assert(!frontend_panel_draw(&p,v,336)); + return 0; +} +''') + + +def test_keyboard_labels_read_actual_binding_cache(tmp_path): + text = (ROOT / 'port/linux/src/xinput_sdl.c').read_text() + body = function(text, 'halo_keyboard_binding_label') + run_c(tmp_path, r''' +#include +#include +#include +#define NUMBER_OF_HALO_KEYBOARD_ACTIONS 2 +#define MAXIMUM_BINDINGS 2 +static int bindings[2][2]={{4,5},{-1,6}},reads; +static void bindings_read(void) {reads++;} +static void halo_input_name(int input,char *name,unsigned int size) {snprintf(name,size,"%s",input==4?"Z":input==5?"Mouse Left":"Wheel Up");} +static void halo_input_shown_name(char const *name,char *shown,unsigned int size) {snprintf(shown,size,"%s",!strcmp(name,"Z")?"Y":name);} +''' + body + r''' +int main(void) { + char label[64]; + assert(halo_keyboard_binding_label(0,0,label,sizeof(label))&&!strcmp(label,"Y")); + assert(halo_keyboard_binding_label(0,1,label,sizeof(label))&&!strcmp(label,"Mouse Left")); + assert(!halo_keyboard_binding_label(1,0,label,sizeof(label))&&!label[0]); + assert(halo_keyboard_binding_label(1,1,label,sizeof(label))&&!strcmp(label,"Wheel Up")); + bindings[0][0]=5;assert(halo_keyboard_binding_label(0,0,label,sizeof(label))&&!strcmp(label,"Mouse Left")); + assert(reads==5);assert(!halo_keyboard_binding_label(-1,0,label,sizeof(label))&&!label[0]); + assert(!halo_keyboard_binding_label(0,2,label,sizeof(label))&&!label[0]); + assert(!halo_keyboard_binding_label(0,0,0,0));return 0; +} +''') + + +def test_menu_actions_are_independent_of_gameplay_remaps(tmp_path): + text = (ROOT / 'port/linux/game/frontend_prompts.c').read_text() + header = (ROOT / 'port/linux/game/frontend_prompts.h').read_text() + enum = re.search(r'enum frontend_prompt_action.*?;', header).group() + run_c(tmp_path, '#include \n#include \n' + enum + '\n' + + function(text, 'frontend_prompt_button') + function(text, 'frontend_prompt_key') + r''' +int main(void) { + assert(frontend_prompt_button(FRONTEND_SELECT)==0); + assert(frontend_prompt_button(FRONTEND_CANCEL)==1); + assert(frontend_prompt_button(FRONTEND_STYLE)==3); + assert(!strcmp(frontend_prompt_key(FRONTEND_SELECT),"Return")); + assert(!strcmp(frontend_prompt_key(FRONTEND_CANCEL),"Escape")); + assert(!strcmp(frontend_prompt_key(FRONTEND_STYLE),"Tab")); + assert(frontend_prompt_button(99)==-1&&!frontend_prompt_key(99)[0]);return 0; +} +''') + + +def test_frontend_glyph_preferences_cache_failure_and_cleanup(tmp_path): + code = r''' +#include +#include +#include +#define TRUE 1 +#define FALSE 0 +typedef int boolean;typedef float real;typedef unsigned long pixel32; +typedef struct {short x0,y0,x1,y1;}rectangle2d; +#define csmemset memset +static void ce_hud_buttons_forget(void){} +struct bitmap_data {unsigned long *hardware_format;}; +struct icon_hud_element_definition {int unused;}; +struct dynamic_screen_vertex {struct {real x,y;}position,texture_coordinates;pixel32 color;}; +struct rasterizer_dynamic_screen_geometry_parameters { + struct bitmap_data *map[3];struct {real i,j;}map_texture_scale[3],map_scale[3];int framebuffer_blend_function; +}; +static int style,live,created,registered,fail,new_draws,draws; +static short observed_port; +static int controller_button_style_for_port(short p){observed_port=p;return style;} +static int controller_glyph_draw_menu(short s,short b,rectangle2d *r,pixel32 c){ + assert(s==style&&b>=0&&b<4);new_draws++;r->x0+=26;return 1; +} +static real draw_unicode_string_capital_middle(rectangle2d *r,void const *s){return 100;} +static struct bitmap_data *bitmap_2d_new(int w,int h,int m,int f){ + struct bitmap_data *b;assert(w==32&&h==32&&!m&&f==11);if(fail==1)return NULL; + b=calloc(1,sizeof(*b));live++;created++;return b; +} +static int rasterizer_bitmap_new(struct bitmap_data *b){b->hardware_format=(unsigned long*)b;return fail!=2;} +static void bitmap_delete(struct bitmap_data *b){free(b);live--;} +static void rasterizer_psuedo_dynamic_screen_quad_draw(struct rasterizer_dynamic_screen_geometry_parameters *p,struct dynamic_screen_vertex *v){ + assert(p->framebuffer_blend_function==0&&v[0].color==0x40ffffff); + assert(v[2].position.x>v[0].position.x&&v[2].position.y>v[0].position.y);draws++; +} +''' + code += (ROOT / 'port/linux/game/hud_button_layout.h').read_text() + hud = (ROOT/'port/linux/game/hud_hires_tags.c').read_text() + start = hud.index('static struct\n{\n\tstruct bitmap_data *bitmap;', hud.index('/* Original Xbox controller faces')) + state = hud[start:hud.index('/* ---------- private code */', start)] + code += 'long hud_hires_asset_count(void);\nchar const *hud_hires_asset_tag(long);\nvoid hud_hires_register_placeholder(long,unsigned long const *);\n' + code += state + function(hud, 'hud_hires_button_bitmap') + code += source('port/linux/game/frontend_glyphs.c') + r''' +long hud_hires_asset_count(void){return 12;} +char const *hud_hires_asset_tag(long a){static char const *names[]={ + "ui\\hud\\buttons\\classic_a","ui\\hud\\buttons\\classic_b","ui\\hud\\buttons\\classic_x","ui\\hud\\buttons\\classic_y", + "ui\\hud\\buttons\\gem_a","ui\\hud\\buttons\\gem_b","ui\\hud\\buttons\\gem_x","ui\\hud\\buttons\\gem_y", + "ui\\shell\\bitmaps\\a_butn","ui\\shell\\bitmaps\\b_butn","ui\\shell\\bitmaps\\x_butn","ui\\shell\\bitmaps\\y_butn"};return names[a];} +void hud_hires_register_placeholder(long a,unsigned long const *p){registered+=p?1:-1;} +int main(void){ + rectangle2d cursor={100,50,500,150};int repeat,before,button; + for(repeat=0;repeat<10;repeat++)for(style=0;style<11;style++)for(button=0;button<4;button++) { + cursor.x0=100;assert(frontend_glyph_draw(2,button,&cursor,0x40112233));assert(observed_port==2&&cursor.x0==126); + if(style<3){before=created;assert(hud_hires_button_bitmap(style,button));assert(created==before);} + } + assert(live==4&&created==120&®istered==4&&draws==120&&new_draws==320); + hud_buttons_forget();assert(!live&&!registered);hud_buttons_forget();assert(!live&&!registered); + style=0; + for(fail=1;fail<=2;fail++){ + before=created;assert(!frontend_glyph_draw(0,0,&cursor,0x40112233));assert(!live&&!registered); + assert(!frontend_glyph_draw(0,0,&cursor,0x40112233));assert(created==before+(fail==2));hud_buttons_forget(); + } + fail=0;assert(frontend_glyph_draw(0,0,&cursor,0x40112233));assert(live==1&®istered==1); + assert(!frontend_glyph_draw(-1,0,&cursor,0));assert(!frontend_glyph_draw(4,0,&cursor,0));assert(!frontend_glyph_draw(0,4,&cursor,0)); + hud_buttons_forget();assert(!live&&!registered);return 0; +} +''' + run_c(tmp_path, code) + + + +def test_manual_controller_prompts_follow_hud_gate_and_auto_source(tmp_path): + text = (ROOT/'port/linux/game/frontend_prompts.c').read_text() + header = (ROOT/'port/linux/game/frontend_prompts.h').read_text() + enum = re.search(r'enum frontend_prompt_action.*?;',header).group() + run_c(tmp_path, r""" +#include +#include +#define TRUE 1 +typedef struct {short x0,y0,x1,y1;}rectangle2d; +typedef unsigned long pixel32; +typedef struct {float alpha,red,green,blue;}real_argb_color; +static int hud=1,automatic=1,keyboard,device=-1,observed=99,calls; +static int config_boolean(char const *n){return !strcmp(n,"display.high_res_hud")?hud:automatic;} +static int keyboard_prompt_menu_enabled(int d){(void)d;return keyboard;} +static int frontend_menu_available(void){return 1;} +static char const *tag_get_name(long tag){(void)tag;return "pc\\modern\\prompts";} +static int frontend_input_device(void){return device;} +static void draw_string_get_color(real_argb_color *c){c->alpha=1.0f;} +static int frontend_glyph_draw(short d,short b,rectangle2d *r,pixel32 c){(void)d;(void)b;(void)r;(void)c;return 1;} +static void keyboard_glyph_draw(char const *s,rectangle2d *r,pixel32 c,int m){(void)s;(void)r;(void)c;(void)m;} +static void frontend_prompt_text(rectangle2d *r,char const *s){(void)r;(void)s;} +static void frontend_prompt_action(rectangle2d *r,int d,int a,char const *s,pixel32 c){(void)r;(void)a;(void)s;(void)c;observed=d;calls++;} +"""+enum+function(text,'frontend_prompts_draw')+r""" +int main(void){ + rectangle2d bounds={0,0,640,22}; + frontend_prompts_draw(1,&bounds);assert(observed==-1&&calls==3); + automatic=0;frontend_prompts_draw(1,&bounds);assert(observed==0); + hud=0;frontend_prompts_draw(1,&bounds);assert(observed==-1); + hud=1;keyboard=1;frontend_prompts_draw(1,&bounds);assert(observed==-1); + automatic=1;keyboard=0;device=2;frontend_prompts_draw(1,&bounds);assert(observed==2); + device=-2;calls=0;frontend_prompts_draw(1,&bounds);assert(!calls); + return 0; +} +""") + + +def test_keyboard_footer_draws_keycaps_for_manual_and_detected_input(tmp_path): + text = (ROOT/'port/linux/game/frontend_prompts.c').read_text() + header = (ROOT/'port/linux/game/frontend_prompts.h').read_text() + enum = re.search(r'enum frontend_prompt_action.*?;', header).group() + run_c(tmp_path, r''' +#include +#include +#define TRUE 1 +typedef struct {short x0,y0,x1,y1;} rectangle2d; +typedef unsigned long pixel32; +typedef struct {float alpha,red,green,blue;} real_argb_color; +static int automatic=1,hud=1,device=-1,keycaps,pads,plain_keys,touch_text; +static char const *manual="classic"; +static int config_boolean(char const *n){return !strcmp(n,"display.high_res_hud")?hud:!strcmp(n,"input.auto_button_detection")?automatic:0;} +static char const *config_string(char const *n){(void)n;return manual;} +static int frontend_menu_available(void){return 1;} +static char const *tag_get_name(long tag){(void)tag;return "pc\\modern\\prompts";} +static int frontend_input_device(void){return device;} +static void draw_string_get_color(real_argb_color *c){c->alpha=1.0f;} +static int frontend_glyph_draw(short d,short b,rectangle2d *r,pixel32 c){(void)d;(void)b;(void)r;(void)c;pads++;return 1;} +static void halo_input_shown_name(char const *s,char *out,unsigned int n){(void)n;strcpy(out,s);} +static void keyboard_glyph_draw(char const *s,rectangle2d *r,pixel32 c,int m){(void)s;(void)r;(void)c;assert(m);keycaps++;} +static void frontend_prompt_text(rectangle2d *r,char const *s){ + (void)r;if(!strcmp(s,"Return")||!strcmp(s,"Escape")||!strcmp(s,"Tab")||!strcmp(s,"Arrows: MOVE"))plain_keys++; + if(strstr(s,"Tap "))touch_text++; +} +''' + enum + function((ROOT/'port/linux/src/keyboard_prompts.c').read_text(), 'keyboard_prompt_menu_enabled') + + ''.join(function(text, n) for n in ('frontend_prompt_button','frontend_prompt_key','frontend_prompt_action','frontend_prompts_draw')) + r''' +int main(void){ + rectangle2d bounds={0,0,640,22};int i; + for(hud=0;hud<2;hud++) { + automatic=1;device=-1;manual="classic";keycaps=pads=plain_keys=0; + frontend_prompts_draw(1,&bounds);assert(keycaps==(hud?7:0)&&!pads);if(hud)assert(!plain_keys); + automatic=0;manual="keyboard"; + for(i=-2;i<4;i++) {device=i;keycaps=pads=plain_keys=0; + frontend_prompts_draw(1,&bounds);assert(keycaps==(hud?7:0)&&!pads);if(hud)assert(!plain_keys); + } + automatic=1;device=2;keycaps=pads=0; + frontend_prompts_draw(1,&bounds);assert(!keycaps&&pads==(hud?4:0)); + device=-2;keycaps=pads=touch_text=0; + frontend_prompts_draw(1,&bounds);assert(!keycaps&&!pads&&touch_text==1); + } + return 0; +} +''') diff --git a/tools/test_gulch_build_label.py b/tools/test_gulch_build_label.py new file mode 100644 index 0000000000..49f290ad78 --- /dev/null +++ b/tools/test_gulch_build_label.py @@ -0,0 +1,156 @@ +"""Exercise generated build metadata, the actual label and widget text ownership.""" + +import io +import os +from pathlib import Path +import re +import shutil +import subprocess +from types import SimpleNamespace + +import pytest + +from tools import android_build, linux_build, ninja_syntax, web_build, windows_build + +ROOT = Path(__file__).resolve().parents[1] + + +def function(source, name): + start = source.index("static void " + name + "(") + return source[start:source.index("\n}", start) + 2] + + +def run_handler(tmp_path, metadata_flags, expected): + tmp_path.mkdir(exist_ok=True) + compiler = os.environ.get("CC") or shutil.which("clang") or shutil.which("cc") + if not compiler: + pytest.skip("C compiler unavailable") + helpers = (ROOT / "port/linux/game/menu_functions.c").read_text(encoding="utf-8") + code = r''' +#include +#include +#include +#include +#include +typedef int boolean; +#define TRUE 1 +#define FALSE 0 +#define NUMBEROF(a) (sizeof(a) / sizeof((a)[0])) +#define ROW_TEXT_LENGTH 64 +struct widget_instance { + int type; long definition_tag_index; + struct { struct { wchar_t *text; } text_box; } parameters; +}; +static char const *current_name; +static long allocations; +static char const *tag_get_name(long index) { return index == 7 ? current_name : NULL; } +static void *ui_widget_realloc(void *old, size_t size, char const *file, long line) { + (void)file; (void)line; allocations++; assert(old == NULL); + return malloc(size); +} +static void ustrncpy(wchar_t *target, wchar_t const *text, size_t length) { + size_t i; for(i=0;iparameters.text_box.text) return 0; + for(i=0;expected[i];i++) if(widget->parameters.text_box.text[i] != (unsigned char)expected[i]) return 0; + return widget->parameters.text_box.text[i]==0; +} +''' + function(helpers, "text_set_length") + "\n" + function(helpers, "text_set") + r''' +#include "gulch_build_label.inl" +int main(void) { + struct widget_instance widget={0}, other={0}; + wchar_t *owned; + assert(sizeof(wchar_t)==2); + widget.type=1;widget.definition_tag_index=7; + current_name="pc\\main_menu\\gulch_build_number"; + assert(gulch_build_label_event(&widget)); + assert(text_is(&widget, EXPECTED));assert(allocations==1); + owned=widget.parameters.text_box.text; + assert(gulch_build_label_event(&widget));assert(widget.parameters.text_box.text==owned); + assert(allocations==1 && text_is(&widget, EXPECTED)); + assert(!gulch_build_label_event(NULL)); + other.type=1;other.definition_tag_index=7; + current_name="pc\\main_menu\\build_number"; + assert(!gulch_build_label_event(&other));assert(!other.parameters.text_box.text); + current_name="pc\\main_menu\\gulch_build_number_extra"; + assert(!gulch_build_label_event(&other)); + current_name="pc\\main_menu\\gulch_build_number"; + other.type=0;assert(!gulch_build_label_event(&other));other.type=1; + other.definition_tag_index=8;assert(!gulch_build_label_event(&other));other.definition_tag_index=7; + assert(allocations==1); + free(widget.parameters.text_box.text); + return 0; +} +''' + source = tmp_path / "build_label.c" + binary = tmp_path / ("build_label.exe" if os.name == "nt" else "build_label") + source.write_text(code, encoding="utf-8") + flags = ["-std=gnu89", "-fshort-wchar", "-Wall", "-Wextra", "-Werror", + "-I", str(ROOT / "port/linux/game"), f'-DEXPECTED="{expected}"'] + flags.extend(metadata_flags) + if os.name == "nt": + flags.insert(0, "--target=i686-pc-windows-msvc") + built = subprocess.run([compiler, *flags, str(source), "-o", str(binary)], + capture_output=True, text=True) + assert built.returncode == 0, built.stdout + built.stderr + subprocess.run([str(binary)], check=True, capture_output=True, text=True) + + +@pytest.mark.parametrize("number,expected", [ + (0, "gulch build local"), (321, "gulch build 321"), + (2147483647, "gulch build 2147483647"), +]) +def test_handler_uses_executable_build_and_owns_only_its_widget(tmp_path, number, expected): + run_handler(tmp_path, [f"-DHALO_BUILD_NUMBER={number}"], expected) + + +def menu_compile_flags(platform, monkeypatch, tmp_path): + """Run the real graph generators without downloading or compiling dependencies.""" + output = io.StringIO() + sln = SimpleNamespace(build_dir=tmp_path / "graph", linux_cc="clang", windows_cc="clang", + compiler_launcher=None, port_release=True, port_profile=False, + port_portable=False, port_lto="off", port_pgo="off", port_pgo_profile=None, + web_emcc="/test/emsdk/emcc", android_guest_cc="clang") + with monkeypatch.context() as setup: + setup.chdir(ROOT) + if platform == "windows": + setup.setattr(windows_build.sys, "platform", "win32") + setup.setattr(windows_build, "fetch_sdl", lambda: None) + setup.setattr(windows_build, "inline_export_wrapper", lambda source: source) + generate = windows_build.generate_windows_build + elif platform == "android": + sln.android_ndk = tmp_path / "ndk" + (sln.android_ndk / "toolchains/llvm/prebuilt/test-host").mkdir(parents=True, exist_ok=True) + setup.setenv("ANDROID_NDK_HOST_TAG", "test-host") + setup.setattr(android_build, "fetch_third_party", lambda: None) + generate = android_build.generate_android_build + else: + generate = {"linux": linux_build.generate_linux_build, + "web": web_build.generate_web_build}[platform] + generate(ninja_syntax.Writer(output), sln) + text = re.sub(r" \$\n *", " ", output.getvalue()) + rule = "android_guest_cc" if platform == "android" else platform + "_cc" + source = r"port[/\\]linux[/\\]game[/\\]menu_functions\.c" + match = re.search(r"^build [^\n]*: " + rule + " " + source + + r"(?: [^\n]*)?\n cflags = ([^\n]*)", text, re.M) + assert match, f"{platform} graph did not compile menu_functions.c" + return match.group(1) + + +@pytest.mark.parametrize("platform", ["linux", "windows", "android", "web"]) +def test_generated_menu_flags_reach_the_actual_label_and_reset_to_local(platform, monkeypatch, tmp_path): + for number in (192, None): + if number is None: + monkeypatch.delenv("HALO_BUILD_NUMBER", raising=False) + else: + monkeypatch.setenv("HALO_BUILD_NUMBER", str(number)) + flags = menu_compile_flags(platform, monkeypatch, tmp_path) + metadata = re.findall(r"-DHALO_BUILD_NUMBER=\S+", flags) + assert metadata == [f"-DHALO_BUILD_NUMBER={number or 0}"], flags + expected = f"gulch build {number}" if number else "gulch build local" + run_handler(tmp_path / ("numbered" if number else "local"), metadata, expected) diff --git a/tools/test_gulchce_updater.py b/tools/test_gulchce_updater.py new file mode 100644 index 0000000000..6a9af0a549 --- /dev/null +++ b/tools/test_gulchce_updater.py @@ -0,0 +1,86 @@ +"""Exercise the actual desktop release checker without downloading/installing files.""" +from pathlib import Path +import os +import re +import shutil +import subprocess + +import pytest +from harness import function + +ROOT = Path(__file__).resolve().parents[1] + + +def test_release_feed_and_build_comparison(tmp_path): + compiler = shutil.which("clang") + if not compiler: + pytest.skip("clang is required") + source = (ROOT / "port/linux/src/updater.c").read_text() + repository = re.search(r'^#define UPDATE_REPOSITORY .*$', source, re.M).group() + harness = r''' +#include +#include +#include +#include +#define HALO_BUILD_NUMBER 60 +#define MAXIMUM_CHECK_SIZE (1024ULL * 1024) +#define SDLCALL +#define SDL_free free +enum { _updater_idle, _updater_checking, _updater_available, _updater_handled }; +static int updater_state, download_ok = 1, deleted; +static long updater_latest_build, updater_latest_network_version, updater_release_network_version; +static const char *response; +static void updater_path(char *path, size_t size, const char *name) { + snprintf(path, size, "%s", name); +} +static int update_download(const char *url, const char *path, unsigned long long maximum, void *a, void *b, + char *error, size_t size) { + assert(!strcmp(url, "https://api.github.com/repos/chestahh/GulchCE/releases/latest")); + assert(maximum == MAXIMUM_CHECK_SIZE); + return download_ok; +} +static char *SDL_LoadFile(const char *path, size_t *size) { + char *copy = malloc(strlen(response) + 1); + strcpy(copy, response); *size = strlen(response); return copy; +} +static void update_delete_file(const char *path) { deleted++; } +static void platform_log(const char *format, ...) {} +static void SDL_SetAtomicInt(int *state, int value) { *state = value; } +''' + harness += repository + "\n" + function(source, "updater_latest_release") + harness += "\n" + function(source, "updater_check_thread") + harness += r''' +int main(void) { + response = "{\"tag_name\":\"build-61\"}"; + updater_check_thread(NULL); + assert(updater_state == _updater_available && updater_latest_build == 61); + assert(deleted == 1 && updater_latest_network_version == 0); + response = "{\"tag_name\":\"build-62\",\"body\":\"Network version: 41\"}"; + updater_check_thread(NULL); + assert(updater_latest_build == 62 && updater_latest_network_version == 41); + response = "{\"tag_name\":\"build-60\"}"; + updater_check_thread(NULL); assert(updater_state == _updater_handled); + response = "{\"tag_name\":\"build-59\"}"; + updater_check_thread(NULL); assert(updater_state == _updater_handled); + response = "{\"message\":\"Not Found\"}"; + updater_check_thread(NULL); assert(updater_state == _updater_handled); + download_ok = 0; + updater_check_thread(NULL); assert(updater_state == _updater_handled); + return 0; +} +''' + test = tmp_path / "updater.c" + binary = tmp_path / "release_check.exe" + test.write_text(harness) + flags = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld"] if os.name == "nt" else [] + subprocess.run([compiler, *flags, str(test), "-o", str(binary)], check=True, capture_output=True) + subprocess.run([str(binary)], check=True, capture_output=True) + + +def test_android_and_downloads_use_the_same_repository(): + desktop = (ROOT / "port/linux/src/updater.c").read_text() + android = (ROOT / "port/android/app/src/main/java/com/halo/decomp/Updater.java").read_text() + assert 'REPOSITORY = "chestahh/GulchCE"' in android + assert '"https://github.com/" UPDATE_REPOSITORY "/releases/download/build-' in desktop + assert '"https://github.com/" + REPOSITORY + "/releases/download/build-' in android + assert "OpenCommunityEdition/OpenCE" not in desktop + android diff --git a/tools/test_hires_live_settings.py b/tools/test_hires_live_settings.py new file mode 100644 index 0000000000..a58705b56f --- /dev/null +++ b/tools/test_hires_live_settings.py @@ -0,0 +1,140 @@ +"""Live high-res toggles: run the production cache and font-selection code.""" +from pathlib import Path +from harness import function +from test_hud_button_style import run_c +ROOT=Path(__file__).resolve().parents[1] + + +def test_only_committed_affected_textures_are_refreshed(tmp_path): + hud=(ROOT/'port/linux/src/hud_hires.c').read_text() + texture=(ROOT/'port/linux/src/xbox_textures.c').read_text() + code=r''' +#include +#include +#include +static unsigned long revision; +static int hud_on=1,text_on=1; +static unsigned long config_changes(void){return revision;} +static int config_boolean(char const *s){return strstr(s,"high_res_hud")?hud_on:text_on;} +static struct {int title;} hud_hires_embedded[2]={{0},{1}}; +static long hud_hires_asset_count(void){return 2;} +static long hud_hires_asset_at(unsigned long a,long w,long h){return w==32 && h==32 && a<2?(long)a:-1;} +#define TEXTURE_BUCKET_COUNT 4 +#define TEXTURE_IDLE_FRAMES 1800 +/* Current production cache sweeps by elapsed SDL time, not frame count. */ +typedef unsigned long long Uint64; +#define TEXTURE_SWEEP_SECONDS 10 +#define TEXTURE_SWEEP_COUNT 3 +static unsigned long texture_sweep_frames[TEXTURE_SWEEP_COUNT],texture_sweep_count; +static Uint64 texture_next_sweep; +static Uint64 SDL_GetTicks(void){return 0;} +struct texture_entry { + struct texture_entry *next; unsigned long address,generation,last_used_frame; + struct {unsigned long width,height;} description; + unsigned texture,hud_upscale; +}; +static struct texture_entry *texture_buckets[TEXTURE_BUCKET_COUNT]; +static unsigned long texture_frame,texture_drop_serial; +static unsigned long recent_textures[8]; +static int invalidated,deleted; +static void glDeleteTextures(int n,unsigned const *t){(void)n;(void)t;deleted++;} +static void xgpu_gl_state_invalidate(void){invalidated++;} +''' + function(hud,'hud_hires_settings_changed')+'\n'+function(hud,'hud_hires_bitmap_affected')+'\n'+function(texture,'xgpu_texture_cache_begin_frame')+r''' +int main(void){ + struct texture_entry h={0},t={0},world={0};int i; + h.address=0;t.address=1;world.address=99; + h.description.width=t.description.width=world.description.width=32; + h.description.height=t.description.height=world.description.height=32; + texture_buckets[0]=&h;h.next=&t;t.next=&world; + h.generation=t.generation=world.generation=42; + xgpu_texture_cache_begin_frame();assert(h.generation==42 && t.generation==42); + for(i=0;i<20;i++){ + /* An unrelated saved setting (or an uncommitted menu edit) is harmless. */ + revision++;xgpu_texture_cache_begin_frame();assert(h.generation==42 && t.generation==42); + recent_textures[0]=99;hud_on=!hud_on;revision++; + xgpu_texture_cache_begin_frame();assert(h.generation==0 && t.generation==42 && world.generation==42); + assert(recent_textures[0]==0);h.generation=42; + text_on=!text_on;revision++;xgpu_texture_cache_begin_frame(); + assert(t.generation==0 && h.generation==42 && world.generation==42);t.generation=42; + } + assert(invalidated==40 && deleted==0); + /* Map address reuse is classified against the new map's tags, not old choices. */ + h.address=99;hud_on=!hud_on;revision++;xgpu_texture_cache_begin_frame();assert(h.generation==42); + return 0; +} +''' + run_c(tmp_path,code) + + +def test_text_can_start_disabled_and_toggle_without_caching_none(tmp_path): + text=(ROOT/'port/linux/src/text_hires.c').read_text() + source=(ROOT/'source/rasterizer/rasterizer_text.c').read_text() + code=r''' +#include +#include +typedef float real;typedef unsigned short word;typedef unsigned char byte; +#define NONE -1 +#define TEXT_HIRES_FIT_LETTERS 52 +#define MAXIMUM_HIRES_TEXT_FONTS 4 +static int enabled,calls;static unsigned long revision; +static unsigned long config_changes(void){return revision;} +static int config_boolean(char const *s){(void)s;return enabled;} +struct font_header{struct{void *address;}pixels;}; +struct font_character{int character_width,bitmap_height,bitmap_width,pixels_offset;}; +static byte ink[]={255};static struct font_header font={{ink}}; +static struct font_character capital={5,1,1,0}; +static struct {struct font_header *font;real oversample;long hires_font;}hires_text_fonts[4]; +static short hires_text_next_font; +static struct font_header *font_definition_get(long n){(void)n;return &font;} +static struct font_character *font_get_character_by_ascii_code(struct font_header *f,word c){(void)f;(void)c;return &capital;} +static char const *tag_get_name(long n){(void)n;return "ui\\small_ui";} +static long text_hires_font(char const *n,float h,short const *w,float o){(void)n;(void)h;(void)w;(void)o;calls++;return 7;} +''' + function(text,'text_hires_enabled')+'\n'+function(source,'hires_text_font_get')+r''' +int main(void){int i; + assert(hires_text_font_get(1,1)==NONE && calls==0); + for(i=0;i<20;i++){ + enabled=1;revision++;assert(hires_text_font_get(1,1)==7); + assert(hires_text_font_get(1,1)==7); + enabled=0;revision++;assert(hires_text_font_get(1,1)==NONE); + } + assert(calls==1); /* No atlas/font rebuild on a toggle. */ + enabled=1;revision++;assert(hires_text_font_get(1,.75f)==7 && calls==2); + memset(hires_text_fonts,0,sizeof(hires_text_fonts));hires_text_next_font=0; + assert(hires_text_font_get(1,1)==7 && calls==3); + return 0; +} +''' + run_c(tmp_path,code) + + +def test_menu_changes_commit_only_on_save(tmp_path): + source=(ROOT/'port/linux/game/menu_functions.c').read_text() + code=r''' +#include +#include +#include +typedef int boolean; +#define TRUE 1 +#define FALSE 0 +#define NONE -1 +static int committed=1,writes; +struct widget_instance {int definition_tag_index;struct{struct{short selected_index,number_of_items;}list;}parameters;}; +struct pc_menu_setting {char const *setting;short loaded_index,value_count;char const *values[2];}; +static struct pc_menu_setting setting={"display.high_res_hud",-1,2,{"true","false"}}; +static struct pc_menu_setting *pc_menu_setting_get(int i){(void)i;return &setting;} +static int spinner_item(struct widget_instance *w){(void)w;return 0;} +static int setting_text(char const *s,char *out,size_t n,int def){(void)s;(void)n;(void)def;strcpy(out,committed?"true":"false");return 1;} +static int setting_value_index(struct pc_menu_setting *s,char const *v){(void)s;return strcmp(v,"true")!=0;} +static int config_write(char const *s,char const *v){(void)s;committed=!strcmp(v,"true");writes++;return 1;} +static void platform_log(char const *s,...){(void)s;} +'''+'\n'+function(source,'setting_load')+'\n'+function(source,'setting_save')+r''' +int main(void){struct widget_instance w={0};w.parameters.list.number_of_items=2; + assert(setting_load(&w));w.parameters.list.selected_index=1; + assert(committed && writes==0); /* Selecting No does not commit. */ + assert(setting_load(&w));assert(w.parameters.list.selected_index==0 && committed); /* Reopen after Cancel. */ + w.parameters.list.selected_index=1;assert(setting_save(&w));assert(!committed && writes==1); + assert(setting_save(&w));assert(writes==1); + w.parameters.list.selected_index=0;assert(!committed);assert(setting_save(&w));assert(committed && writes==2); + return 0;} +''' + run_c(tmp_path,code) diff --git a/tools/test_hud_ammo_thresholds.py b/tools/test_hud_ammo_thresholds.py new file mode 100644 index 0000000000..281f710e5b --- /dev/null +++ b/tools/test_hud_ammo_thresholds.py @@ -0,0 +1,234 @@ +"""Render the real NV2A meter shader and committed atlas in a hidden GL context. + +Exercises all 256 cutoffs of six ammunition sprites at five HUD scales +and fractional placement, comparing the original and corrected sampling. No game assets or player profile are needed. +""" +import argparse +import json +import os +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +import numpy as np +from PIL import Image + +from hud_assets import add_meter_thresholds + +ROOT = Path(__file__).resolve().parents[1] + + +def block(source, marker): + start = source.index(marker) + end = source.index('{', start) + 1 + depth = 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +PRELUDE = r''' +#define _CRT_SECURE_NO_WARNINGS +#include +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +typedef unsigned long DWORD, D3DCOLOR; +#else +typedef uint32_t DWORD, D3DCOLOR; +#endif +typedef int BOOL; +#define TRUE 1 +#define FALSE 0 +#define __HALO_LINUX_PLATFORM_H +#define CHECK(c) do { if (!(c)) {fprintf(stderr,"FAIL %d: %s\n",__LINE__,#c);exit(1);} } while(0) +''' + +HARNESS = r''' +#include "xgpu.h" +#define GL_DEFINE(name) __typeof__(name) name; +GL_FUNCTIONS(GL_DEFINE) +#undef GL_DEFINE +BOOL xgpu_reversed_depth; +int config_boolean(const char *name) {return 0;} +const char *config_string(const char *name) {return "";} +static DWORD real_alpha_to_pixel32(float a) {return (DWORD)(a*255.0f+0.5f)<<24;} +#define MAX(a,b) ((a)>(b)?(a):(b)) +struct meter_parameters { + DWORD gradient_min_color, gradient_max_color, flash_color, background_color, tint_color; + float gradient; BOOL flash_color_is_negative; +}; +static struct nv2a_pixel_shader_key meter_key(struct meter_parameters *meter, BOOL point) { + struct nv2a_pixel_shader_key key={0}; + key.sampler_type[0]=_xgpu_sampler_2d; + key.alpha_kill[0]=1; key.coverage_alpha=1; key.point_threshold=point; + METER_SETUP + return key; +} +static GLuint shader(GLenum type,const char *text) { + GLuint s=glCreateShader(type);glShaderSource(s,1,&text,NULL);glCompileShader(s); + GLint ok;glGetShaderiv(s,GL_COMPILE_STATUS,&ok); + if(!ok){char log[8192];glGetShaderInfoLog(s,sizeof(log),NULL,log);fprintf(stderr,"%s\n%s",log,text);exit(1);}return s; +} +static GLuint program(struct nv2a_pixel_shader_key *key) { + const char *vs="#version 450 core\n" + "uniform vec4 uv_rect; out vec4 xD0,xD1,xB0,xB1,xT0,xT1,xT2,xT3;out float xFog;out vec2 shield_uv;" + "void main(){vec2 p=vec2((gl_VertexID<<1)&2,gl_VertexID&2);" + "gl_Position=vec4(p*2.0-1.0,0,1);xT0=vec4(uv_rect.xy+p*uv_rect.zw,0,1);" + "xD0=xD1=xB0=xB1=xT1=xT2=xT3=vec4(0);xFog=0;shield_uv=vec2(0);}"; + char *fs=nv2a_pixel_shader_to_glsl(key);GLuint v=shader(GL_VERTEX_SHADER,vs),f=shader(GL_FRAGMENT_SHADER,fs); + free(fs);GLuint p=glCreateProgram();glAttachShader(p,v);glAttachShader(p,f);glLinkProgram(p); + GLint ok;glGetProgramiv(p,GL_LINK_STATUS,&ok);CHECK(ok);glDeleteShader(v);glDeleteShader(f);return p; +} +static void constants(GLuint p,struct nv2a_pixel_shader_key *key) { + float c[8][4]; + for(int bank=0;bank<2;bank++) { + for(int i=0;i<8;i++) { + DWORD v=key->combiner_state[D3DRS_PSCONSTANT0_0+8*bank+i]; + c[i][0]=((v>>16)&255)/255.0f;c[i][1]=((v>>8)&255)/255.0f;c[i][2]=(v&255)/255.0f;c[i][3]=((v>>24)&255)/255.0f; + } + glUniform4fv(glGetUniformLocation(p,bank?"ps_c1":"ps_c0"),8,(float*)c); + } + float scale[4][4]={{1,1,1,1},{1,1,1,1},{1,1,1,1},{1,1,1,1}}; + glUniform4fv(glGetUniformLocation(p,"texture_scale"),4,(float*)scale); + glUniform1i(glGetUniformLocation(p,"tex0"),0); +} +static void draw(GLuint p,struct nv2a_pixel_shader_key *key,int *rect,int w,int h,float shift,unsigned char *out) { + glUseProgram(p);constants(p,key); + float uv[4]={(rect[0]+shift)/2048.0f,(rect[1]+shift)/2048.0f, + (rect[2]-rect[0])/2048.0f,(rect[3]-rect[1])/2048.0f}; + glUniform4fv(glGetUniformLocation(p,"uv_rect"),1,uv); + glViewport(0,0,w,h);glClearColor(32/255.0f,48/255.0f,64/255.0f,1);glClear(GL_COLOR_BUFFER_BIT); + glEnable(GL_BLEND);glBlendColor(1,1,1,1);glBlendFunc(GL_CONSTANT_COLOR,GL_SRC_ALPHA); + glDrawArrays(GL_TRIANGLES,0,3);glReadPixels(0,0,w,h,GL_RGBA,GL_UNSIGNED_BYTE,out); + CHECK(glGetError()==GL_NO_ERROR); +} +int main(int argc,char **argv) { + CHECK(SDL_Init(SDL_INIT_VIDEO));SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION,4); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION,5);SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK,SDL_GL_CONTEXT_PROFILE_CORE); + SDL_Window *window=SDL_CreateWindow("HUD regression",16,16,SDL_WINDOW_OPENGL|SDL_WINDOW_HIDDEN);CHECK(window); + SDL_GLContext context=SDL_GL_CreateContext(window);CHECK(context); +#define LOAD(name) name=(__typeof__(name))SDL_GL_GetProcAddress(#name);CHECK(name); + GL_FUNCTIONS(LOAD) +#undef LOAD + unsigned char *atlas=malloc(2048*2048*4),*out=malloc(1040*272*4),*reference=malloc(1040*272*4); + FILE *input=fopen(argv[1],"rb");CHECK(input);CHECK(fread(atlas,1,2048*2048*4,input)==2048*2048*4);fclose(input); + GLuint texture,target,fbo,vao;glGenTextures(1,&texture);glBindTexture(GL_TEXTURE_2D,texture); + glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA8,2048,2048,0,GL_RGBA,GL_UNSIGNED_BYTE,atlas);glGenerateMipmap(GL_TEXTURE_2D); + glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_LINEAR);glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE); + glGenTextures(1,&target);glBindTexture(GL_TEXTURE_2D,target);glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA8,1040,272,0,GL_RGBA,GL_UNSIGNED_BYTE,NULL); + glGenFramebuffers(1,&fbo);glBindFramebuffer(GL_FRAMEBUFFER,fbo);glFramebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0,GL_TEXTURE_2D,target,0); + CHECK(glCheckFramebufferStatus(GL_FRAMEBUFFER)==GL_FRAMEBUFFER_COMPLETE);glBindTexture(GL_TEXTURE_2D,texture); + glGenVertexArrays(1,&vao);glBindVertexArray(vao);glDisable(GL_DITHER); + struct meter_parameters meter={.gradient_min_color=0xffffffff,.gradient_max_color=0xffffff, + .flash_color=0xff000000,.background_color=0xff000000,.tint_color=0xbfffffff,.gradient=1}; + struct nv2a_pixel_shader_key key=meter_key(&meter,TRUE),legacy=meter_key(&meter,FALSE); + GLuint fixed=program(&key),old=program(&legacy); + int rects[][4]={HEALTH_RECTS};int divisions[]={1,2,3,4,8};int renders=0,old_ghosts=0; + for(int s=0;s<6;s++) for(int size=0;size<5;size++) for(int offset=0;offset<2;offset++) for(int bars=0;bars<=255;bars++) { + int *r=rects[s],w=(r[2]-r[0])/divisions[size],h=(r[3]-r[1])/divisions[size]; + int q=bars;float shift=offset?0.37f:0; + meter.gradient_min_color=(q<<24)|0xffffff;meter.flash_color=q<<24; + key=meter_key(&meter,TRUE);legacy=meter_key(&meter,FALSE); + draw(fixed,&key,r,w,h,shift,out);draw(old,&legacy,r,w,h,shift,reference); + int filled=0; + for(int y=0;y0); + /* Interpolation can land either side of an exact texel boundary. + Verify only unambiguous categorical expectations at those ties. */ + int ambiguous=0; + for(int dy=-1;dy<=1;dy+=2)for(int dx=-1;dx<=1;dx+=2) { + int tx=(int)floorf(px+dx*0.001f),ty=(int)floorf(py+dy*0.001f); + if((atlas[4*(ty*2048+tx)]>=q)!=(threshold>=q))ambiguous=1; + } + if(ambiguous)continue; + if(threshold>=q) { + if(out[at]!=32 || out[at+1]!=48 || out[at+2]!=64) fprintf(stderr,"sprite=%d division=%d shift=%f bars=%d x=%d y=%d atlas=%d,%d threshold=%d q=%d rgb=%d,%d,%d\n",s,divisions[size],shift,bars,x,y,ax,ay,threshold,q,out[at],out[at+1],out[at+2]); + CHECK(out[at]==32 && out[at+1]==48 && out[at+2]==64); + if(reference[at]!=32 || reference[at+1]!=48 || reference[at+2]!=64)old_ghosts++; + } else if(out[at]>32)filled++; + } + renders++; + } + CHECK(old_ghosts>0); + /* Red zero in continuous sprites: new sampling must produce identical output. */ + /* The unmodified Xbox/disabled-hires shader has no extra fetch. */ + char *text=nv2a_pixel_shader_to_glsl(&legacy);CHECK(!strstr(text,"texelFetch"));free(text); + printf("PASS: %d real GL ammunition renders, all 256 cutoffs, six ammo sprites, five scales, fractional placement; %d legacy ghost samples eliminated\n",renders,old_ghosts); + glDeleteTextures(1,&texture);glDeleteTextures(1,&target);glDeleteFramebuffers(1,&fbo); + free(atlas);free(out);free(reference);SDL_GL_DestroyContext(context);SDL_DestroyWindow(window);SDL_Quit();return 0; +} +''' + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--cc', default='clang') + args = parser.parse_args() + entry = next(e for e in json.loads((ROOT / 'port/assets/hud/layout.json').read_text())['assets'] + if e['name'] == 'hud_ammo_meters__0') + atlas = np.asarray(Image.open(ROOT / 'port/assets/hud/hud_ammo_meters__0.png')).copy() + rebuilt = add_meter_thresholds(atlas.copy(), entry) + assert np.array_equal(atlas, rebuilt), 'committed thresholds must match the generator' + rects = [[value * entry['scale'] for value in c['xbox']] for c in entry['cells'] if c.get('thresholds')] + assert len(rects) == 6 + for rect, cell in zip(rects, [c for c in entry["cells"] if c.get("thresholds")]): + x, y, right, bottom = rect + assert set(np.unique(atlas[y:bottom, x:right, 0])) == set(cell["thresholds"]) + for c in entry['cells']: + if not c.get('thresholds'): + x, y, right, bottom = [value * entry['scale'] for value in c['xbox']] + assert not atlas[y:bottom, x:right, 0].any() + # Use the game's actual combiner setup, rather than a substitute shader. + source = (ROOT / 'source/rasterizer/xbox/rasterizer_xbox_dynavobgeom.c').read_text() + setup = source[source.index('pixel_shader.texture_modes = 1;'):source.index('\n\t}\n\telse if (parameters->map[0])')] + fields = {'texture_modes': 'key.texture_modes', 'combiner_count': 'key.combiner_state[D3DRS_PSCOMBINERCOUNT]', + 'final_combiner_inputs_abcd': 'key.combiner_state[D3DRS_PSFINALCOMBINERINPUTSABCD]', + 'final_combiner_inputs_efg': 'key.combiner_state[D3DRS_PSFINALCOMBINERINPUTSEFG]'} + for name, index in {'constant_0': 'PSCONSTANT0_0', 'constant_1': 'PSCONSTANT1_0', + 'alpha_inputs': 'PSALPHAINPUTS0', 'rgb_inputs': 'PSRGBINPUTS0', + 'alpha_outputs': 'PSALPHAOUTPUTS0', 'rgb_outputs': 'PSRGBOUTPUTS0'}.items(): + setup = re.sub(r'pixel_shader\.' + name + r'\[(\d+)\]', r'key.combiner_state[D3DRS_' + index + r'+\1]', setup) + for name, expression in fields.items(): + setup = setup.replace('pixel_shader.' + name, expression) + assert 'pixel_shader.' not in setup + enums = (ROOT / 'port/include/xdk/xdk_pdb.h').read_text() + unit = PRELUDE + '\n'.join(block(enums, 'enum ' + name + ' {') + ';' for name in + ['_D3DRENDERSTATETYPE', '_D3DCMPFUNC', '_D3DFOGMODE']) + unit += HARNESS.replace('METER_SETUP', setup).replace('HEALTH_RECTS', ','.join('{' + ','.join(map(str, r)) + '}' for r in rects)) + # Compile the production translator and string builder with only platform/config stubs. + unit += '\n' + (ROOT / 'port/linux/src/xgpu_text.c').read_text() + for name in ('mcc_environment_shader_gl.c', 'plasma_model_shader.c', 'nv2a_psh.c'): + unit += '\n' + (ROOT / 'port/linux/src' / name).read_text() + compiler = [args.cc, '-std=gnu11', '-O2', '-fuse-ld=lld', '-I' + str(ROOT / 'port/linux/src'), '-I' + str(ROOT / 'port/linux/game'), '-iquote' + str(ROOT / 'port/linux/include')] + env = dict(os.environ) + if sys.platform == 'win32': + sdl = next((ROOT / 'build/windows/third_party').glob('SDL3-*/include')).parent + compiler += ['--target=i686-pc-windows-msvc', '-I' + str(sdl / 'include')] + libraries = [str(sdl / 'lib/x86/SDL3.lib')] + env['PATH'] = str(sdl / 'lib/x86') + os.pathsep + env['PATH'] + else: + compiler += subprocess.check_output(['pkg-config', '--cflags', 'sdl3'], text=True).split() + libraries = subprocess.check_output(['pkg-config', '--libs', 'sdl3'], text=True).split() + ['-lm'] + with tempfile.TemporaryDirectory(prefix='halo-hud-test-') as directory: + path = Path(directory) + (path / 'hud.c').write_text(unit) + (path / 'atlas.rgba').write_bytes(atlas.tobytes()) + subprocess.run([*compiler, str(path / 'hud.c'), *libraries, '-o', str(path / 'hud.exe')], check=True) + subprocess.run([str(path / 'hud.exe'), str(path / 'atlas.rgba')], env=env, check=True, timeout=180) + + +if __name__ == '__main__': + main() + diff --git a/tools/test_hud_button_style.py b/tools/test_hud_button_style.py index 803e1da6d1..07b9bf3c62 100644 --- a/tools/test_hud_button_style.py +++ b/tools/test_hud_button_style.py @@ -11,7 +11,7 @@ ROOT = Path(__file__).resolve().parents[1] -def run_c(tmp_path, code): +def run_c(tmp_path, code, link_math=False): compiler = shutil.which('clang') if not compiler: pytest.skip('clang required') @@ -19,7 +19,8 @@ def run_c(tmp_path, code): binary = tmp_path / 'style.exe' source.write_text(code) target = ['--target=i686-pc-windows-msvc'] if sys.platform == 'win32' else ['-m32'] - result = subprocess.run([compiler, *target, '-std=gnu89', '-O1', str(source), '-o', str(binary)], + libraries = ['-lm'] if link_math and sys.platform != 'win32' else [] + result = subprocess.run([compiler, *target, '-std=gnu89', '-O1', str(source), '-o', str(binary), *libraries], capture_output=True, text=True) assert result.returncode == 0, result.stderr subprocess.run([str(binary)], check=True, timeout=10) @@ -86,16 +87,20 @@ def test_supplied_gems_preserve_transparency_and_fit_existing_bounds(): assert abs((bounds[1]+bounds[3])-(reference[1]+reference[3])) <= 1 -def test_legacy_button_styles_toggle_and_dispose(tmp_path): - path = ROOT / 'port/linux/game' / ('hud_hires_tags.c') +@pytest.mark.parametrize('mcc', [False, True]) +def test_six_button_styles_toggle_and_dispose(tmp_path, mcc): + path = ROOT / 'port/linux/game' / ('mcc_hud_draw.c' if mcc else 'hud_hires_tags.c') source = path.read_text() - start = source.index('/* Original Xbox controller faces') - end = source.index('/* ---------- private code */', start) + start = source.index('static struct' if mcc else '/* Original Xbox controller faces') + end = source.index('/* Identify the controller entry' if mcc else '/* ---------- private code */', start) state = source[start:end] - names = ['hud_hires_button_bitmap', 'hud_hires_button_draw'] + if mcc: + state = source[start:source.index('static short mcc_weapon_frame', start)] + function(source, 'mcc_hud_glyphs_dispose') + '\n' + names = ['mcc_hud_button_bitmap'] if mcc else ['hud_hires_button_bitmap', 'hud_hires_button_draw'] routines = (ROOT/'port/linux/game/hud_button_layout.h').read_text() + '\n'.join(function(source, name) for name in names) tags = [a['tag'] for a in json.loads((ROOT/'port/assets/buttons/buttons.json').read_text())['assets'] - if a['name'] in ['a_butn__0','b_butn__0','x_butn__0','y_butn__0','black_butn__0','white_butn__0'] or 'classic' in a or 'source_png' in a] + if a['name'] in ['a_butn__0','b_butn__0','x_butn__0','y_butn__0','black_butn__0','white_butn__0', + 'mcc_black_butn__0','mcc_white_butn__0'] or 'classic' in a or 'source_png' in a] prelude = r''' #define ce_hud_buttons_stock(icon, index) 1 static int ce,stock_sheet=1; @@ -121,7 +126,12 @@ def test_legacy_button_styles_toggle_and_dispose(tmp_path): }; static int enabled=1,gems,live,last_asset=-1,draws; static short controller_glyph_style(void) {return (short)gems;} -#define controller_glyph_draw(style,index,icon,cursor,color) 0 +static boolean controller_glyph_draw(short style, short index, + struct icon_hud_element_definition const *icon, rectangle2d *cursor, pixel32 color) +{ + (void)style; (void)index; (void)icon; (void)cursor; (void)color; + return FALSE; +} #define controller_glyphs_dispose() ((void)0) static pixel32 drawn_color; static int drawn_blend; @@ -137,6 +147,7 @@ def test_legacy_button_styles_toggle_and_dispose(tmp_path): } static int rasterizer_bitmap_new(struct bitmap_data *b) {b->hardware_format=(unsigned long *)b;return 1;} static void bitmap_delete(struct bitmap_data *b) {free(b);live--;} +static void xgpu_mcc_texture_unbind(unsigned long const *t) {(void)t;} static void hud_hires_register_placeholder(long a,unsigned long const *t) {if(t)last_asset=(int)a;} static void rasterizer_psuedo_dynamic_screen_quad_draw(struct rasterizer_dynamic_screen_geometry_parameters *p, struct dynamic_screen_vertex *v) { @@ -147,7 +158,7 @@ def test_legacy_button_styles_toggle_and_dispose(tmp_path): prelude += 'static char const *tags[]={' + ','.join(json.dumps(t) for t in tags) + '};\n' prelude += 'static long hud_hires_asset_count(void) {return sizeof(tags)/sizeof(*tags);}\n' prelude += 'static char const *hud_hires_asset_tag(long i) {return tags[i];}\n' - call = r''' + call = 'assert(mcc_hud_button_bitmap((short)i));' if mcc else r''' buttons[i].flags=2;buttons[i].color=0xff123456; assert(hud_hires_button_draw(&buttons[i],&cursor,0x7fabcdef)); assert(drawn_color==0xffffffff); @@ -160,8 +171,9 @@ def test_legacy_button_styles_toggle_and_dispose(tmp_path): assert(hud_hires_button_draw(&buttons[i],&cursor,0)); assert(drawn_color==0x00ffffff); ''' - dispose = 'hud_buttons_forget' - check_off = (r''' + dispose = 'mcc_hud_glyphs_dispose' if mcc else 'hud_buttons_forget' + check_off = (r'''enabled=0;gems=0;assert(mcc_hud_button_bitmap(0)); + assert(!strstr(tags[last_asset],"classic"));''' if mcc else r''' enabled=0;assert(!hud_hires_button_draw(&buttons[0],&cursor,0xffffffff)); ce=1;assert(!hud_hires_button_draw(&buttons[0],&cursor,0xffffffff)); stock_sheet=0;assert(hud_hires_button_draw(&buttons[0],&cursor,0xffffffff)); @@ -202,7 +214,7 @@ def test_legacy_button_styles_toggle_and_dispose(tmp_path): OFF DISPOSE();DISPOSE();assert(live==0);return 0; } -'''.replace('CALL',call).replace('CONTROL', 'assert(hud_hires_button_draw(&buttons[control],&cursor,0x7fabcdef));assert(drawn_color==0x7fabcdef);assert(drawn_blend==7);').replace('OFF',check_off).replace('DISPOSE',dispose)) +'''.replace('CALL',call).replace('CONTROL', 'assert(mcc_hud_button_bitmap((short)slot));' if mcc else 'assert(hud_hires_button_draw(&buttons[control],&cursor,0x7fabcdef));assert(drawn_color==0x7fabcdef);assert(drawn_blend==7);').replace('OFF',check_off).replace('DISPOSE',dispose)) def test_visible_face_bounds_match_xbox_and_keep_black_white(tmp_path): diff --git a/tools/test_hud_corrections.py b/tools/test_hud_corrections.py index 853e66a34a..6feb56b52c 100644 --- a/tools/test_hud_corrections.py +++ b/tools/test_hud_corrections.py @@ -1,4 +1,4 @@ -"""Supplied reticle/zoom artwork fidelity and CE sprite selection.""" +"""Supplied artwork fidelity, classic cutouts, and CE sprite selection.""" import hashlib import json from pathlib import Path @@ -8,28 +8,12 @@ from harness import function from hud_assets import build_asset -import shutil -import subprocess -import sys -import pytest +from test_hud_button_style import run_c ROOT = Path(__file__).resolve().parents[1] ASSETS = ROOT / 'port/assets/hud' -def run_c(tmp_path, code): - compiler = shutil.which('clang') - if not compiler: - pytest.skip('clang required') - source = tmp_path / 'style.c' - binary = tmp_path / 'style.exe' - source.write_text(code) - target = ['--target=i686-pc-windows-msvc'] if sys.platform == 'win32' else ['-m32'] - result = subprocess.run([compiler, *target, '-std=gnu89', '-O1', str(source), '-o', str(binary)], - capture_output=True, text=True) - assert result.returncode == 0, result.stderr - subprocess.run([str(binary)], check=True, timeout=10) - def test_supplied_sources_are_unchanged(): manifest = json.loads((ASSETS / 'corrections/source-sha256.json').read_text()) @@ -38,7 +22,7 @@ def test_supplied_sources_are_unchanged(): def test_packed_corrections_use_supplied_pixels(): - for filename in ['layout.json', 'ce_layout.json']: + for filename in ['layout.json', 'ce_layout.json', 'mcc_layout.json']: for entry in json.loads((ASSETS / filename).read_text())['assets']: if not any('source_png' in cell for cell in entry['cells']): continue @@ -63,9 +47,11 @@ def test_packed_corrections_use_supplied_pixels(): def test_sniper_reticle_keeps_stock_visible_size_and_position(): # Measured stock alpha bounds (>=128), not the padded sprite rectangles. + # MCC's original sheet has four times Xbox/CE's texture resolution. for name, scale, sprite, bounds in [ ('sniper__hud_reticles_scope__0', 8, [32, 0, 50, 18], [36, 4, 45, 13]), ('ce_sniper_scope', 8, [51, 0, 63, 12], [52, 1, 61, 10]), + ('mcc_sniper_scope', 2, [108, 0, 152, 44], [112, 4, 148, 40]), ]: alpha = Image.open(ASSETS / (name+'.png')).getchannel('A') x0,y0,x1,y1 = [n*scale for n in sprite] diff --git a/tools/test_hud_shield_tick.py b/tools/test_hud_shield_tick.py new file mode 100644 index 0000000000..a1c87d6669 --- /dev/null +++ b/tools/test_hud_shield_tick.py @@ -0,0 +1,58 @@ +"""Shield decay on an unowned object has no player HUD to update.""" +import os +from pathlib import Path +import shutil +import subprocess + +import pytest +from harness import function + +ROOT = Path(__file__).resolve().parents[1] + + +def test_shield_tick_player_ownership(tmp_path): + compiler = shutil.which("clang") + if compiler is None: + pytest.skip("clang is required") + source = (ROOT / "source/interface/hud_unit.c").read_text() + (tmp_path / "under_test.inc").write_text(function(source, "hud_tick_shield")) + (tmp_path / "shield.c").write_text(r''' +#include +#define NONE (-1) +typedef float real; +static struct player { short local_player_index; } players[2]={{0},{NONE}}; +static struct hud { real last_shield_vitality; } hud={2.0f}; +static int player_lookups, hud_lookups; +static struct player *player_get(long index) +{ + assert(index>=0 && index<2); + player_lookups++; + return &players[index]; +} +static struct hud *get_hud_state(short index) +{ + assert(index==0); + hud_lookups++; + return &hud; +} +#include "under_test.inc" +int main(void) +{ + hud_tick_shield(NONE,0.25f); + assert(!player_lookups && !hud_lookups && hud.last_shield_vitality==2.0f); + hud_tick_shield(0,0.25f); + assert(player_lookups==1 && hud_lookups==1 && hud.last_shield_vitality==1.75f); + hud_tick_shield(1,0.25f); + assert(player_lookups==2 && hud_lookups==1 && hud.last_shield_vitality==1.75f); + hud_tick_shield(NONE,0.25f); + assert(player_lookups==2 && hud_lookups==1 && hud.last_shield_vitality==1.75f); + return 0; +} +''') + binary = tmp_path / ("shield.exe" if os.name == "nt" else "shield") + command = [compiler, "-m32", "-std=gnu89", "-O1", "-Wall", "-Werror", + str(tmp_path / "shield.c"), "-o", str(binary)] + if os.name == "nt": + command.append("-fuse-ld=lld") + subprocess.run(command, check=True, capture_output=True, text=True) + subprocess.run([str(binary)], check=True, capture_output=True, timeout=10) diff --git a/tools/test_hud_timer.py b/tools/test_hud_timer.py new file mode 100644 index 0000000000..3f9fa6ff38 --- /dev/null +++ b/tools/test_hud_timer.py @@ -0,0 +1,125 @@ +"""Exercise the scripted timer's real renderer with poisoned automatic storage.""" +from pathlib import Path +import shutil +import subprocess + +import pytest +from harness import function, structure + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.fixture(scope="module") +def timer_tools(tmp_path_factory): + clang = shutil.which("clang") + if not clang: + pytest.skip("clang is needed for the timer renderer test") + work = tmp_path_factory.mktemp("hud-timer") + native = (ROOT / "source/interface/hud_messaging.c").read_text() + definitions = (ROOT / "source/interface/hud_definitions.h").read_text() + types = "\n".join(structure(definitions, name) for name in [ + "hud_absolute_placement_definition", "hud_placement_definition", "hud_color_definition"]) + types += "\n" + "\n".join(structure(native, name) for name in [ + "hud_timer_data_definition", "number_hud_element_definition", "hud_number_definition"]) + prefix = r''' +#include +#include +#include +typedef float real; +typedef unsigned char boolean, byte; +typedef unsigned short word; +typedef struct { short x,y; } point2d; +typedef struct { real i,j; } real_vector2d; +struct tag_reference { long group; char *name; long length,index; }; +#define NONE (-1) +#define TRUE 1 +#define FALSE 0 +#define FLAG(x) (1u<<(x)) +#define MAX(a,b) ((a)>(b)?(a):(b)) +#define TICKS_PER_SECOND 30 +#define SECONDS_PER_MINUTE 60 +#define _interface_hud_digits 0 +#define _hud_number_show_all_leading_zeros_bit 0 +enum { _hud_corner_top_left, _hud_corner_top_right, _hud_corner_bottom_left, + _hud_corner_bottom_right, _hud_corner_center }; +#define match_assert(file,line,cond) assert(cond) +''' + stubs = r''' +static struct { struct hud_timer_data_definition timer; } messaging; +#define hud_messaging_globals (&messaging) +static struct { struct { struct hud_color_definition color,time_up_color; } timer_definition; } globals; +#define hud_globals (&globals) +static struct hud_number_definition digits; +#define HUD_NUMBER_DEFINITION_GET(index) (&digits) +static struct {short local_player_index;} render; +static long time_code_time=NONE,time_code_stop_time=NONE; +static char temporary[64]; +static short remaining; +static int calls,missing; +static long game_time_get(void) { return 100; } +static short scripted_hud_get_timer_ticks(void) { return remaining; } +static long interface_get_tag_index(int kind) { return missing?NONE:0; } +static void render_debug_string(int active,char *text) { } +static void hud_draw_numbers(short player, struct hud_absolute_placement_definition const *absolute, + struct number_hud_element_definition const *number, short value, short decimal, + short flags, long reference, real scale) { + int step=missing?0:24; + int first=40; + int values[3]={4,35,43}; + if(absolute->corner==1 || absolute->corner==3) { first+=5*step;step=-step; } + if(absolute->corner==4) first-=3*step; + assert(number->placement.multiplayer_scaling_flags==0); + assert(number->placement.scale.i==1 && number->placement.scale.j==1); + assert(number->placement.offset.x==first+calls*step*5/2); + assert(number->placement.offset.y==20); + assert(number->digits==2 && number->number_flags==1); + assert(decimal==NONE && scale==2); + assert(value==(remaining>0?values[calls]:0)); + assert(number->colors.color==(remaining>0?0x1234u:0x5678u)); + assert(flags==(remaining<=0)); + calls++; +} +''' + main = r''' +int main(int argc,char **argv) { + messaging.timer.corner=(short)atoi(argv[1]); + remaining=(short)(atoi(argv[2])?0:((4*60+35)*30+13)); + missing=atoi(argv[3]); + messaging.timer.enabled=(boolean)atoi(argv[4]); + messaging.timer.position.x=40;messaging.timer.position.y=20; + messaging.timer.ticks=remaining;messaging.timer.reference_time=100; + globals.timer_definition.color.color=0x1234; + globals.timer_definition.time_up_color.color=0x5678; + digits.screen_width=12; + hud_render_timer(); + assert(calls==(messaging.timer.enabled?3:0)); + return 0; +} +''' + code = function(native, "hud_render_timer") + executables = [] + for name, body in [("fixed", code), ("uninitialized", code.replace( + "numbers.placement.multiplayer_scaling_flags = 0;", ""))]: + source = work / (name + ".c") + source.write_text(prefix + types + stubs + body + main) + exe = work / (name + ".exe") + subprocess.run([clang, "-m32", "-std=gnu89", "-O1", + "-ftrivial-auto-var-init=pattern", str(source), "-o", str(exe)], check=True) + executables.append(exe) + return executables + + +@pytest.mark.parametrize("corner", range(5)) +@pytest.mark.parametrize("expired", [0, 1]) +def test_timer_placement_and_scaling(timer_tools, corner, expired): + subprocess.run([str(timer_tools[0]), str(corner), str(expired), "0", "1"], check=True) + + +@pytest.mark.parametrize("missing,enabled", [(1, 1), (0, 0)]) +def test_missing_digits_or_hidden_timer(timer_tools, missing, enabled): + subprocess.run([str(timer_tools[0]), "3", "0", str(missing), str(enabled)], check=True) + + +def test_uninitialized_flags_are_detected(timer_tools): + result = subprocess.run([str(timer_tools[1]), "3", "0", "0", "1"], capture_output=True) + assert result.returncode != 0 diff --git a/tools/test_hud_upscale.py b/tools/test_hud_upscale.py new file mode 100644 index 0000000000..a745a3d716 --- /dev/null +++ b/tools/test_hud_upscale.py @@ -0,0 +1,72 @@ +"""Exercise the production HUD interpolator without maps or a graphics driver.""" +from pathlib import Path +import shutil +import subprocess +import sys + +import pytest + +ROOT = Path(__file__).resolve().parents[1] + + +def test_original_pixels_keep_channels_centres_and_bounds(tmp_path): + compiler = shutil.which("clang") + if not compiler: + pytest.skip("clang required") + source = (ROOT / "port/linux/src/hud_hires.c").read_text() + code = source[source.index("static void upscale_weights"): + source.index("static unsigned char *png_decode")] + harness = r''' +#include +#include +#include +PRODUCTION +int main(void) +{ + unsigned char pixel[4] = {37, 91, 173, 255}, input[7*7*4] = {0}; + unsigned char *output; + unsigned long x, y, c; + double mass = 0, centre_x = 0, centre_y = 0; + assert(!hud_hires_upscale_pixels(NULL, 1, 1)); + assert(!hud_hires_upscale_pixels(pixel, 0, 1)); + assert(!hud_hires_upscale_pixels(pixel, 1, 0)); + assert(!hud_hires_upscale_pixels(pixel, 257, 1)); + assert(!hud_hires_upscale_pixels(pixel, 1, 257)); + output = hud_hires_upscale_pixels(pixel, 1, 1); + assert(output); + for (x = 0; x < 16; x++) { + assert(output[x*4] == 173 && output[x*4+1] == 91); + assert(output[x*4+2] == 37 && output[x*4+3] == 255); + } + free(output); + /* A sprite's centre must stay at the same normalized texture position. */ + memset(input + (3*7+3)*4, 255, 4); + output = hud_hires_upscale_pixels(input, 7, 7); + assert(output); + for (y = 0; y < 28; y++) for (x = 0; x < 28; x++) { + unsigned char alpha = output[(y*28+x)*4+3]; + mass += alpha; + centre_x += (x+.5)*alpha; + centre_y += (y+.5)*alpha; + for (c = 0; c < 4; c++) { + assert(output[(y*28+x)*4+c] == output[(x*28+y)*4+c]); + assert(output[(y*28+x)*4+c] == output[(y*28+27-x)*4+c]); + } + } + assert(mass > 0 && centre_x/mass == 14 && centre_y/mass == 14); + free(output); + memset(input, 0, sizeof(input)); + output = hud_hires_upscale_pixels(input, 7, 7); + assert(output); + for (x = 0; x < 28*28*4; x++) assert(!output[x]); + free(output); + return 0; +} +''' + unit = tmp_path / "hud_upscale.c" + unit.write_text(harness.replace("PRODUCTION", code)) + executable = tmp_path / "hud_upscale.exe" + target = ["--target=i686-pc-windows-msvc"] if sys.platform == "win32" else [] + subprocess.run([compiler, *target, "-std=gnu89", "-O2", str(unit), "-o", str(executable)], + check=True, capture_output=True, text=True) + subprocess.run([str(executable)], check=True, timeout=10) diff --git a/tools/test_join_protocol.py b/tools/test_join_protocol.py new file mode 100644 index 0000000000..dd58531dd3 --- /dev/null +++ b/tools/test_join_protocol.py @@ -0,0 +1,104 @@ +"""The actual join packet table and codec reject pre-agreement/truncated joins.""" +from pathlib import Path +import re + +from harness import constant, enum_with, function, structure +from test_hud_button_style import run_c + +ROOT = Path(__file__).resolve().parents[1] + + +def test_join_codec_requires_complete_shared_agreement(tmp_path): + client = (ROOT / "source/networking/network_client_manager.c").read_text() + server = (ROOT / "source/networking/network_server_message_handler.c").read_text() + messages = (ROOT / "source/networking/network_messages.c").read_text() + packets = (ROOT / "source/memory/data_packets.c").read_text() + encoding = (ROOT / "source/memory/data_encoding.c").read_text() + swapping = (ROOT / "source/memory/byte_swapping.c").read_text() + swap_header = (ROOT / "source/memory/byte_swapping.h").read_text() + groups = (ROOT / "source/memory/data_packet_groups.h").read_text() + client_join = structure(client, "message_client_join_game_request") + server_join = structure(server, "message_client_join_game_request") + normalize = lambda s: re.sub(r"\s+", " ", re.sub(r"/\*.*?\*/", "", s, flags=re.S)).strip() + assert constant(server, "JOIN_GAME_TOKEN_LENGTH") == 16 + assert normalize(client_join.replace("join_token", "join_game_token")) == normalize( + server_join.replace("JOIN_GAME_TOKEN_LENGTH", "0x10")) + assert constant(client, "MAXIMUM_MACHINE_NAME_LENGTH") == constant(server, "MAXIMUM_MACHINE_NAME_LENGTH") + fields = next(fields for fields, name in re.findall( + r"\t\{\n((?:\t\t.*\n)*?)\t\},\n\tNETWORK_GAME_MESSAGE_DEFINITION\((\w+),", messages) + if name == "client_join_game_request") + field_count = re.search(r"client_join_game_request_fields\[(\d+)\]", messages).group(1) + macros = re.search(r"#define DATA_PACKET_FIELD\(.*?\n\n", messages, re.S).group(0) + swap_macros = "\n".join(line for line in swap_header.splitlines() if line.startswith("#define SWAP")) + swap_macros += "\n" + re.search(r"#define SWAP8\(.*?\n\n", swapping, re.S).group(0).replace("ui64", "ULL") + code = r''' +#include +#include +#include +#include +#include +typedef unsigned char byte; +typedef unsigned short word; +typedef int boolean; +typedef long byte_swap_code; +#define __int64 long long +#define TRUE 1 +#define FALSE 0 +#define NONE -1 +#define UNSIGNED_CHAR_MAX UCHAR_MAX +#define UNSIGNED_SHORT_MAX USHRT_MAX +#define csmemcpy memcpy +#define csmemset memset +#define csstrcpy strcpy +#define csstrncpy strncpy +#define match_assert(file,line,condition) assert(condition) +#define display_assert(...) assert(0) +#define system_exit exit +#define csprintf(buffer,...) (snprintf(buffer,sizeof(temporary),__VA_ARGS__),buffer) +static char temporary[256]; +''' + enum_with(swap_header, "_1byte") + "\n" + swap_macros + "\n" + code += function(swapping, "byte_swap_memory") + "\n" + code += structure((ROOT / "source/memory/data_encoding.h").read_text(), "data_encoding_state") + "\n" + code += enum_with(groups, "_data_packet_field_pad") + "\n" + code += structure(groups, "data_packet_field") + "\n" + structure(groups, "data_packet_definition") + "\n" + for name in ("data_encode_new", "data_encode_memory", "data_encode_integer", "data_encode_string", + "data_decode_new", "data_decode_memory", "data_decode_byte", "data_decode_short", + "data_decode_long", "data_decode_integer", "data_decode_string"): + code += function(encoding, name) + "\n" + for name in ("_data_packet_verify", "data_packet_verify", "_data_packet_encode", "data_packet_encode", + "_data_packet_decode", "data_packet_decode"): + code += function(packets, name) + "\n" + # The game uses two-byte wchar_t on every platform. Keep the real structs + # and field list, with only that type spelling adapted for the host harness. + code += "#define wchar_t unsigned short\n#define MAXIMUM_MACHINE_NAME_LENGTH " + str(constant(client, "MAXIMUM_MACHINE_NAME_LENGTH")) + "\n" + code += client_join + "\n#undef wchar_t\n" + code += "typedef struct message_client_join_game_request message_client_join_game_request;\n" + macros + code += "static struct {struct data_packet_field client_join_game_request_fields[" + field_count + "];} data_0030aa68 = {{\n" + fields + "}};\n" + code += 'static struct data_packet_definition definition = NETWORK_GAME_MESSAGE_DEFINITION(client_join_game_request,"join",message_client_join_game_request);\n' + code += r''' +int main(void) { + struct message_client_join_game_request input; + struct {byte before[16];struct message_client_join_game_request value;byte after[16];} output; + byte wire[512],copy[512];short size,version;int i,j; + assert(sizeof(long)==4 && sizeof(input)==348); + memset(&input,0x39,sizeof(input));input.network_version=32738; + assert(data_packet_encode(&definition,1,&input,wire,&size,sizeof(wire))); + assert(size==349); + memcpy(copy,wire,size);memset(&output,0,sizeof(output)); + assert(data_packet_decode(&definition,copy,size,&output.value,&version,NULL)); + assert(version==1 && !memcmp(&input,&output.value,sizeof(input))); + /* The previous join has 346 bytes plus the codec version. Every missing + * suffix, including either agreement byte, must fail the actual decoder. */ + for(i=0;i #include -static int automatic=1, enabled; +static int automatic=1,hud=1; static char const *manual="classic"; -int config_boolean(char const *n){if(!strcmp(n,"display.keyboard_glyphs"))return enabled;assert(!strcmp(n,"input.auto_button_detection"));return automatic;} +int config_boolean(char const *n){if(!strcmp(n,"display.high_res_hud"))return hud;assert(!strcmp(n,"input.auto_button_detection"));return automatic;} char const *config_string(char const *n){(void)n;return manual;} ''' + code('port/linux/src/keyboard_prompts.c') + r''' int main(void){ unsigned char keys[512]={0}; - assert(!keyboard_prompt_enabled(0));enabled=1; #ifdef HALO_ANDROID assert(!keyboard_prompt_enabled(0)); #else @@ -46,18 +45,21 @@ def test_manual_auto_activity_disconnect_and_split_screen(tmp_path, android): keyboard_prompt_pad(0,0,1,1);assert(keyboard_prompt_enabled(0)); /* no stick jitter */ keyboard_prompt_pad(0,0,0,1);keyboard_prompt_pad(0,0,1,1);assert(!keyboard_prompt_enabled(0)); keyboard_prompt_pad(0,0,0,0);assert(keyboard_prompt_enabled(0)); + assert(keyboard_prompt_menu_enabled(-1)&&!keyboard_prompt_menu_enabled(0)&&!keyboard_prompt_menu_enabled(-2)); keyboard_prompt_touch();assert(!keyboard_prompt_enabled(0)); keyboard_prompt_pad(0,0,0,0);assert(!keyboard_prompt_enabled(0)); keyboard_prompt_pad(0,1,0,1);keyboard_prompt_pad(0,0,0,0);assert(!keyboard_prompt_enabled(0)); keyboard_prompt_keys(keys,512,0x100);assert(keyboard_prompt_enabled(0)); - enabled=0;assert(!keyboard_prompt_enabled(0)); automatic=0;assert(!keyboard_prompt_enabled(0));manual="keyboard"; assert(keyboard_prompt_enabled(0)&&keyboard_prompt_enabled(3)); + assert(keyboard_prompt_menu_enabled(0)&&keyboard_prompt_menu_enabled(-1)); keyboard_prompt_pad(0,1,1,1);assert(keyboard_prompt_enabled(0)); - automatic=1;assert(!keyboard_prompt_enabled(0));enabled=1;assert(!keyboard_prompt_enabled(0)); - keys[5]=1;keyboard_prompt_keys(keys,512,0);assert(keyboard_prompt_enabled(0));automatic=0; assert(!keyboard_prompt_enabled(-1)&&!keyboard_prompt_enabled(4)); - manual="ps_modern";assert(!keyboard_prompt_enabled(0));return 0; + hud=0;assert(!keyboard_prompt_enabled(0)&&!keyboard_prompt_menu_enabled(-1)); + automatic=1;keyboard_prompt_keys(keys,512,0x100); + assert(keyboard_prompt_active(0)&&!keyboard_prompt_enabled(0)&&!keyboard_prompt_menu_enabled(-1)); + hud=1;assert(keyboard_prompt_enabled(0)&&keyboard_prompt_menu_enabled(-1)); + automatic=0;manual="ps_modern";assert(!keyboard_prompt_enabled(0));return 0; } ''') @@ -162,8 +164,8 @@ def test_supersampled_shapes_cache_failure_and_cleanup(tmp_path): #define MAX(a,b) ((a)>(b)?(a):(b)) #define KEYBOARD_ART_SIZE 128 #define KEYBOARD_ART_COUNT 13 -typedef float real;typedef unsigned int pixel32; -struct bitmap_data {unsigned int *pixels,*hardware_format;}; +typedef float real;typedef unsigned long pixel32; +struct bitmap_data {unsigned long *pixels,*hardware_format;}; static struct bitmap_data *keyboard_art[13];static int keyboard_art_attempted[13]; static int allocations,releases,fail; static struct bitmap_data *bitmap_2d_new(short w,short h,int m,int f){ @@ -190,8 +192,9 @@ def test_optional_hook_precedes_controller_translation_and_preserves_custom_path start = text.index('case _hud_message_type_icon:') hook = text.index('keyboard_hud_prompt(', start) assert hook < text.index('icon_index = preferences.game_control_to_xbox_buttons', start) + assert 'mcc_cache_tags_loaded()' in text config = (ROOT/'port/linux/src/port_config.c').read_text(encoding='utf-8') - assert '"display.keyboard_glyphs", _config_boolean, "false"' in config + assert '"display.keyboard_glyphs"' not in config def test_score_hint_only_rewrites_known_token_with_room(tmp_path): diff --git a/tools/test_king_network_state.py b/tools/test_king_network_state.py new file mode 100644 index 0000000000..e102bdaa82 --- /dev/null +++ b/tools/test_king_network_state.py @@ -0,0 +1,77 @@ +"""Exercise upstream hill framing and stock/multi-hill transitions on real functions.""" +import subprocess +from pathlib import Path + +from harness import function, structure +from test_mcc_identity import compile_tool + +ROOT = Path(__file__).resolve().parents[1] + + +def test_hill_state_framing_and_transitions(tmp_path): + source = (ROOT / "source/game/game_engine_king.c").read_text() + code = r''' +#include +#include +typedef int boolean; +typedef unsigned char byte; +#define TRUE 1 +#define FALSE 0 +#define NONE -1 +#define MAXIMUM_HILLS_AT_ONCE 5 +#define VALID_INDEX(i,n) ((i)>=0 && (i)<(n)) +#define NUMBEROF(a) (sizeof(a)/sizeof((a)[0])) +#define csmemcpy memcpy +#define csmemset memset +enum { king_hill_uncontrolled, _multiplayer_sound_hill_move }; +struct king_globals { long score[2], score_tick[2], hill_timer, hill_id; }; +struct king_hill { long hill_id, hill_previous_controller, hill_state; }; +static struct king_globals king_globals; +static struct king_hill king_hills[MAXIMUM_HILLS_AT_ONCE]; +static short king_hill_count; +static int sounds, finds, score_sounds; +static void find_hill(struct king_hill *hill) { (void)hill; finds++; } +static void king_hills_to_globals(void) { king_globals.hill_id=king_hills[0].hill_id; } +static void game_engine_play_multiplayer_sound(int sound) { (void)sound; sounds++; } +static void king_client_score_sounds(long team,long before,long after) +{ (void)team; (void)before; (void)after; score_sounds++; } +''' + structure(source, "king_extra_hills_network_state") + "\n" + "\n".join( + function(source, name) for name in ( + "game_engine_king_write_network_state", "game_engine_king_read_network_state")) + r''' +int main(void) { + byte data[1024]; long stock=sizeof(king_globals), full; + struct king_extra_hills_network_state extra; + memset(data,0xA5,sizeof(data)); + king_hill_count=1; king_globals.hill_id=4; king_globals.score[0]=7; + assert(game_engine_king_write_network_state(data,stock-1)==0); + assert(game_engine_king_write_network_state(data,sizeof(data))==stock); + assert(data[stock]==0xA5); + assert(!game_engine_king_read_network_state(data,stock-1,TRUE)); + assert(game_engine_king_read_network_state(data,stock,TRUE)); + assert(king_hill_count==1 && king_hills[0].hill_id==4 && finds==1); + assert(sounds==0 && score_sounds==0); + king_hill_count=3; king_hills[1].hill_id=5; king_hills[2].hill_id=9; + full=game_engine_king_write_network_state(data,sizeof(data)); + assert(full==stock+(long)sizeof(extra)); + assert(game_engine_king_write_network_state(data,stock)==stock); + king_hill_count=1; + assert(game_engine_king_read_network_state(data,full,FALSE)); + assert(king_hill_count==3 && king_hills[1].hill_id==5 && king_hills[2].hill_id==9); + assert(sounds==1 && finds==3 && score_sounds==2); + assert(!game_engine_king_read_network_state(data,full-1,FALSE)); + memcpy(&extra,data+stock,sizeof(extra)); extra.hill_count=5; + memcpy(data+stock,&extra,sizeof(extra)); + assert(!game_engine_king_read_network_state(data,full,FALSE)); + assert(king_hill_count==3 && sounds==1); + extra.hill_count=-1; memcpy(data+stock,&extra,sizeof(extra)); + assert(!game_engine_king_read_network_state(data,full,FALSE)); + assert(game_engine_king_read_network_state(data,stock,FALSE)); + assert(king_hill_count==1 && sounds==2); + return 0; +} +''' + path = tmp_path / "test.c" + path.write_text(code) + binary = compile_tool(tmp_path, [path]) + result = subprocess.run([str(binary)], capture_output=True, text=True, timeout=15) + assert result.returncode == 0, result.stdout + result.stderr diff --git a/tools/test_lighting_compatibility.py b/tools/test_lighting_compatibility.py new file mode 100644 index 0000000000..513f3364b0 --- /dev/null +++ b/tools/test_lighting_compatibility.py @@ -0,0 +1,30 @@ +"""Do not confuse HSC player ordering or requested events with observed coverage.""" +from copy import deepcopy +import pytest +from lighting_compatibility_run import report_passed + + +def report(player): + peer=dict(exit=0,forced_stop=False,two_player_samples=30,respawns={str(player):2}, + inventories={'0':[['ar'],['ar','plasma']]},policy_samples=20, + correct_policy_samples=20,config_verified=True,failures=[], + one_player_samples=20,first_two_player_tick=700) + return dict(case='xbox',peers={'host':peer,'client':deepcopy(peer)}, + agreement=dict(problems=[],divergences=[],figures={'seconds':25})) + + +@pytest.mark.parametrize('player',[0,1]) +def test_either_network_player_can_be_the_hsc_target(player): + assert report_passed(report(player)) + + +@pytest.mark.parametrize('fault',['no_respawn','different_player','policy','divergence','not_late','no_pairs']) +def test_missing_coverage_is_not_a_pass(fault): + r=report(0) + if fault=='no_respawn':r['peers']['client']['respawns']={'0':0} + if fault=='different_player':r['peers']['client']['respawns']={'1':2} + if fault=='policy':r['peers']['client']['correct_policy_samples']=19 + if fault=='divergence':r['agreement']['divergences']=['weapon mismatch'] + if fault=='not_late':r['case']='late';r['peers']['host']['one_player_samples']=0 + if fault=='no_pairs':r['agreement']['figures']['seconds']=0 + assert not report_passed(r) diff --git a/tools/test_lighting_performance.py b/tools/test_lighting_performance.py new file mode 100644 index 0000000000..a14efaffef --- /dev/null +++ b/tools/test_lighting_performance.py @@ -0,0 +1,86 @@ +"""Check that benchmark reports retain real stalls and separate capture overhead.""" +import pytest +from lighting_performance_run import distribution, summarize, memory_window_mib +from lighting_performance_build import ROOT, instrument_shader_stalls, instrument_renderer_profile +from harness import function + + +@pytest.mark.parametrize('name', ['prepare_draw', 'buffer_upload']) +def test_renderer_timers_preserve_the_production_body(name): + source = (ROOT/'port/linux/src/d3d8_gl.c').read_text() + timed = instrument_renderer_profile(source) + assert function(timed, 'lighting_timed_'+name).replace('lighting_timed_'+name+'(', name+'(', 1) == function(source, name) + wrapper = function(timed, name) + assert wrapper.count('lighting_profile_begin(') == wrapper.count('lighting_profile_end(') == 1 + assert wrapper.index('lighting_profile_begin(') < wrapper.index('lighting_timed_'+name+'(') < wrapper.index('lighting_profile_end(') + + +@pytest.mark.parametrize('name,kind', [('xgpu_compile_shader', 0), + ('xgpu_link_program', 1), ('program_get', 1)]) +def test_shader_stall_clocks_cover_real_compile_and_link_paths(name, kind): + source = (ROOT/'port/linux/src/d3d8_gl.c').read_text() + body = function(instrument_shader_stalls(source), name) + begin = body.index(f'lighting_stall_shader_begin({kind});') + operation = body.index('glCompileShader(' if kind == 0 else 'glLinkProgram(') + status = body.index('GL_COMPILE_STATUS' if kind == 0 else 'GL_LINK_STATUS') + end = body.index(f'lighting_stall_shader_end({kind});') + assert begin < operation < status < end + assert body.count('lighting_stall_shader_begin(') == 1 + assert body.count('lighting_stall_shader_end(') == 1 + + +def test_binary_cache_status_does_not_end_a_link_timer(): + source = (ROOT/'port/linux/src/d3d8_gl.c').read_text() + body = function(instrument_shader_stalls(source), 'program_cache_load') + assert 'lighting_stall_shader_' not in body + + +def test_percentiles_and_slow_frame_budget(): + result=distribution([10]*98+[50,100],100) + assert result['p99_ms']==50 + assert result['low_1pct_fps']==10 + assert result['over_1_5_budget_percent']==2 + assert result['over_50ms']==1 + + +def test_warmup_capture_and_minute_boundaries(): + rows=[dict(seconds=t,frame_ms=10,selected=2,scene_lights=4, + occlusion_updates=1,capture_excluded=0,tick=t*30) for t in range(160)] + rows[35].update(frame_ms=1000,capture_excluded=1) + rows[95]['frame_ms']=200 # Real hitch must remain in both overall and per-minute data. + result=summarize(rows,30,120,100) + assert result['raw']['frames']==120 and result['pacing']['frames']==119 + assert result['raw']['worst_ms']==1000 and result['pacing']['worst_ms']==200 + assert result['minutes'][0]['worst_ms']==10 + assert result['minutes'][1]['worst_ms']==200 + assert result['measured_span']==119 + assert result['selected_max']==2 + + +def test_missing_frame_samples_are_not_a_pass(): + with pytest.raises(ValueError,match='No frame samples'): + distribution([],60) + + +def test_disabled_capture_keeps_stalls_even_with_old_fixture_markers(): + rows=[dict(seconds=t,frame_ms=10,selected=2,scene_lights=4, + occlusion_updates=1,capture_excluded=0,tick=t*30) for t in range(60)] + rows[35].update(frame_ms=200,capture_excluded=1) + result=summarize(rows,30,30,120,captures=False) + assert result['pacing']==result['raw'] + assert result['pacing']['worst_ms']==200 + assert result['excluded_capture_frames']==0 + assert result['minutes'][0]['worst_ms']==200 + + +def test_early_exit_keeps_missing_memory_windows_distinct_from_zero(): + samples=[dict(seconds=45,private=100*2**20),dict(seconds=50,private=120*2**20)] + assert memory_window_mib(samples,45,75)==110 + assert memory_window_mib(samples,585) is None + + +def test_240_fps_budget_counts_sub_120_stalls(): + result = distribution([4.0, 4.16, 4.18, 8.0], 240) + assert result['budget_ms'] == pytest.approx(1000 / 240) + assert result['over_budget_percent'] == 50 + assert result['over_1_5_budget_percent'] == 25 diff --git a/tools/test_linux_port.py b/tools/test_linux_port.py index e2c60fe530..ad63de05e7 100644 --- a/tools/test_linux_port.py +++ b/tools/test_linux_port.py @@ -150,6 +150,19 @@ def test_render_skips_tags_used_as_both_struct_and_union(): XDK_INCLUDE = Path(__file__).resolve().parent.parent / "port" / "include" / "xdk" +@pytest.mark.skipif(shutil.which("clang") is None, reason="clang is needed to compile the headers") +def test_source_fixups_header_is_self_contained(tmp_path): + root = XDK_INCLUDE.parent.parent.parent + source = write(tmp_path / "fixups.c", '#include "halo_linux_source_fixups.h"\n') + # This declarations-only header must not require the game's include path + # or host libc, so the Linux target can be checked on Windows too. + subprocess.run( + ["clang", "--target=i686-linux-gnu", "-std=gnu89", "-Werror", "-fsyntax-only", + "-I", str(root / "port/linux/include"), str(source)], + check=True, + ) + + def test_xdk_headers_use_the_sdk_spellings(): # each port gives the SDK's keywords and names its own meaning (its # prefix header), so none of one port's must be written into them @@ -336,7 +349,12 @@ def test_menus_are_well_formed(): header = png.read(24) width, height = int.from_bytes(header[16:20], "big"), int.from_bytes(header[20:24], "big") logical = int(frame.get("width")), int(frame.get("height")) - assert width % logical[0] == 0 and width // logical[0] == height // logical[1], where + if element.get("name", "").startswith("frontend_legacy/glyph_"): + # Controller artwork is presented in its authored 21x26 + # legacy glyph cell, independently of the texture size. + assert logical == (21, 26) and width == height == 256, where + else: + assert width % logical[0] == 0 and width // logical[0] == height // logical[1], where elif element.tag == "strings": strings[element.get("name")] = element # (a string's map= is its number in the list's map list, menu_tags.c) @@ -378,7 +396,8 @@ def test_menus_are_well_formed(): def test_menu_settings_exist(): """Every setting a menu's spinner sets is one of config.toml's - (port/linux/src/port_config.c), of the profile or an action of a row's + (port/linux/src/port_config.c), a group of those settings, of the profile + or an action of a row's (menu_functions.c), and the keyboard's controls are the same in the settings, in the controls' screen and in the input code.""" @@ -389,9 +408,17 @@ def test_menu_settings_exist(): profile = set(re.findall(r'\{ "(profile\.[a-z_]+)", \d', functions)) # (and the actions a row does on OK rather than a setting: DISCORD ACCOUNT's LINK, setting_write's) actions = set(re.findall(r'!strcmp\(name, "([a-z_]+\.action)"\)', functions)) + # Grouped lighting rows are implemented by a separate menu module. Check + # their actual member keys too, rather than accepting a whole namespace. + lighting = (root / "port/linux/game/lighting_menu.c").read_text() + groups = dict(re.findall(r'\{\s*"(lighting\.[a-z_]+)",\s*\{([^}]+)\}\}', lighting)) + assert groups + for name, body in groups.items(): + members = set(re.findall(r'"([a-z_]+\.[a-z_]+)"', body)) + assert members and members <= known, f"{name}: {members - known}" for path in (MENUS / "ce").glob("*.xml"): for setting in re.findall(r'setting="([^"]+)"', path.read_text()): - assert setting in known | profile | actions, f"{path.name}: {setting}" + assert setting in known | profile | actions | groups.keys(), f"{path.name}: {setting}" controls = set(re.findall(r'"(controls\.[a-z_]+)"', (root / "port/linux/src/xinput_sdl.c").read_text())) assert controls == {name for name in known if name.startswith("controls.")} assert controls == set(re.findall(r'\{ "(controls\.[a-z_]+)", L"', functions)) @@ -604,7 +631,7 @@ def test_config_has_each_section_once(tmp_path): (stubs / "SDL3" / "SDL.h").write_text("") (stubs / "platform.h").write_text("void platform_log(const char *format, ...);\n") # (beside the stubs, which it then includes instead of the platform layer's) - for name in ("port_config.c", "port_config.h"): + for name in ("port_config.c", "port_config.h", "lighting_settings_migration.inl"): shutil.copy(root / "port/linux/src" / name, stubs / name) (tmp_path / "main.c").write_text(CONFIG_PROGRAM) program = tmp_path / "config_program" @@ -627,10 +654,10 @@ def sections(): return re.findall(r"^\[(\w+)\]$", config.read_text(), re.M) # the defaults - assert run("get", "display.first_person_legs")[0] == "false" + assert run("get", "display.match_timer")[0] == "false" assert len(sections()) == len(set(sections())), sections() - run("write", "display.first_person_legs", "true") - assert run("get", "display.first_person_legs")[0] == "true" + run("write", "display.match_timer", "true") + assert run("get", "display.match_timer")[0] == "true" # MCC discovery starts enabled; an explicit later opt-out stays saved. for key in ("game.workshop_maps", "game.mcc_campaigns", "game.mcc_collections"): @@ -640,13 +667,26 @@ def sections(): # an older version's config.write_text("[display]\nvsync = false\n\n[game]\nconsole_log = \"all\"\n\n" - "[display]\nfirst_person_legs = true\n") - value, log = run("get", "display.first_person_legs") + "[display]\nmatch_timer = true\n") + value, log = run("get", "display.match_timer") assert value == "true" and "joined" in log assert sections().count("display") == 1 assert run("get", "display.vsync")[0] == "false" assert run("get", "game.console_log")[0] == "all" + # Legacy lighting resets before any menu or game reads it; the marker is + # written with the reset and later explicit choices survive fresh loads. + config.write_text('[display]\nvsync = false\nweapon_glow = true\n' + 'shield_glow = true\nshield_glow_intensity = "light_show"\n') + assert run("get", "display.weapon_glow")[0] == "false" + assert run("get", "display.shield_glow")[0] == "false" + assert run("get", "display.shield_glow_intensity")[0] == "default" + assert run("get", "display.dynamic_lighting_reset")[0] == "true" + assert 'weapon_glow = false' in config.read_text() + assert run("get", "display.vsync")[0] == "false" + run("write", "display.weapon_glow", "true") + assert run("get", "display.weapon_glow")[0] == "true" + # ---------- system link's stand-in machines (tools/system_link_bots.py) @@ -693,6 +733,12 @@ def test_system_link_bots_messages_are_the_games(): for data in sent: name = names[data[-1]] assert len(data) - 4 == sizes[name], name + limits = (root / "port/linux/include/halo_port_limits.h").read_text() + version = int(re.search(r"^#define HALO_PORT_NETWORK_VERSION (\d+)$", limits, re.M)[1]) + join = sent[0][3:-1] + assert sent[0][-1] == bots.CLIENT_JOIN_GAME_REQUEST + assert join[-2:] == struct.pack(">H", version) + assert join[112:-2] == bytes(170 + 64), "agreement must not replace account credentials" # ---------- the wire format (tools/network_format.py) @@ -700,8 +746,8 @@ def test_system_link_bots_messages_are_the_games(): def test_network_format_is_the_recorded_one(): """what the machines send each other is what port/linux/network_format.txt - records for HALO_PORT_NETWORK_VERSION, and NETCODE.md says what that - version changed""" + records for HALO_PORT_NETWORK_VERSION, and NETCODE.md says what that version + changed. The ordinary OpenCE contract is pinned by test_mcc_protocol.py.""" from tools import network_format problems = network_format.check() @@ -819,18 +865,19 @@ def riding_menu_layout(files): assert base + "/op_vehicle_riding" not in widgets assert base + "/var_vehicle_riding" not in strings assert "VEHICLE RIDING:" not in [s.get("text") for s in strings[base + "/labels"]] - assert len(strings[base + "/help_strings"]) == 17 + # GulchCE keeps its Session Options entries and full-height host rows. + assert len(strings[base + "/help_strings"]) == 20 help_widget = widgets[base + "/help"] - assert help_widget.get("font") == "ui\\small_ui" and int(help_widget.get("top")) == 366 - assert int(help_widget.get("top")) + int(help_widget.get("height")) <= 414 + assert help_widget.get("font") == "ui\\small_ui" and int(help_widget.get("top")) == 392 + assert int(help_widget.get("top")) + int(help_widget.get("height")) <= 448 for child in children: name = child.get("widget") if not name.endswith("/button_bar"): - assert int(child.get("y")) + int(widgets[name].get("height")) <= 366, name + assert int(child.get("y")) + int(widgets[name].get("height")) <= 392, name # (no empty row slot where a row left, and no row over the next one's) rows_y = sorted({int(c.get("y")) for c in children if not c.get("widget").endswith("/button_bar")}) - assert {b - a for a, b in zip(rows_y, rows_y[1:])} == {22}, rows_y + assert {b - a for a, b in zip(rows_y, rows_y[1:])} == {28}, rows_y coop = base + "/coop_options" coop_rows = widgets[coop + "/coop_options_menu"].findall("child")[:-1] for above, below in zip(coop_rows, coop_rows[1:]): diff --git a/tools/test_map_load_errors.py b/tools/test_map_load_errors.py new file mode 100644 index 0000000000..9055acc7af --- /dev/null +++ b/tools/test_map_load_errors.py @@ -0,0 +1,283 @@ +"""Real diagnostic formatters, failed-load lifetime and unchanged fatal UI.""" +from pathlib import Path +import subprocess + +from harness import function, structure +from test_mcc_identity import compile_tool + +ROOT = Path(__file__).resolve().parents[1] +GAME = ROOT / "port/linux/game" + + +def run_c(tmp_path, code): + source = tmp_path / "diagnostics.c" + source.write_text(code) + binary = compile_tool(tmp_path, [source, GAME / "mcc_errors.c", GAME / "custom_edition_errors.c"]) + result = subprocess.run([str(binary)], capture_output=True, text=True, timeout=10) + assert result.returncode == 0, result.stdout + result.stderr + + +def test_family_messages_are_bounded_and_keep_actionable_reasons(tmp_path): + run_c(tmp_path, r''' +#include "mcc_errors.h" +#include "custom_edition_errors.h" +#include +#include +#include +#define CHECK(c) do {if(!(c)){fprintf(stderr,"line %d\n",__LINE__);return 1;}}while(0) +int main(void) { + char text[512], tiny[4]={'x','x','x','!'}, long_name[1000]; + wchar_t wide[512]; + memset(long_name,'A',sizeof(long_name));long_name[999]=0; + custom_edition_error_message("a10",custom_edition_status_explanation(_cache_file_status_opensauce_cache),text,sizeof(text)); + CHECK(strstr(text,"OpenSauce") && strstr(text,"a10")); + custom_edition_error_message("b30",custom_edition_status_explanation(_cache_file_status_tag_cache_overflow),text,sizeof(text)); + CHECK(strstr(text,"tag-cache limit") && !strstr(text,"Close other")); + mcc_error_message("mcc_maps/pack/a10",mcc_status_explanation(MCC_CACHE_WRONG_VERSION),text,sizeof(text)); + CHECK(strstr(text,"pack/a10") && strstr(text,"version 13") && !strstr(text,"custom_maps")); + mcc_error_text("mcc_maps/other/a10","Resource sounds.map is invalid.",wide,512); + CHECK(wcsstr(wide,L"other/a10") && wcsstr(wide,L"sounds.map")); + mcc_error_message(long_name,"Install matching resources.",text,sizeof(text)); + CHECK(strstr(text,"Install matching resources.") && strlen(text)<=110); + mcc_error_message("mcc_maps/long_package_name/long_level_name",long_name,text,sizeof(text)); + CHECK(strstr(text,"long_packa...") && strstr(text,"_level_name") && strstr(text,"See debug.txt.")); + CHECK(strlen(text)<=110); + mcc_error_message("mcc_maps/p/a\n%ls", "bad\tresource",text,sizeof(text)); + CHECK(!strchr(text,'\n') && !strchr(text,'\t') && strstr(text,"%ls")); + mcc_error_message(NULL,NULL,tiny,3);CHECK(!tiny[2] && tiny[3]=='!'); + custom_edition_error_message(NULL,NULL,tiny,1);CHECK(!tiny[0]); + mcc_error_message(NULL,NULL,NULL,0);custom_edition_error_message(NULL,NULL,NULL,0); + return 0; +} +''') + + +def test_mcc_failure_reason_survives_cleanup_and_next_attempt_is_fresh(tmp_path): + actual = function((GAME / "mcc_cache.c").read_text(), "mcc_cache_tags_load") + run_c(tmp_path, r''' +#include "mcc_runtime.h" +#include "mcc_errors.h" +#include "mcc_loading.h" +#include +#include +#include +#include +#include +typedef int boolean; +#define TRUE 1 +#define NULL_HEADER ((struct cache_file_tag_header *)0) +#define NUMBEROF(a) (sizeof(a)/sizeof((a)[0])) +#define _error_silent 0 +struct cache_file_tag_header {int unused;}; +static struct mcc_runtime mcc_loaded_cache; +static FILE *mcc_stream; +static int mcc_loaded, fail, popups, cleanups; +static wchar_t queued[512]; +static void error(int p,char const *f,...) {(void)p;(void)f;} +static char const *mcc_identity_local_name(char const *s) {return s;} +static void mcc_cache_tags_unload(void) { + if(mcc_loaded_cache.tags)free(mcc_loaded_cache.tags); + memset(&mcc_loaded_cache,0,sizeof(mcc_loaded_cache));mcc_loaded=0;cleanups++; +} +static FILE *mcc_open_explain(char const *n,struct mcc_cache_source *s,struct mcc_cache_identity *i,char *reason,size_t size) { + (void)n;(void)s;memset(i,0,sizeof(*i));i->tag_data_size=64; + if(fail==1){snprintf(reason,size,"Its .map file is missing.");return NULL;} + return (FILE *)1; +} +static int mcc_package_name(char const *name,char *out) {strcpy(out,name);return 1;} +enum mcc_cache_status mcc_cache_load(struct mcc_cache_source const *s,void *raw,size_t size,struct mcc_cache_report *r) { + (void)s;(void)raw;(void)size;memset(r,0,sizeof(*r));return fail==2 ? MCC_CACHE_BAD_BSP : MCC_CACHE_OK; +} +char const *mcc_cache_status_string(enum mcc_cache_status s) {(void)s;return "technical reason";} +static int mcc_resources_select(struct mcc_runtime *r,void *raw) { + (void)raw;if(fail==3){strcpy(r->failure,"Resource sounds.map is invalid.");return 0;}return 1; +} +static int mcc_resources_checksum(struct mcc_runtime *r,unsigned mask,uint32_t *sum) {(void)r;(void)mask;*sum=1;return fail!=4;} +static int mcc_identity_loaded(char const *name,struct mcc_runtime *r) {(void)name;(void)r;return fail!=5;} +static void *mcc_memory_reserve(uint32_t a,uint32_t s) {(void)a;(void)s;return fail==6 ? NULL : calloc(1,128);} +static int mcc_scenario_identity(struct mcc_runtime *r,char const *n) {(void)r;(void)n;return fail!=7;} +static int mcc_hud_bitmaps_prepare(struct mcc_runtime *r) {(void)r;return 1;} +static int mcc_tags_prepare(struct mcc_runtime *r) {(void)r;return fail!=8;} +static int mcc_scripts_prepare(struct mcc_runtime *r) { + if(fail==9){strcpy(r->failure,"Unsupported script: fixture_function.");return 0;}return 1; +} +int mcc_geometry_prepare(struct mcc_runtime *r) {(void)r;return fail!=10;} +int mcc_audio_prepare(struct mcc_runtime *r) {(void)r;return fail!=11;} +int mcc_bitmaps_prepare(struct mcc_runtime *r) {(void)r;return fail!=12;} +void mcc_bitmaps_prepare_gpu(struct mcc_runtime *r) {(void)r;} +static int mcc_tags_validate(struct mcc_runtime *r) {(void)r;return fail!=13;} +int mcc_runtime_read(struct mcc_runtime *r,uint32_t off,uint32_t size,void *out) {(void)r;(void)off;memset(out,0,size);return fail!=14;} +static int mcc_script_threads_prepare(void) {return fail!=15;} +static void mcc_campaign_begin(void) {} +void mcc_loading_stage(enum mcc_loading_stage s) {(void)s;} +void mcc_loading_update(enum mcc_loading_stage s,unsigned long a,unsigned long b) {(void)s;(void)a;(void)b;} +static void display_error_text_when_main_menu_loaded(wchar_t const *s) {wcscpy(queued,s);popups++;} +''' + actual + r''' +#define CHECK(c) do {if(!(c)){fprintf(stderr,"line %d fail=%d\n",__LINE__,fail);return 1;}}while(0) +int main(void) { + unsigned char header[2048]; + wchar_t const *reason[]={L"",L"missing",L"geometry",L"sounds.map",L"read completely",L"changed after joining", + L"memory address",L"saved-game",L"converted",L"fixture_function",L"geometry",L"sounds",L"textures",L"validation",L"header",L"memory"}; + for(fail=1;fail<=15;fail++) { + CHECK(mcc_cache_tags_load("mcc_maps/package/a10",header)==NULL_HEADER); + CHECK(wcsstr(queued,L"package/a10") && wcsstr(queued,reason[fail])); + CHECK(!mcc_loaded_cache.failure[0] && !mcc_loaded_cache.tags && !mcc_loaded); + } + CHECK(popups==15 && cleanups==30); + fail=0;queued[0]=0; + CHECK(mcc_cache_tags_load("mcc_maps/other/a10",header)!=NULL_HEADER && mcc_loaded && !queued[0]); + mcc_cache_tags_unload(); + return 0; +} +''') + + +def test_fatal_media_text_preserves_widget_and_loop_lifecycle(tmp_path): + ui = (ROOT / "source/interface/ui_widget.c").read_text() + actual = "\n".join(function(ui, name) for name in ( + "display_error_abort_to_dashboard", "display_error_damaged_media", "display_error_damaged_media_text")) + run_c(tmp_path, r''' +#include +#include +#include +typedef int boolean; +#define TRUE 1 +#define FALSE 0 +#define NONE -1 +#define _ui_widget_type_text_box 1 +#define _error_media_damaged 2 +#define _error_silent 0 +#define NUMBEROF(a) (sizeof(a)/sizeof((a)[0])) +#define match_vassert(a,b,c,d) ((void)0) +#define ustrncpy wcsncpy +struct widget_instance {int type;struct {struct {int string_list_index;} text_box;} parameters;int widget_is_error_dialog;}; +static struct widget_instance widget, *ui_widget_port_error_text_box; +static wchar_t const *ui_widget_port_fatal_text,*ui_widget_port_error_text; +static int dashboard_abort_error,closes,loops,ends,missing; +static void error(int p,char const *f,...) {(void)p;(void)f;} +static void ui_widgets_close_all(void) {closes++;ui_widget_port_error_text=NULL;ui_widget_port_error_text_box=NULL;} +static struct widget_instance *ui_widget_load_by_name_or_tag(char const *n,int a,void *b,int c,int d,int e,int f) { + (void)n;(void)a;(void)b;(void)c;(void)d;(void)e;(void)f;widget.type=1;return missing ? NULL : &widget; +} +static void input_frame_end(void) {ends++;} +static void main_loop_of_death(void) {loops++;} +''' + actual + r''' +int main(void) { + wchar_t text[32]=L"Missing bitmaps.map"; + display_error_damaged_media_text(text);text[0]='X'; + if(closes!=1 || loops!=1 || ends!=1 || dashboard_abort_error!=2 || !widget.widget_is_error_dialog)return 1; + if(ui_widget_port_fatal_text || ui_widget_port_error_text_box!=&widget || wcscmp(ui_widget_port_error_text,L"Missing bitmaps.map"))return 2; + display_error_damaged_media(); + if(closes!=2 || loops!=2 || ends!=2 || ui_widget_port_error_text)return 3; + missing=1;display_error_damaged_media_text(L"another failure"); + if(ui_widget_port_fatal_text || ui_widget_port_error_text || loops!=3)return 4; + return 0; +} +''') + + +def test_main_menu_queue_copies_and_keeps_first_failure(tmp_path): + actual = function((ROOT / "source/interface/ui_widget.c").read_text(), "display_error_text_when_main_menu_loaded") + run_c(tmp_path, r''' +#include +#include +#define NONE -1 +#define _error_silent 0 +#define NUMBEROF(a) (sizeof(a)/sizeof((a)[0])) +#define ustrncpy wcsncpy +#define _error_cannot_create_saved_game_file_with_empty_name 10 +static struct {int main_menu_deferred_error_code;} widget_globals={NONE}; +static wchar_t const *ui_widget_port_error_pending_text; +static void error(int p,char const *f,...) {(void)p;(void)f;} +''' + actual + r''' +int main(void) { + wchar_t reason[64]=L"Resource sounds.map is invalid"; + display_error_text_when_main_menu_loaded(reason);reason[0]='X'; + display_error_text_when_main_menu_loaded(L"generic recovery fallback"); + if(wcscmp(ui_widget_port_error_pending_text,L"Resource sounds.map is invalid"))return 1; + widget_globals.main_menu_deferred_error_code=NONE; + display_error_text_when_main_menu_loaded(L"next attempt"); + return wcscmp(ui_widget_port_error_pending_text,L"next attempt")!=0; +} +''') + + +def test_ce_load_failure_is_consumed_without_changing_cleanup(tmp_path): + cache = (GAME / "custom_edition_cache.c").read_text() + types = "\n".join(structure(cache, name) for name in ( + "custom_edition_file", "custom_edition_cache_globals")) + actual = "\n".join(function(cache, name) for name in ( + "custom_edition_cache_tags_load", "custom_edition_cache_load_error")) + run_c(tmp_path, r''' +#include "custom_edition_errors.h" +#include +#include +#include +typedef int boolean; +typedef unsigned char byte; +#define TRUE 1 +#define FALSE 0 +#define MAP_PATH_SIZE 256 +#define READ_STAGING_BYTES 65536 +#define COMBINED_DECODED_OFFSET 0x30000000u +#define COMBINED_BITMAPS_OFFSET 0x40000000u +#define COMBINED_SOUNDS_OFFSET 0x60000000u +#define COMBINED_OFFSET_LIMIT 0x80000000u +#define CACHE_FILE_HEADER_FILE_LENGTH_OFFSET 8 +#define _error_silent 0 +#define csstrcasecmp strcmp +struct cache_file_tag_header {int unused;}; +''' + types + r''' +static struct custom_edition_cache_globals custom_edition_cache_globals; +static char custom_edition_failure_name[64],custom_edition_failure_reason[320]; +static int fail,closes,disposals; +static unsigned char tags[128]; +static int custom_edition_level_name(char const *s) {return !strncmp(s,"custom_maps\\",12);} +static char const *tag_name_strip_path(char const *s) {char const *p=strrchr(s,'\\');return p ? p+1 : s;} +static unsigned char *halo_custom_edition_tag_cache(void) {return fail==1 ? NULL : tags;} +static char const *custom_edition_unavailable_reason(void) {return "Custom Edition maps are turned off.";} +static void error(int p,char const *f,...) {(void)p;(void)f;} +static int custom_edition_map_path(char const *n,char *p) {strcpy(p,n);return fail!=2;} +static int read_file(void *c,uint32_t off,uint32_t size,void *out) {(void)c;(void)off;memset(out,0,size);return 1;} +static int custom_edition_file_open(struct custom_edition_file *f,char const *p) {(void)p;f->source.read=read_file;return 1;} +enum cache_file_status cache_file_identify(struct cache_file_source *s,struct cache_file_identity *i) { + (void)s;memset(i,0,sizeof(*i));i->format=_cache_file_format_custom_edition_cache; + return fail==3 ? _cache_file_status_opensauce_cache : _cache_file_status_ok; +} +char const *cache_file_status_describe(enum cache_file_status s) {(void)s;return "technical check";} +static void custom_edition_cache_files_close(void) {memset(&custom_edition_cache_globals,0,sizeof(custom_edition_cache_globals));closes++;} +static int custom_edition_resource_map_path(enum resource_map_type t,char *p) {(void)t;strcpy(p,"resource");return 1;} +enum cache_file_status resource_map_open(struct cache_file_source *s,enum resource_map_type t,struct resource_map *m) { + (void)s;(void)t;(void)m;return _cache_file_status_ok; +} +enum cache_file_status custom_edition_cache_load(struct cache_file_source *s,struct resource_map *const *m, + uint8_t *data,uint32_t size,struct custom_edition_load_report *r) { + (void)s;(void)m;(void)data;(void)size;memset(r,0,sizeof(*r)); + return fail==4 ? _cache_file_status_tag_cache_overflow : _cache_file_status_ok; +} +static void custom_edition_cache_report_log(struct custom_edition_load_report const *r) {(void)r;} +static int custom_edition_cache_tags_convert(uint8_t *data,struct custom_edition_load_report const *r) { + (void)data;(void)r;if(fail==5){strcpy(custom_edition_failure_reason,"Its scripts could not be prepared.");return 0;}return 1; +} +static void custom_edition_sounds_dispose(void) {disposals++;} +static void custom_edition_models_dispose(void) {disposals++;} +static void custom_edition_bitmaps_dispose(void) {disposals++;} +''' + actual + r''' +#define CHECK(c) do {if(!(c)){fprintf(stderr,"line %d fail=%d\n",__LINE__,fail);return 1;}}while(0) +int main(void) { + unsigned char header[2048]; + char const *reason[]={"","turned off","missing","OpenSauce","tag-cache limit","scripts"}; + for(fail=1;fail<=5;fail++) { + CHECK(!custom_edition_cache_tags_load("a10",header)); + CHECK(!strcmp(custom_edition_cache_load_error("levels\\a10\\a10"),"game_load() failed.")); + CHECK(strstr(custom_edition_cache_load_error("custom_maps\\a10"),reason[fail])); + CHECK(!custom_edition_failure_name[0] && !custom_edition_failure_reason[0]); + } + CHECK(closes==3 && disposals==3); + fail=4;CHECK(!custom_edition_cache_tags_load("a10",header)); + CHECK(!strstr(custom_edition_cache_load_error("custom_maps\\b30"),"tag-cache limit")); + fail=0;CHECK(custom_edition_cache_tags_load("a10",header)!=NULL); + CHECK(!custom_edition_failure_name[0] && !custom_edition_failure_reason[0] && custom_edition_cache_globals.tags_loaded); + return 0; +} +''') diff --git a/tools/test_material_prepare.py b/tools/test_material_prepare.py new file mode 100644 index 0000000000..c1f45f7c7f --- /dev/null +++ b/tools/test_material_prepare.py @@ -0,0 +1,65 @@ +"""The real preparation gates: no pixel fallback, bounded metadata, inactive/GLES paths.""" +import os +from pathlib import Path +import shutil +import subprocess +import pytest + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.mark.parametrize('gles', [False, True]) +def test_material_preparation_gates(tmp_path, gles): + compiler = shutil.which('clang') + if not compiler: + pytest.skip('clang required') + source = (ROOT/'port/linux/game/material_prepare.c').read_text() + state = source[source.index('#ifndef HALO_GLES'):source.index('/* Native draw-packet')] + functions = source[source.index('int material_prepare_skip_shader'):source.index('void material_prepare_map')] + code = r''' +#include +#include +typedef struct {unsigned Data;} D3DBaseTexture; +struct bitmap_data {int valid;}; +struct shader {struct {int type;} base;}; +static int calls,draws; +static int texture_cache_prepare_descriptor(struct bitmap_data *b,void *p) { + calls++;((D3DBaseTexture *)p)->Data=0;return b->valid; +} +static void render_material_prepare_draw(void) {draws++;} +''' + code += state+'\n#endif\n'+functions + code += r''' +int main(void) { + struct bitmap_data b[4097];struct shader shader; + void *header=(void *)123;int i; + assert(!material_prepare_bitmap(&b[0],&header) && header==(void *)123); + assert(!material_prepare_draw() && !material_prepare_skip_shader(NULL)); +#ifndef HALO_GLES + bitmaps=calloc(MATERIAL_BITMAP_LIMIT,sizeof(*bitmaps));assert(bitmaps);preparing=1; + b[0].valid=0;assert(material_prepare_bitmap(&b[0],&header) && !header && !bitmap_count); + for(i=0;i<4097;i++)b[i].valid=1; + assert(material_prepare_bitmap(&b[0],&header) && header && ((D3DBaseTexture *)header)->Data==1); + assert(material_prepare_bitmap(&b[0],&header) && calls==2 && bitmap_count==1); + for(i=1;i<4096;i++)assert(material_prepare_bitmap(&b[i],&header) && header); + assert(material_prepare_bitmap(&b[4096],&header) && !header && bitmap_count==4096); + assert(material_prepare_draw() && draws==1); + for(i=0;i +#include +#include +#define CHECK(x) do {if(!(x)){fprintf(stderr,"line %d: %s\n",__LINE__,#x);return 1;}}while(0) +static struct mcc_admission host,client; +static struct mcc_admission_message sent; +static int sends,blocked,valid=1,players; +static long destination; +static int send(void *user,long machine,struct mcc_admission_message const *m){ + (void)user;sent=*m;destination=machine;sends++;return !blocked; +} +static int peer(void *user,long machine){(void)user;return valid && machine==2;} +static int has_players(void *user,long machine){(void)user;(void)machine;return players;} +static struct mcc_admission_identity identity; +static void setup(uint32_t now){ + struct mcc_admission_env env={NULL,send,peer,has_players}; + memset(&identity,0,sizeof(identity));strcpy(identity.name,"mcc_maps\\package\\level"); + identity.name[64]=7;identity.content[31]=42;identity.metadata[0]=19;identity.checksum=123; + mcc_admission_init(&host,&env);mcc_admission_init(&client,&env); + mcc_admission_tick(&host,now,&identity,1); +} +static void deliver(uint32_t now){ + struct mcc_admission_message request=sent; + mcc_admission_receive(&host,2,&request,sizeof(request),now); + if(destination==2)mcc_admission_receive(&client,-1,&sent,sizeof(sent),now); +} +int main(int argc,char **argv){ + struct mcc_admission_message message;uint32_t now=1000,start;int test,old,i; + if(argc!=2)return 2;test=atoi(argv[1]);setup(now); + CHECK(mcc_admission_begin(&client,&identity,now));message=sent; + if(test==0){ + CHECK(!mcc_admission_status(&client));deliver(now);CHECK(mcc_admission_status(&client)==1); + CHECK(mcc_admission_active(&host,2,now,1));start=host.peers[2].started; + for(i=1;i<24;i++){ + now=1000+i*5000;mcc_admission_tick(&client,now,NULL,0);deliver(now); + mcc_admission_tick(&host,now,&identity,1); + CHECK(mcc_admission_active(&host,2,now,1));CHECK(host.peers[2].started==start); + } + now=121000;mcc_admission_tick(&host,now,&identity,1); + CHECK(!mcc_admission_active(&host,2,now,0));message.generation++; + mcc_admission_receive(&host,2,&message,sizeof(message),now); + CHECK(sent.op==MCC_ADMISSION_REFUSED && !mcc_admission_active(&host,2,now,0)); + mcc_admission_tick(&client,now,NULL,0);CHECK(mcc_admission_status(&client)==-1); + }else if(test==1){ + old=sends; + mcc_admission_receive(&host,2,&message,sizeof(message)-1,now); + mcc_admission_receive(&host,3,&message,sizeof(message),now); + message.generation=0;mcc_admission_receive(&host,2,&message,sizeof(message),now);message=sent; + message.identity.name[64]^=1;mcc_admission_receive(&host,2,&message,sizeof(message),now);message=sent; + message.identity.metadata[31]^=1;mcc_admission_receive(&host,2,&message,sizeof(message),now);message=sent; + message.identity.content[31]^=1;mcc_admission_receive(&host,2,&message,sizeof(message),now);message=sent; + message.identity.checksum++;mcc_admission_receive(&host,2,&message,sizeof(message),now);message=sent; + message.op=99;mcc_admission_receive(&host,2,&message,sizeof(message),now); + CHECK(sends==old && !mcc_admission_active(&host,2,now,1)); + message=sent;message.op=MCC_ADMISSION_ACK;message.generation++; + mcc_admission_receive(&client,-1,&message,sizeof(message),now);CHECK(!mcc_admission_status(&client)); + message.generation--;message.identity.name[64]^=1; + mcc_admission_receive(&client,-1,&message,sizeof(message),now);CHECK(!mcc_admission_status(&client)); + }else if(test==2){ + deliver(now);players=1;mcc_admission_tick(&host,now,&identity,1); + CHECK(mcc_admission_active(&host,2,now,1)); /* next mission still needs validation */ + players=0;mcc_admission_finish(&client,1,now+1);deliver(now+1); + CHECK(!mcc_admission_active(&host,2,now+1,1));CHECK(mcc_admission_active(&host,2,now+1,0)); + CHECK(!mcc_admission_active(&host,2,now+15001,0)); + players=1;mcc_admission_tick(&host,now+2,&identity,1);CHECK(!mcc_admission_active(&host,2,now+2,0)); + }else if(test==3){ + deliver(now);now+=MCC_ADMISSION_HEARD; + mcc_admission_receive(&host,2,&message,sizeof(message),now);CHECK(sent.op==MCC_ADMISSION_REFUSED); + CHECK(!mcc_admission_active(&host,2,now,0)); + mcc_admission_forget(&host,2);mcc_admission_receive(&host,2,&message,sizeof(message),now); + CHECK(mcc_admission_active(&host,2,now,1)); + valid=0;mcc_admission_tick(&host,now+1,&identity,1);CHECK(!mcc_admission_active(&host,2,now+1,1)); + }else if(test==4){ + deliver(now);message=client.client;message.op=MCC_ADMISSION_CANCEL; + mcc_admission_receive(&host,2,&message,sizeof(message),now);CHECK(!mcc_admission_active(&host,2,now,0)); + message.op=MCC_ADMISSION_BEGIN;message.generation++; + mcc_admission_receive(&host,2,&message,sizeof(message),now+1000); + CHECK(sent.op==MCC_ADMISSION_REFUSED && !mcc_admission_active(&host,2,now+1000,0)); + mcc_admission_tick(&host,now,&host.host,2); /* alias-safe identity reset */ + mcc_admission_receive(&host,2,&message,sizeof(message),now);CHECK(mcc_admission_active(&host,2,now,1)); + identity.name[64]++;mcc_admission_tick(&host,now,&identity,3); + mcc_admission_receive(&host,2,&message,sizeof(message),now);CHECK(!mcc_admission_active(&host,2,now,1)); + }else if(test==5){ + setup(0xfffff000u);now=0xfffff000u;CHECK(mcc_admission_begin(&client,&identity,now));deliver(now); + now+=5000;mcc_admission_tick(&client,now,NULL,0);deliver(now);CHECK(mcc_admission_status(&client)==1); + blocked=1;mcc_admission_finish(&client,1,now);CHECK(client.state>0); + blocked=0;mcc_admission_tick(&client,now+1,NULL,0);CHECK(client.state==0 && sent.op==MCC_ADMISSION_READY); + }else if(test==6){ + deliver(now);old=sends;message=client.client; + for(i=0;i<1000;i++)mcc_admission_receive(&host,2,&message,sizeof(message),now); + CHECK(sends==old);message.op=MCC_ADMISSION_REFUSED; + mcc_admission_receive(&client,-1,&message,sizeof(message),now);CHECK(mcc_admission_status(&client)==-1); + }else return 2; + return 0; +} +''') + return compile_tool(work, [source, ROOT / "port/linux/game/mcc_admission.c"]) + + +@pytest.mark.parametrize("case", range(7), ids=["fixed-deadline", "untrusted-input", "ready-grace", + "silence-and-peer-lifetime", "tombstone-revision", + "clock-wrap-backpressure", "rate-and-refusal"]) +def test_lease(admission_tool, case): + result = subprocess.run([str(admission_tool), str(case)], capture_output=True, text=True) + assert result.returncode == 0, result.stderr + + +@pytest.mark.parametrize("missing_lobby_route", [False, True], ids=["current-route", "before-fix-route"]) +def test_game_adapter_authenticates_transport_and_current_settings(tmp_path, missing_lobby_route): + from harness import structure, function, enum_with + + headers = { + "cseries.h": "#pragma once\n#include \ntypedef int boolean;typedef unsigned short word;typedef unsigned char byte;\n#define NONE -1\n#define NUMBEROF(a) (sizeof(a)/sizeof((a)[0]))\n", + "networking/network_game_manager.h": "#pragma once\nstruct network_player {int valid,machine_index;};\nstruct network_game {struct {long version;char name[128];} map;unsigned char mcc_content_sha256[32],mcc_metadata_sha256[32];struct network_player players[4];};\nboolean network_player_is_valid(struct network_player *);\n", + "networking/network_game_globals.h": "#pragma once\nstruct network_game_server {int dummy;};struct network_game_client {int dummy;};struct network_game_server_client_machine {int dummy;};\nstruct network_game_server *global_network_game_server_get(void);struct network_game_client *global_network_game_client_get(void);struct network_game *network_game_get_game(void);\n", + "networking/network_client_manager.h": "struct network_game *network_game_client_get_game(struct network_game_client *);\n", + } + for name, text in headers.items(): + path = tmp_path / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + path = tmp_path / "bungie_net/common/message_header.h" + path.parent.mkdir(parents=True) + path.write_text((ROOT / "source/bungie_net/common/message_header.h").read_text()) + distributed = (ROOT / "port/linux/game/network_distributed.h").read_text() + # Production is ILP32 and asserts this header is12 bytes. Native Linux + # test compilers are LP64; preserve wire fields instead of adding tail + # padding to the adapter envelope and falsely rejecting valid packets. + (tmp_path / "network_distributed.h").write_text( + '#include \n#include "bungie_net/common/message_header.h"\n' + structure(distributed, "distributed_message_header").replace('unsigned long', 'uint32_t').replace('long', 'int32_t') + + '\ntypedef char wire_header_is_12[sizeof(struct distributed_message_header)==12 ? 1 : -1];' + + '\nenum {_distributed_message_mcc_admission=105};\n') + # Compile the complete production adapter with the same public APIs and a + # controlled engine, not a second implementation of its packet checks. + adapter = tmp_path / "adapter.c" + adapter.write_text((ROOT / "port/linux/game/mcc_admission_game.c").read_text()) + server_source = (ROOT / "source/networking/network_server_message_handler.c").read_text() + ingress = function(server_source, "network_game_server_handle_client_message") + if missing_lobby_route: + before = "if (mcc_admission_handles_message(message, message_buffer_size))" + assert ingress.count(before) == 1 + ingress = ingress.replace(before, "if (0)") + datagram = function(server_source, "network_game_server_handle_datagram") + unrelated = "".join(f"#define {name}(...) 1\n" for name in sorted(set( + __import__("re").findall(r"\b(network_game_server_handle_message_\w+)\(", ingress + datagram)))) + declarations = r''' +#include "third_person_protocol.h" +#define MINIMUM_TRANSPORT_ERROR_MESSAGE_SIZE 4 +#define TRANSPORT_ERROR_MESSAGE_TEXT_LENGTH 1 +#define _network_game_server_state_ingame 1 +#define match_assert(...) ((void)0) +static void network_event(char const *format,...){(void)format;} +#define third_person_session_active() 0 +#define third_person_protocol_unwrap(a,b,c,d) ((void)(a),(void)(b),(void)(c),(void)(d),0) +#define network_game_server_get_state(...) ingame +#define network_game_server_client_machine_is_loaded(...) loaded +static int network_game_server_get_client_machine(struct network_game_server *s,struct network_game_server_client_machine *m,long *index){(void)s;(void)m;*index=2;return mapped;} +#define network_game_server_client_machine_heard(...) ((void)0) +#define network_distributed_handle_stream_message(...) (++ordinary) +#define network_voice_handles_message(...) 0 +#define network_voice_handle_message(...) ((void)0) +#define mcc_share_game_handles_message(...) 0 +#define mcc_share_game_handle_message(...) ((void)0) +#define map_share_handles_message(...) 0 +#define map_share_handle_message(...) ((void)0) +#define network_map_vote_handles_message(...) 0 +#define network_map_vote_handle_message(...) ((void)0) +#define transport_error_message_text(...) "unused" +#define TRUE 1 +#define FALSE 0 +#define NETWORK_GAME_MESSAGE_VERSION 2 +#define _network_game_packet_class_client_search 0 +#define _network_game_packet_class_client_ingame 1 +#define MAXIMUM_NETWORK_MACHINE_COUNT 4 +#define VALID_INDEX(i,n) ((unsigned)(i)<(unsigned)(n)) +struct transport_address {struct {unsigned long long_words[1];} address;}; +struct message_client_broadcast_game_search {int dummy;}; +struct message_client_ping {int dummy;}; +struct message_client_game_update {int dummy;}; +static struct {void *connection;struct transport_address address;} network_distributed_return_addresses[4]; +#define network_game_server_datagram_event_logged() 0 +#define transport_address_to_string(...) "unused" +#define network_game_should_accept_remote_connections() 0 +#define decode_network_game_message(a,b,c,d,e,f) ((void)(a),(void)(b),(void)(c),(void)(d),(void)(e),(void)(f),0) +#define network_game_server_get_client_machine_at_address(...) (joined ? &peer : NULL) +#define network_game_server_get_remote_client_machine_at_address(...) (joined ? &peer : NULL) +#define network_game_server_handle_client_update_packet(...) ((void)0) +#define network_game_server_get_client_connection(...) NULL +#define network_distributed_handle_message(i,m,n) (mcc_load_network_handles_message(m,n) ? mcc_load_network_handle_message(i,m,n,0) : mcc_admission_handle_message(i,m,n,0)) +''' + unrelated + enum_with((ROOT / "source/networking/network_messages.h").read_text(), + "_message_client_broadcast_game_search") + enum_with(server_source, "_message_type_error") + source = tmp_path / "test.c" + source.write_text(r''' +#include "cseries.h" +#include "networking/network_game_globals.h" +#include "networking/network_game_manager.h" +#include "network_distributed.h" +#include "mcc_admission.h" +#include +#include +#define CHECK(x) do {if(!(x)){fprintf(stderr,"line %d: %s\n",__LINE__,#x);return 1;}}while(0) +static struct network_game game; +static struct network_game_server server; +static struct network_game_client client; +static struct network_game_server_client_machine peer; +static int hosting=1,joined=1,connected=1,sends,ingame,loaded,ordinary,mapped=1,progress; +static unsigned long now=1000,revision=1; +static struct {struct distributed_message_header header;struct mcc_admission_message body;} packet,last; +typedef char wire_message_is_216[sizeof(packet)==216 ? 1 : -1]; +static int mcc_load_network_handles_message(void const *data,unsigned size){return size>=sizeof(struct distributed_message_header) && ((struct distributed_message_header const *)data)->type==106;} +static void mcc_load_network_handle_message(long index,void const *data,unsigned size,int reliable){(void)index;(void)data;(void)size;if(reliable)progress++;} +struct network_game_server *global_network_game_server_get(void){return hosting ? &server : NULL;} +struct network_game_client *global_network_game_client_get(void){return connected ? &client : NULL;} +struct network_game *network_game_get_game(void){return &game;} +struct network_game *network_game_client_get_game(struct network_game_client *c){(void)c;return &game;} +struct network_game_server_client_machine *network_game_server_get_client_machine_at_index(struct network_game_server *s,long n){(void)s;return n==2 ? &peer : NULL;} +boolean network_game_server_client_machine_is_joined_to_game(struct network_game_server *s,struct network_game_server_client_machine *p){(void)s;return joined && p==&peer;} +boolean network_player_is_valid(struct network_player *p){return p->valid;} +boolean mcc_level_name(char const *name){return !strncmp(name,"mcc_maps\\",9);} +unsigned long mcc_identity_host_revision(void){return revision;} +void const *mcc_identity_host_settings(void const *g,long bytes,struct network_game *copy){if(bytes!=sizeof(*copy))return NULL;memcpy(copy,g,bytes);return copy;} +unsigned long system_milliseconds(void){return now;} +void build_message_header(word *out,word size,byte type,byte flags){*out=(word)((size<<4)|(type<<2)|flags);} +boolean network_distributed_client_send_reliably(void *p,word size){if(size!=sizeof(last))return 0;memcpy(&last,p,size);sends++;return 1;} +boolean network_distributed_server_send_to_machine_reliably(long n,void *p,word size){if(n!=2)return 0;return network_distributed_client_send_reliably(p,size);} +''' + declarations + ingress + datagram + r''' +static void receive(int reliable){ + struct transport_address address={{0}}; + if(reliable)network_game_server_handle_client_message(&server,&peer,(word *)&packet,sizeof(packet)); + else network_game_server_handle_datagram(&server,(word *)&packet,sizeof(packet),&address); +} +int main(void){ + int old;uint32_t token; + strcpy(game.map.name,"mcc_maps\\package\\level");game.map.name[64]=9; + game.map.version=123;game.mcc_content_sha256[31]=42;game.mcc_metadata_sha256[0]=7; + packet.header.type=105;packet.header.count=1;build_message_header(&packet.header.header,sizeof(packet),2,0); + packet.body.op=MCC_ADMISSION_BEGIN;packet.body.generation=1; + memcpy(packet.body.identity.name,game.map.name,128);packet.body.identity.checksum=123; + memcpy(packet.body.identity.content,game.mcc_content_sha256,32);memcpy(packet.body.identity.metadata,game.mcc_metadata_sha256,32); + CHECK(mcc_admission_handles_message(&packet,sizeof(packet))); + packet.header.type=106;receive(0);CHECK(!progress); + ingame=loaded=1;receive(0);CHECK(!progress);ingame=loaded=0; + joined=0;receive(1);CHECK(!progress);joined=1; + receive(1);CHECK(progress==1 && !ingame && !loaded);packet.header.type=105; + receive(0);CHECK(!sends && !mcc_admission_host_active(2)); + ingame=loaded=1;receive(0);CHECK(!sends && !mcc_admission_host_active(2));ingame=loaded=0; + mcc_admission_handle_message(3,&packet,sizeof(packet),1);CHECK(!sends); + mcc_admission_handle_message(2,&packet,sizeof(packet)-1,1);CHECK(!sends); + packet.header.count=2;receive(1);CHECK(!sends);packet.header.count=1; + packet.header.header|=1;receive(1);CHECK(!sends);packet.header.header&=~1; + joined=0;receive(1);CHECK(!sends);joined=1; + mapped=0;receive(1);CHECK(!sends);mapped=1; + receive(1);CHECK(sends==1 && last.body.op==MCC_ADMISSION_ACK && mcc_admission_host_needs_map(2)); + CHECK(!ingame && !loaded && !ordinary); + packet.header.type=1;receive(1);CHECK(!ordinary); + ingame=loaded=1;receive(1);CHECK(ordinary==1);ingame=loaded=0;packet.header.type=105; + old=sends;packet.body.identity.name[64]++;receive(1);CHECK(sends==old);packet.body.identity.name[64]--; + revision++;game.map.name[64]++;mcc_admission_update();CHECK(!mcc_admission_host_active(2)); + receive(1);CHECK(sends==old); /* old origin cannot inherit revised hold */ + mcc_admission_disconnect();hosting=0;game.map.name[64]--; + CHECK(mcc_admission_client_begin(&game));CHECK(mcc_admission_client_pending()); + token=mcc_admission_client_token();mcc_admission_client_clear(); + CHECK(mcc_admission_client_begin(&game));CHECK(token!=mcc_admission_client_token()); + mcc_admission_client_release(token);CHECK(mcc_admission_client_pending()); + packet=last;packet.body.op=MCC_ADMISSION_ACK; + mcc_admission_handle_message(NONE,&packet,sizeof(packet),0);CHECK(!mcc_admission_client_status()); + mcc_admission_handle_message(NONE,&packet,sizeof(packet),1);CHECK(mcc_admission_client_status()==1); + game.map.name[64]++;mcc_admission_update();CHECK(mcc_admission_client_status()==-1); + mcc_admission_disconnect();CHECK(!mcc_admission_client_pending()); + CHECK(mcc_admission_client_begin(&game));token=mcc_admission_client_token(); + mcc_admission_client_release(token);CHECK(!mcc_admission_client_pending()); + return 0; +} +''') + exe = compile_tool(tmp_path, [source, adapter, ROOT / "port/linux/game/mcc_admission.c"]) + result = subprocess.run([str(exe)], capture_output=True, text=True) + if missing_lobby_route: + assert result.returncode == 1 and "sends==1" in result.stderr, result.stderr + else: + assert result.returncode == 0, result.stderr diff --git a/tools/test_mcc_android_importer.py b/tools/test_mcc_android_importer.py new file mode 100644 index 0000000000..6e1af61531 --- /dev/null +++ b/tools/test_mcc_android_importer.py @@ -0,0 +1,21 @@ +"""Exercise the Android importer's actual Java core without an Android device.""" +from pathlib import Path +import shutil +import subprocess + +import pytest + +ROOT = Path(__file__).resolve().parents[1] + + +def test_android_mcc_importer(tmp_path): + javac, java = shutil.which("javac"), shutil.which("java") + if not javac or not java: + pytest.skip("JDK 17+ is required") + source = ROOT / "port/android/app/src/main/java/com/halo/decomp" + subprocess.run([javac, "--release", "17", "-Xlint:all", "-d", str(tmp_path), + str(source / "MccJson.java"), str(source / "MccPackageImporter.java"), + str(ROOT / "tools/tests/MccPackageImporterTest.java")], check=True, capture_output=True, text=True) + result = subprocess.run([java, "-cp", str(tmp_path), "com.halo.decomp.MccPackageImporterTest", str(tmp_path)], + capture_output=True, text=True, timeout=60) + assert result.returncode == 0, result.stdout + result.stderr diff --git a/tools/test_mcc_avoidance.py b/tools/test_mcc_avoidance.py new file mode 100644 index 0000000000..aff8566b03 --- /dev/null +++ b/tools/test_mcc_avoidance.py @@ -0,0 +1,66 @@ +"""MCC passengers must not enter or continue independent movement avoidance.""" +from pathlib import Path +import shutil +import subprocess +import sys +import pytest +from harness import function + +ROOT = Path(__file__).resolve().parents[1] + + +def test_passenger_avoidance_and_legacy_path(tmp_path): + compiler = shutil.which("clang") or shutil.which("cc") + if not compiler: + pytest.skip("C compiler required") + adapter = (ROOT / "port/linux/game/mcc_seats.c").read_text() + native = (ROOT / "source/ai/action_avoid.c").read_text() + source = r''' +#include +typedef int boolean; +#define TRUE 1 +#define FALSE 0 +#define match_assert(a,b,c) ((void)0) +enum {_firing_point_evaluation_mode_avoid=6}; +struct actor_datum {struct {int timeslice,swarm;} meta;struct {int vehicle_passenger;} input; + struct {int danger_type;} danger_zone;}; +struct avoid_state_data {int unused;}; +struct firing_position {int unused;}; +struct firing_position_evaluation_context {int evaluation_mode;}; +struct path_state {int unused;}; +static struct actor_datum actor; +static int active,selections; +static boolean mcc_cache_tags_loaded(void) {return active;} +static struct actor_datum *actor_get(long i) {(void)i;return &actor;} +static short actor_active_select_firing_position(long i,void *s,void *c,long *o,void *w,boolean *f) +{(void)i;(void)s;(void)c;(void)w;*o=0;*f=0;++selections;return -1;} +static void actor_change_firing_position(long i,short p,void *c,long o,void *w,boolean f) +{(void)i;(void)p;(void)c;(void)o;(void)w;(void)f;} +''' + function(adapter, "mcc_seat_blocks_avoidance") + "\n" + "\n".join( + function(native, name) for name in ("action_avoid_setup", "action_avoid_perform")) + r''' +int main(void) { + struct avoid_state_data state; + actor.meta.timeslice=1;actor.danger_zone.danger_type=1; + actor.input.vehicle_passenger=1; + if(!action_avoid_setup(0,&state)||action_avoid_perform(0)||selections!=1)return 1; + active=1;state.unused=123; + if(action_avoid_setup(0,&state)||state.unused!=123||!action_avoid_perform(0)||selections!=1)return 2; + actor.input.vehicle_passenger=0; + if(!action_avoid_setup(0,&state)||state.unused||action_avoid_perform(0)||selections!=2)return 3; + actor.input.vehicle_passenger=1; /* Seated after avoidance setup. */ + if(!action_avoid_perform(0)||selections!=2)return 4; + active=0;if(action_avoid_perform(0)||selections!=3)return 5; + return 0; +} +''' + path = tmp_path / "avoidance.c" + path.write_text(source) + binary = tmp_path / ("avoidance.exe" if sys.platform == "win32" else "avoidance") + command = [compiler, "-std=gnu89", "-Wall", "-Werror", str(path), "-o", str(binary)] + if sys.platform == "win32": + command[1:1] = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld"] + result = subprocess.run(command, + capture_output=True, text=True) + assert result.returncode == 0, result.stderr + result = subprocess.run([str(binary)], capture_output=True, text=True, timeout=10) + assert result.returncode == 0, result.stdout + result.stderr diff --git a/tools/test_mcc_bitmap_flags.py b/tools/test_mcc_bitmap_flags.py new file mode 100644 index 0000000000..d4d2e83231 --- /dev/null +++ b/tools/test_mcc_bitmap_flags.py @@ -0,0 +1,444 @@ +"""Exercise MCC descriptor conversion with generated pixels, without map assets.""" +from pathlib import Path +import shutil +import subprocess +import sys + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from harness import function, structure + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.fixture(scope="module") +def bitmap_converter(tmp_path_factory): + compiler = shutil.which("clang") + if not compiler: + pytest.skip("clang is needed for MCC bitmap conversion tests") + bitmap = (ROOT / "port/linux/game/mcc_bitmaps.c").read_text() + native = (ROOT / "source/bitmaps/bitmaps.c").read_text() + swizzle = (ROOT / "source/rasterizer/rasterizer_swizzle.c").read_text() + source = r''' +#include +#include +#include +#include +#include +#define MIN(a,b) ((a)<(b)?(a):(b)) +#define MAX(a,b) ((a)>(b)?(a):(b)) +#define TRUE 1 +#define FALSE 0 +#define NONE -1 +#define FLAG(bit) (1u<<(bit)) +#define TEST_FLAG(value,bit) ((value)&FLAG(bit)) +#define VALID_INDEX(index,count) ((index)>=0 && (index)<(count)) +#define NUMBER_OF_BITMAP_FLAGS 9 +#define NUMBER_OF_BITMAP_TYPES 3 +#define NUMBER_OF_BITMAP_FORMATS 18 +#define BITMAP_GROUP_TAG 0x6269746du +#define _bitmap_format_a8r8g8b8 11 +#define _bitmap_has_power_of_two_dimensions_bit 0 +#define _bitmap_compressed_bit 1 +#define _bitmap_palettized_bit 2 +#define _bitmap_swizzled_bit 3 +#define _bitmap_linear_bit 4 +#define _error_silent 0 +#define error(...) ((void)0) +#define match_assert(file,line,condition) do {if(!(condition))abort();} while(0) +#define MCC_BITMAP_BASE 0x60000000u +#define MCC_BITMAP_LIMIT 0x1FFFFFFFu +#define MCC_BITMAP_ALLOCATION_LIMIT 0x08000000u +typedef unsigned char boolean; +struct bitmap_data { + uint32_t signature; + short width,height,depth,type,format; + unsigned short flags; + short mipmap_count; + int32_t pixels_offset,pixels_size,tag_index,cache_block_index; + void *hardware_format,*base_address; +}; +struct tag_block {long count;void *address;}; +struct bitmap_group_sprite {unsigned char data[32];}; +struct bitmap_group_sequence {short first_bitmap_index,bitmap_count;struct tag_block sprites;}; +struct bitmap_group {short usage;struct {long file_offset;} import_bitmap,pixel_data;struct tag_block bitmaps,sequences;}; +struct mcc_runtime { + struct bitmap_group group; + unsigned char source[350000]; + uint32_t size,reads,read_fail_at,resource_reads; + unsigned char *tag_index,*tags; + uint32_t used; + struct {uint32_t tag_count,bitmap_count;} report; + void *bitmaps; +}; +static void *mcc_runtime_pointer(struct mcc_runtime *r,uint32_t address,uint32_t size) { + uintptr_t start=(uintptr_t)r->tags; + if(address==(uintptr_t)&r->group && size<=sizeof(r->group))return &r->group; + return r->tags && address>=start && address-start<=r->used && size<=r->used-(address-start) ? + (void *)(uintptr_t)address : NULL; +} +static void *mcc_runtime_allocate(struct mcc_runtime *r,uint32_t size) { + uint32_t at=(r->used+15)&~15u; + if(size>65536-at)return NULL; + r->used=at+size;return r->tags+at; +} +static int mcc_resources_read(struct mcc_runtime *r,unsigned type,char const *name,uint32_t offset,uint32_t bytes,void *out,char const *group) { + (void)type;(void)name;(void)offset;(void)bytes;(void)out;(void)group; + r->resource_reads++;return 0; +} +static short floor_log2(unsigned value) {short n=0;while(value>1){value>>=1;n++;}return n;} +static int bitmap_format_type_valid_width(short f,short t,short v) {(void)f;(void)t;return v>0 && v<=30000;} +static int bitmap_format_type_valid_height(short f,short t,short v) {return bitmap_format_type_valid_width(f,t,v);} +static int bitmap_format_type_valid_depth(short f,short t,short v) {(void)f;(void)t;return v==1;} +static int mcc_runtime_read(struct mcc_runtime *r,uint32_t offset,uint32_t size,void *out) { + r->reads++; + if(r->reads==r->read_fail_at || offset>r->size || size>r->size-offset)return 0; + memcpy(out,r->source+offset,size);return 1; +} +static int test_hardware_calls,test_hardware_fail_at; +static long rasterizer_xbox_bitmap_get_pixel_data_size(struct bitmap_data *b) { + uint32_t bytes=0;unsigned level; + if(++test_hardware_calls==test_hardware_fail_at)return 64; + if(b->flags&16)return (((b->width*(b->format==11 ? 4 : 2)+63)&~63u)*b->height+127u)&~127u; + for(level=0;level<=(unsigned)b->mipmap_count;level++) { + unsigned w=MAX(b->width>>level,1),h=MAX(b->height>>level,1); + bytes+=b->format==14 ? ((w+3)/4)*((h+3)/4)*8 : w*h*(b->format==11 ? 4 : 2); + } + return (bytes+127u)&~127u; +} +static uint32_t global_vector_palette[256]; +#define BCDEC_STATIC +#define BCDEC_IMPLEMENTATION +#include "bcdec.h" +static int test_allocations,test_fail_at,test_live; +static void *test_bitmap_malloc(size_t n) { + void *p; + if (++test_allocations==test_fail_at) return NULL; + p=malloc(n);if(p)test_live++;return p; +} +static void test_bitmap_free(void *p) {if(!p)abort();test_live--;free(p);} +#define malloc test_bitmap_malloc +#define free test_bitmap_free +''' + source += "\n" + next(line for line in bitmap.splitlines() if line.startswith("#define MCC_BITMAP_STORAGE_LIMIT ")) + source += "\n" + structure(bitmap, "mcc_texture") + source += "\n" + structure(bitmap, "mcc_bitmap_clone") + source += "\n" + structure(bitmap, "mcc_textures") + source += "\n" + "\n".join(function(bitmap, name) for name in [ + "mcc_bitmap_tag", "mcc_bitmap_block", "mcc_bitmap_clone_block", "mcc_bitmap_specialize"]) + source += r''' +static int test_reverse,test_empty; +/* Consumer selection is outside this test. Actual clone construction must + * append complete groups, and reuse must leave the constructed array alone. */ +static int mcc_bitmap_usages(struct mcc_runtime *r,struct mcc_textures *t) { + uint32_t a=0xE1110001u,b=0xE2220003u,empty=0xE3330000u,repeated=a; + uint32_t count,tags,target; + assert(t->count==(test_empty ? 0u : 5u)); + if(!test_empty) { + assert(t->items[0].handle==a && t->items[1].handle==a && t->items[2].handle==a); + assert(t->items[3].handle==b && t->items[4].handle==b); + } + if(test_reverse) { + if(!mcc_bitmap_specialize(r,t,&b,4) || !mcc_bitmap_specialize(r,t,&a,2))return 0; + } else if(!mcc_bitmap_specialize(r,t,&a,2) || !mcc_bitmap_specialize(r,t,&b,4))return 0; + assert(a!=repeated && b!=0xE2220003u && a!=b); + count=t->count;tags=r->report.tag_count;target=a; + if(!mcc_bitmap_specialize(r,t,&repeated,2))return 0; + assert(repeated==target && t->count==count && r->report.tag_count==tags); + if(!mcc_bitmap_specialize(r,t,&empty,2))return 0; + assert(t->count==count && r->report.tag_count==tags+1); + assert(t->clone_count==3 && t->count==(test_empty ? 0u : 10u)); + return 1; +} +''' + source += "\n" + function(native, "bitmap_verify") + source += "\n" + function(swizzle, "rasterizer_xbox_bitmap_get_max_mipmap_count") + source += "\n" + "\n".join(function(bitmap, name) for name in [ + "mcc_bitmap_bytes", "mcc_pixel", "mcc_channels", "mcc_bitmap_decode", + "mcc_morton_axis", "mcc_bitmap_pack", "mcc_bitmap_lightmap_flags", "mcc_bitmap_complete_mips", + "mcc_texture_prepare", "mcc_bitmaps_prepare", "mcc_bitmaps_read", + "mcc_bitmap_valid_texture", "mcc_bitmaps_valid", "mcc_bitmaps_group_valid", "mcc_bitmaps_dispose"]) + source += r''' +#undef malloc +#undef free +static int test_construction(char const *mode) { + static short const widths[5]={4,16,4,8,4},heights[5]={2,8,2,8,4}; + struct mcc_runtime r={0}; + struct bitmap_data originals[5],*descriptors[5]; + struct mcc_textures *t; + uint32_t index,n,k=0,input=0,successful=0,used=0,stream_end=0; + unsigned char out[512]; + int expected=!strcmp(mode,"construct") || !strcmp(mode,"construct-reverse") || !strcmp(mode,"construct-empty"); + test_reverse=!strcmp(mode,"construct-reverse");test_empty=!strcmp(mode,"construct-empty"); + r.tags=calloc(1,65536);assert(r.tags); + r.report.tag_count=4;r.report.bitmap_count=test_empty ? 0 : 5; + r.tag_index=mcc_runtime_allocate(&r,4*32);r.size=4096; + for(index=0;indexbitmaps.count=count;group->bitmaps.address=bitmaps; + for(n=0;nsignature=BITMAP_GROUP_TAG;b->width=widths[k];b->height=heights[k];b->depth=1; + b->format=6;b->flags=0x81;b->pixels_offset=input;b->pixels_size=b->width*b->height*2; + b->tag_index=entry[3];input+=b->pixels_size; + if(!strcmp(mode,"construct-resource") && k==2)b->flags|=0x100; + memcpy(&originals[k],b,sizeof(*b));descriptors[k]=b; + } + } + if(!strcmp(mode,"construct-read"))r.read_fail_at=3; + if(!strcmp(mode,"construct-pack"))test_hardware_fail_at=3; + if(!strcmp(mode,"construct-allocation"))test_fail_at=8; + assert(mcc_bitmaps_prepare(&r)==expected); + t=r.bitmaps;assert(t && t->count==(test_empty ? 0u : 10u)); + for(index=0;indexcount;index++) { + struct mcc_texture const *item=&t->items[index]; + uint32_t original=(item->resource_handle==0xE1110001u ? 0 : 3)+item->resource_index; + uint32_t offset,size,hash=2166136261u; + if(item->handle==item->resource_handle)assert(item->bitmap==descriptors[original]); + else assert(item->bitmap!=descriptors[original]); + /* Each complete runtime-handle run occurs once, even though clones + * retain their original resource handle for external resource reads. */ + if(index && item->handle!=t->items[index-1].handle) + for(n=0;nitems[n].handle!=item->handle); + if(!item->pixels) { + assert(!memcmp(item->bitmap,&originals[original],sizeof(originals[original]))); + assert(!item->offset && !item->size);continue; + } + successful++; + if(item->resource_handle==0xE1110001u) + offset=item->resource_index==0 ? 0 : item->resource_index==1 ? 128 : item->channels ? 640 : 384; + else offset=item->resource_index==0 ? 0 : item->channels ? 256 : 128; + size=(widths[original]*heights[original]*(item->channels ? 4 : 2)+127u)&~127u; + assert(item->offset==MCC_BITMAP_BASE+offset && item->size==size); + assert(item->bitmap->pixels_offset==(int32_t)item->offset && item->bitmap->pixels_size==(int32_t)size); + assert((uint32_t)item->bitmap->tag_index==item->handle && !item->bitmap->base_address && !item->bitmap->hardware_format); + assert(mcc_bitmaps_read(&r,item->handle,item->offset,size,out)==1 && !memcmp(out,item->pixels,size)); + assert(mcc_bitmaps_read(&r,0xE999000Fu,item->offset,1,out)==0); + for(n=0;npixels[n])*16777619u; + printf("%08x %08x %u %u %u %u %u %u %08x\n",item->handle,item->resource_handle, + item->resource_index,item->channels,item->bitmap->flags,item->bitmap->format,item->offset,size,hash); + used+=size;stream_end=MAX(stream_end,offset+size); + } + assert(successful==(test_empty ? 0u : expected ? 10u : 2u)); + assert(t->end==used && t->stream_end==stream_end); + assert(t->end==(test_empty ? 0u : expected ? 1920u : 384u)); + assert(t->stream_end==(test_empty ? 0u : expected ? 768u : 384u)); + assert(r.resource_reads==(!strcmp(mode,"construct-resource") ? 1u : 0u)); + assert(r.reads==(test_empty ? 0u : expected ? 10u : + !strcmp(mode,"construct-read") || !strcmp(mode,"construct-pack") ? 3u : 2u)); + printf("end %u %u reads %u resources %u\n",t->end,t->stream_end,r.reads,r.resource_reads); + mcc_bitmaps_dispose(&r);assert(!r.bitmaps && !test_live); + free(r.tags);return 0; +} +int main(int argc,char **argv) { + struct bitmap_data bitmap={0},original; + struct mcc_textures textures={0}; + struct mcc_texture texture={0}; + struct mcc_runtime runtime={0}; + uint32_t tag_index[8*8]={0}; + unsigned i;int expect=1,converted,tail=0; + static unsigned const order[8]={0,1,4,5,2,3,6,7}; + if(argc!=2)return 2; + if(!strncmp(argv[1],"construct",9))return test_construction(argv[1]); + runtime.group.usage=4;runtime.size=16; + runtime.tag_index=(unsigned char *)tag_index;runtime.report.tag_count=8; + tag_index[7*8]=BITMAP_GROUP_TAG;tag_index[7*8+3]=7;tag_index[7*8+5]=(uint32_t)&runtime.group; + bitmap.signature=BITMAP_GROUP_TAG;bitmap.width=4;bitmap.height=2;bitmap.depth=1; + bitmap.format=6;bitmap.flags=0x1281;bitmap.pixels_size=16; + texture.bitmap=&bitmap;texture.handle=7; + for(i=0;i<16;i++)runtime.source[i]=(unsigned char)i; + if(!strncmp(argv[1],"stream-",7)) { + uint32_t stream_offset=!strcmp(argv[1],"stream-last") ? MCC_BITMAP_LIMIT-255 : + !strcmp(argv[1],"stream-full") ? MCC_BITMAP_LIMIT-127 : + !strcmp(argv[1],"stream-limit") ? MCC_BITMAP_LIMIT : UINT32_MAX; + int accept=!strcmp(argv[1],"stream-last"); + textures.end=128;textures.stream_end=stream_offset; + memcpy(&original,&bitmap,sizeof(original)); + converted=mcc_texture_prepare(&runtime,&textures,&texture,stream_offset); + assert(converted==accept); + if(accept) { + assert(texture.offset==MCC_BITMAP_BASE+stream_offset && texture.size==128); + assert(textures.end==256 && textures.stream_end==stream_offset+128 && runtime.reads==1); + } else { + assert(!runtime.reads && !test_allocations && !texture.pixels && !texture.offset && !texture.size); + assert(!memcmp(&bitmap,&original,sizeof(original)) && textures.end==128 && textures.stream_end==stream_offset); + } + free(texture.pixels);return 0; + } + if(!strncmp(argv[1],"group-",6)) { + struct bitmap_group_sequence sequence={0}; + sequence.bitmap_count=1; + if(!mcc_texture_prepare(&runtime,&textures,&texture,0))return 31; + textures.count=1;textures.items=&texture;runtime.bitmaps=&textures; + runtime.group.bitmaps.count=1;runtime.group.bitmaps.address=&bitmap; + runtime.group.sequences.count=1;runtime.group.sequences.address=&sequence; + if(!strcmp(argv[1],"group-large")) { + bitmap.width=bitmap.height=4096;bitmap.pixels_size=texture.size=89478528; + } + if(!strcmp(argv[1],"group-unowned")) {texture.bitmap=NULL;expect=0;} + if(!strcmp(argv[1],"group-offset")) {runtime.group.pixel_data.file_offset=1;expect=0;} + if(!strcmp(argv[1],"group-sequence")) sequence.bitmap_count=2; + if(mcc_bitmaps_group_valid(&runtime,&runtime.group)!=expect)return 32; + if(!strcmp(argv[1],"group-sequence") && sequence.bitmap_count)return 33; + free(texture.pixels);return 0; + } + if(!strncmp(argv[1],"allocation-",11)) { + test_fail_at=atoi(argv[1]+11);texture.channels=2; + if(mcc_texture_prepare(&runtime,&textures,&texture,0) || test_live || texture.pixels || textures.end)return 30; + return 0; + } + if(!strncmp(argv[1],"storage-",8)) { + int accept=!strcmp(argv[1],"storage-large"); + textures.end=accept ? 0x40000000u : !strcmp(argv[1],"storage-full") ? MCC_BITMAP_STORAGE_LIMIT-64 : 0xffffffffu; + converted=mcc_texture_prepare(&runtime,&textures,&texture,0); + if(converted!=accept || (!accept && runtime.reads))return 28; + if(accept && (textures.end!=0x40000080u || memcmp(texture.pixels,runtime.source,4)))return 29; + free(texture.pixels);return 0; + } + if(!strcmp(argv[1],"swizzle8192")) { + bitmap.width=8192;bitmap.height=2;bitmap.format=6;bitmap.flags=0x81; + bitmap.pixels_size=32768;runtime.size=32768;runtime.group.usage=0; + for(i=0;i<16384;i++) {runtime.source[i*2]=(unsigned char)i;runtime.source[i*2+1]=(unsigned char)(i>>8);} + if(!mcc_texture_prepare(&runtime,&textures,&texture,0) || bitmap.pixels_size!=32768)return 26; + if(memcmp(texture.pixels+4,runtime.source+16384,2) || + memcmp(texture.pixels+16384,runtime.source+8192,2) || + memcmp(texture.pixels+32766,runtime.source+32766,2))return 27; + free(texture.pixels);return 0; + } + if(!strncmp(argv[1],"wide",4)) { + bitmap.width=15360;bitmap.height=4;bitmap.format=14;bitmap.flags=0x83; + bitmap.pixels_size=30720;runtime.size=30720;runtime.group.usage=1; + if(!strcmp(argv[1],"wide-short")) {bitmap.pixels_size--;return mcc_texture_prepare(&runtime,&textures,&texture,0)?24:0;} + if(!strcmp(argv[1],"wide-limit")) {bitmap.width=16385;return mcc_texture_prepare(&runtime,&textures,&texture,0)?25:0;} + if(!mcc_texture_prepare(&runtime,&textures,&texture,0) || bitmap.format!=11 || + !(bitmap.flags&16) || bitmap.width!=15360 || bitmap.pixels_size!=245760)return 22; + if(texture.pixels[245759]!=255)return 23; + free(texture.pixels);return 0; + } + if(!strcmp(argv[1],"tag-streams")) { + struct mcc_texture items[3]={{0}}; + struct bitmap_data bitmaps[3];unsigned char out[16]; + bitmap.flags=0x81;textures.end=0x20000000u; + textures.items=items;textures.count=3;runtime.bitmaps=&textures; + for(i=0;i<3;i++) { + bitmaps[i]=bitmap;items[i].bitmap=&bitmaps[i];items[i].handle=i==2 ? 8 : 7; + if(!mcc_texture_prepare(&runtime,&textures,&items[i],i==1 ? 128 : 0))return 12; + } + if(items[0].offset!=MCC_BITMAP_BASE || items[1].offset!=MCC_BITMAP_BASE+128 || + items[2].offset!=MCC_BITMAP_BASE || textures.end!=0x20000180u)return 13; + if(mcc_bitmaps_read(&runtime,7,MCC_BITMAP_BASE+128,16,out)!=1 || + mcc_bitmaps_read(&runtime,8,MCC_BITMAP_BASE,16,out)!=1 || + mcc_bitmaps_read(&runtime,8,MCC_BITMAP_BASE+128,1,out)!=0 || + mcc_bitmaps_read(&runtime,9,MCC_BITMAP_BASE,1,out)!=0)return 14; + for(i=0;i<3;i++)free(items[i].pixels); + return 0; + } + if(!strncmp(argv[1],"tail",4)) { + tail=1;runtime.group.usage=0;runtime.size=349525; + bitmap.width=1024;bitmap.height=512;bitmap.format=14;bitmap.flags=0x81; + bitmap.mipmap_count=10;bitmap.pixels_size=349525; + for(i=0;i +#include +#include +int mcc_tags_prepare(struct mcc_runtime *); +void error(int level,char const *format,...) {(void)level;(void)format;} +int mcc_recording_prepare(unsigned char *p,uint32_t s,unsigned char v,unsigned char c,uint32_t *n) { + (void)p;(void)s;(void)v;(void)c;(void)n;abort();return 0; +} +int mcc_recording_weapon_only(unsigned char const *p,uint32_t s,unsigned char v,unsigned char c) { + (void)p;(void)s;(void)v;(void)c;abort();return 0; +} +void *mcc_runtime_pointer(struct mcc_runtime *r,uint32_t address,uint32_t size) { + uint32_t offset=address-r->report.tag_base; + return address>=r->report.tag_base && offset<=r->used && size<=r->used-offset ? r->tags+offset : NULL; +} +int main(int argc,char **argv) { + unsigned char data[4096];struct mcc_runtime r={0};FILE *f;int ok; + if(argc!=3)return 2; + f=fopen(argv[1],"rb");if(!f)return 3; + r.used=(uint32_t)fread(data,1,sizeof(data),f);fclose(f); + r.tags=r.tag_index=data;r.report.tag_base=0x50000000;r.report.tag_count=1; + ok=mcc_tags_prepare(&r); + f=fopen(argv[2],"wb");if(!f)return 4;fwrite(data,1,r.used,f);fclose(f); + printf("%d\n",ok);return 0; +} +''') + binary = work / ("camera.exe" if sys.platform == "win32" else "camera") + game = ROOT / "port/linux/game" + command = [compiler, "-std=gnu89", "-Wall", "-Wextra", "-Werror", "-Wno-multichar", + "-I" + str(work), "-I" + str(game), str(source), str(game / "mcc_tags.c"), "-o", str(binary)] + if sys.platform == "win32": + command[1:1] = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld", "-D_CRT_SECURE_NO_WARNINGS"] + result = subprocess.run(command, capture_output=True, text=True) + assert result.returncode == 0, result.stderr + return binary + + +def fixture(angles): + data = bytearray(0x600 + len(angles) * 0x68) + struct.pack_into(" +#include +typedef int boolean; +enum { D3DRS_DESTBLEND, D3DBLEND_ONE=1, + _framebuffer_blend_function_double_multiply=2, + NUMBER_OF_SHADER_TRANSPARENT_MAPS=4 }; +#define PIN(x,a,b) ((x)<(a)?(a):((x)>(b)?(b):(x))) +struct shader_transparent_chicago { + unsigned short extra_flags;short framebuffer_blend_function; + struct {int count;} maps; +}; +struct pixel_shader_definition {unsigned int rgb_inputs[8];}; +static int loaded, writes, destination; +static int mcc_cache_tags_loaded(void) {return loaded;} +static void SetRenderStateSmart(int state,int value) { + (void)state;writes++;destination=value; +} +#define CHECK(x) do {if (!(x)) {fprintf(stderr,"line %d: %s\n",__LINE__,#x);return 1;}} while (0) +''' + adapter + r''' +int main(void) { + struct shader_transparent_chicago shader={4,2,{4}}; + struct pixel_shader_definition original={{1,2,3,4,0x0C14A034}},pixel; + int mode,flag; + /* A reserved bit in Xbox/CE is not an opt-in. */ + pixel=original;mcc_chicago_blend(&shader,&pixel,1); + CHECK(!writes && !memcmp(&pixel,&original,sizeof(pixel))); + loaded=1; + for(mode=0;mode<8;mode++) for(flag=0;flag<8;flag++) { + shader.framebuffer_blend_function=mode;shader.extra_flags=flag; + pixel=original;writes=0;mcc_chicago_blend(&shader,&pixel,1); + if(mode==2 && (flag&4)) { + CHECK(writes==1 && destination==D3DBLEND_ONE); + CHECK(pixel.rgb_inputs[4]==0x0C140000); + CHECK(!memcmp(pixel.rgb_inputs,original.rgb_inputs,4*sizeof(unsigned int))); + } else CHECK(!writes && !memcmp(&pixel,&original,sizeof(pixel))); + } + shader.framebuffer_blend_function=2;shader.extra_flags=4; + pixel=original;writes=0;mcc_chicago_blend(&shader,&pixel,0); + CHECK(writes==1 && !memcmp(&pixel,&original,sizeof(pixel))); + /* Unloading MCC does not leave adapter state behind. */ + loaded=0;writes=0;pixel=original;mcc_chicago_blend(&shader,&pixel,1); + CHECK(!writes && !memcmp(&pixel,&original,sizeof(pixel))); + return 0; +} +''' + path = tmp_path / "chicago.c" + path.write_text(code) + binary = tmp_path / ("chicago.exe" if os.name == "nt" else "chicago") + target = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld"] if os.name == "nt" else [] + result = subprocess.run([compiler, *target, "-std=gnu89", str(path), "-o", str(binary)], + capture_output=True, text=True) + assert result.returncode == 0, result.stderr + result = subprocess.run([str(binary)], capture_output=True, text=True) + assert result.returncode == 0, result.stderr diff --git a/tools/test_mcc_ci.py b/tools/test_mcc_ci.py new file mode 100644 index 0000000000..89b6534818 --- /dev/null +++ b/tools/test_mcc_ci.py @@ -0,0 +1,81 @@ +"""Keep MCC checks executable in CI, including scripts pytest cannot collect.""" +import ast +from pathlib import Path +import re + +import pytest +import yaml + +ROOT = Path(__file__).resolve().parents[1] + + +def ci_commands(): + for path in (ROOT / ".github/workflows").glob("*.yml"): + workflow = yaml.safe_load(path.read_text(encoding="utf-8")) + for job in workflow.get("jobs", {}).values(): + for step in job.get("steps", []): + if "run" in step and not step.get("continue-on-error"): + yield step["run"].replace("\\\n", " ") + + +def pytest_inputs(commands): + for command in commands: + for args in re.findall(r"\bpython3?\s+-m\s+pytest\b([^\n]*)", command): + yield from re.findall(r"\btools/[\w./-]+", args) + + +def has_pytest_tests(path): + tree = ast.parse(path.read_text(encoding="utf-8")) + return any(isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and + node.name.startswith("test_") for node in ast.walk(tree)) + + +@pytest.fixture(scope="module") +def commands(): + return list(ci_commands()) + + +@pytest.mark.parametrize("path", sorted((ROOT / "tools").rglob("test_*mcc*.py")), + ids=lambda path: path.relative_to(ROOT).as_posix()) +def test_mcc_check_has_ci_runner(path, commands): + relative = path.relative_to(ROOT).as_posix() + if has_pytest_tests(path): + # Passing a directory to pytest covers its discovered harness tests. + assert any(relative == entry or relative.startswith(entry.rstrip("/") + "/") + for entry in pytest_inputs(commands)), relative + else: + # A standalone main() in a pytest argument list executes no checks. + direct = r"\bpython3?\s+" + re.escape(relative) + r"(?:\s|$)" + assert any(re.search(direct, command) for command in commands), relative + + +def test_standalone_meter_is_not_pytest_coverage(): + path = ROOT / "tools/test_mcc_hud_meter_render.py" + assert not has_pytest_tests(path) + assert list(pytest_inputs(["python3 tools/test_mcc_hud_meter_render.py"])) == [] + + +def test_native_windows_reservation_checks_run_on_windows(): + workflow = yaml.safe_load((ROOT / ".github/workflows/mcc.yml").read_text(encoding="utf-8")) + job = workflow["jobs"]["windows-adapters"] + assert job["runs-on"].startswith("windows-") + inputs = set(pytest_inputs(step.get("run", "") for step in job["steps"])) + assert {"tools/test_mcc_memory.py", "tools/test_windows_mcc_startup.py"} <= inputs + + +@pytest.mark.parametrize("job_name", ["reader-and-validator", "windows-adapters"]) +def test_sharing_storage_and_metadata_run_on_both_native_platforms(job_name): + workflow = yaml.safe_load((ROOT / ".github/workflows/mcc.yml").read_text(encoding="utf-8")) + inputs = set(pytest_inputs(step.get("run", "") for step in workflow["jobs"][job_name]["steps"])) + assert {"tools/test_mcc_share.py", "tools/test_mcc_share_stage.py", + "tools/test_mcc_share_metadata.py", "tools/test_mcc_share_storage.py", + "tools/test_mcc_share_menu.py", "tools/test_mcc_admission.py"} <= inputs + + +@pytest.mark.parametrize("module", ["metadata", "storage"]) +def test_sharing_metadata_has_linux_sanitizer_runner(module): + workflow = yaml.safe_load((ROOT / ".github/workflows/mcc.yml").read_text(encoding="utf-8")) + steps = workflow["jobs"]["reader-and-validator"]["steps"] + assert any(step.get("env", {}).get(f"MCC_SHARE_{module.upper()}_SANITIZE") == "1" and + f"tools/test_mcc_share_{module}.py" in set(pytest_inputs([step.get("run", "")])) + for step in steps) diff --git a/tools/test_mcc_damage_tags.py b/tools/test_mcc_damage_tags.py new file mode 100644 index 0000000000..6b65a5a26e --- /dev/null +++ b/tools/test_mcc_damage_tags.py @@ -0,0 +1,29 @@ +"""The real metadata reader rejects non-finite MCC extension acceleration.""" +import struct +import pytest +from tools.test_mcc_cameras import camera_tool, convert + + +@pytest.mark.parametrize("flags,values,accepted", [ + (0x30000, (0, -0.1, 2.45), 1), + (0x10000, (-1, -1, 0), 1), + (0x20000, (-1, float("nan"), float("inf")), 1), + (0x30000, (0, float("nan"), 2), 0), + (0x30000, (0, 0, float("inf")), 0), + (0x20000, (float("-inf"), 0, 0), 0), + (0, (1, float("nan"), float("inf")), 1), +]) +def test_mcc_damage_components(camera_tool, tmp_path, flags, values, accepted): + data = bytearray(0x2C0) + struct.pack_into(" +#include +#include +typedef unsigned int DWORD; +typedef int BOOL; +#define FALSE 0 +#define TRUE 1 +enum { D3DRS_PSCOMBINERCOUNT, D3DRS_PSALPHAINPUTS0=8, D3DRS_PSRGBINPUTS0=16, + D3DRS_PSALPHAOUTPUTS0=24, D3DRS_PSRGBOUTPUTS0=32 }; +struct xgpu_text {char data[16000];}; +static void xgpu_text_append(struct xgpu_text *t,const char *format,...) { + va_list args;size_t n=strlen(t->data);va_start(args,format); + vsnprintf(t->data+n,sizeof(t->data)-n,format,args);va_end(args); +} +''' + emit + prefix + r''' +#define CHECK(x) do {if (!(x)) {fprintf(stderr,"%d: %s\n",__LINE__,#x);return 1;}} while (0) +int main(void) { + DWORD state[64]={0};struct xgpu_text legacy={{0}},mcc={{0}},other={{0}}; + state[D3DRS_PSRGBINPUTS0]=0x484B0A01;state[D3DRS_PSRGBOUTPUTS0]=0x2000; + combiner_stage(&legacy,state,0,FALSE);combiner_stage(&mcc,state,0,TRUE); + CHECK(strstr(legacy.data,"vec3 cAB = vec3(dot(cA, cB));")); + CHECK(!strstr(legacy.data,"cB.z"));CHECK(strstr(mcc.data,"1.0 + dot(cA, cB) - cB.z")); + CHECK(strstr(mcc.data,"vec3 cA = (2.0 * max(t0.rgb, 0.0) - 1.0)")); + CHECK(strstr(mcc.data,"vec3 cB = (2.0 * max(t3.rgb, 0.0) - 1.0)")); + CHECK(strstr(mcc.data,"float aAB = aA * aB;")); + state[D3DRS_PSRGBINPUTS0]=0x484A0A01; + legacy.data[0]=0;combiner_stage(&legacy,state,0,FALSE);combiner_stage(&other,state,0,TRUE); + CHECK(!strcmp(legacy.data,other.data)); + state[D3DRS_PSRGBOUTPUTS0]=0;legacy.data[0]=other.data[0]=0; + combiner_stage(&legacy,state,0,FALSE);combiner_stage(&other,state,0,TRUE); + CHECK(!strcmp(legacy.data,other.data)); + return 0; +} +''' + path = tmp_path / "shader.c" + path.write_text(code) + binary = tmp_path / ("shader.exe" if os.name == "nt" else "shader") + target = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld", "-D_CRT_SECURE_NO_WARNINGS"] if os.name == "nt" else [] + result = subprocess.run([compiler, *target, "-std=gnu89", str(path), "-o", str(binary)], + capture_output=True, text=True) + assert result.returncode == 0, result.stderr + result = subprocess.run([str(binary)], capture_output=True, text=True) + assert result.returncode == 0, result.stderr diff --git a/tools/test_mcc_grenades.py b/tools/test_mcc_grenades.py new file mode 100644 index 0000000000..fff80d9ca9 --- /dev/null +++ b/tools/test_mcc_grenades.py @@ -0,0 +1,123 @@ +"""Execute the MCC-only inventory and snapshot routines with salted fake units. + +The native two-byte inventory has guard bytes, so additional slots cannot +silently extend its layout. No game data or CE code participates. +""" +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from harness import function, structure + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.fixture(scope="session") +def grenade_tool(tmp_path_factory): + clang = shutil.which("clang") + if not clang: + pytest.skip("clang is required for MCC inventory tests") + work = tmp_path_factory.mktemp("mcc-grenades") + implementation = (ROOT / "port/linux/game/mcc_grenades.c").read_text() + names = ["mcc_grenades_active", "mcc_grenades_type_count", "mcc_grenade_definition", + "mcc_grenade_inventory", "mcc_grenades_reset", "mcc_grenades_clear", "mcc_grenades_get", + "mcc_grenades_set", "mcc_grenades_total", "mcc_grenades_next", "mcc_grenades_add", + "mcc_grenade_u32", "mcc_grenades_snapshot", "mcc_grenades_snapshot_validate", "mcc_grenades_restore"] + source = r''' +#include +#include +#include +typedef int boolean; +#define NONE -1 +#define MAXIMUM_OBJECTS_PER_MAP 8 +#define MAXIMUM_NUMBER_OF_LOCAL_PLAYERS 4 +#define NUMBEROF(a) (sizeof(a)/sizeof(*(a))) +#define MIN(a,b) ((a)<(b)?(a):(b)) +#define MAX(a,b) ((a)>(b)?(a):(b)) +#define PIN(x,a,b) ((x)<(a)?(a):((x)>(b)?(b):(x))) +struct unit_datum {struct {signed char grenade_counts[2];unsigned char guards[2];char current_grenade_index,desired_grenade_index;} unit;}; +struct game_globals_grenade {short maximum_count;}; +struct game_globals {struct {long count;void *address;} grenades;}; +static struct unit_datum units[8]; +static long handles[8]; +static int active=1; +static struct game_globals_grenade definitions[4]; +static struct game_globals globals={ {4,definitions} }; +static boolean mcc_cache_tags_loaded(void){return active;} +static struct game_globals *scenario_get_game_globals(void){return &globals;} +static struct unit_datum *unit_try_and_get(long handle){ + unsigned i=(unsigned long)handle&65535; + return handle!=NONE && i<8 && handles[i]==handle ? &units[i] : NULL; +} +''' + structure(implementation, "mcc_grenade_inventory") + r''' +static struct mcc_grenade_inventory mcc_grenade_inventories[MAXIMUM_OBJECTS_PER_MAP]; +static long mcc_grenade_flash_time[MAXIMUM_NUMBER_OF_LOCAL_PLAYERS]; +''' + '\n'.join(function(implementation, n) for n in names) + r''' +int main(int argc,char **argv){ + long unit=0x12340001;unsigned char snapshot[72],bad[72];uint32_t bytes;unsigned i; + if(argc!=2)return 99; + for(i=0;i<8;i++)handles[i]=NONE; + handles[1]=unit;units[1].unit.guards[0]=0xAA;units[1].unit.guards[1]=0x55; + mcc_grenades_reset(); + mcc_grenades_set(unit,0,2);mcc_grenades_set(unit,1,3);mcc_grenades_set(unit,2,4);mcc_grenades_set(unit,3,5); + if(!strcmp(argv[1],"inventory")){ + if(mcc_grenades_total(unit)!=14 || mcc_grenades_get(unit,2)!=4 || mcc_grenades_get(unit,3)!=5)return 1; + if(units[1].unit.guards[0]!=0xAA || units[1].unit.guards[1]!=0x55)return 2; + if(mcc_grenades_next(unit,1,1)!=2 || mcc_grenades_next(unit,0,-1)!=3 || mcc_grenades_next(unit,2,0)!=2)return 3; + mcc_grenades_set(unit,2,0); + if(mcc_grenades_next(unit,1,1)!=3)return 4; + if(mcc_grenades_add(unit,2,7)!=7 || units[1].unit.current_grenade_index!=2)return 5; + mcc_grenades_set(unit,2,300);mcc_grenades_set(unit,3,-3); + if(mcc_grenades_get(unit,2)!=127 || mcc_grenades_get(unit,3)!=0)return 6; + mcc_grenades_clear(unit); + if(mcc_grenades_get(unit,2) || mcc_grenades_total(unit)!=5)return 7; + active=0;mcc_grenades_set(unit,0,99); + if(mcc_grenades_get(unit,0) || units[1].unit.grenade_counts[0]!=2)return 8; + return 0; + } + bytes=mcc_grenades_snapshot(snapshot,sizeof(snapshot)); + if(bytes!=16 || mcc_grenades_snapshot(NULL,0)!=bytes || mcc_grenades_snapshot(bad,15))return 9; + if(memcmp(snapshot,"GMC4\1\0\1\0\1\0\x34\x12\4\5\0\0",16))return 10; + if(!strcmp(argv[1],"roundtrip")){ + mcc_grenades_clear(unit); + if(!mcc_grenades_restore(snapshot,bytes) || mcc_grenades_get(unit,2)!=4 || mcc_grenades_get(unit,3)!=5)return 11; + if(units[1].unit.grenade_counts[0]!=2 || units[1].unit.guards[0]!=0xAA)return 12; + handles[1]=0x23450001; + if(mcc_grenades_get(handles[1],2) || mcc_grenades_restore(snapshot,bytes))return 13; + mcc_grenades_set(handles[1],2,9); + if(mcc_grenades_get(handles[1],2)!=9 || mcc_grenades_get(unit,2))return 14; + return 0; + } + if(!strcmp(argv[1],"invalid")){ + for(i=0;i<16;i++)if(mcc_grenades_snapshot_validate(snapshot,i))return 15; + memcpy(bad,snapshot,16);bad[4]=2;if(mcc_grenades_snapshot_validate(bad,16))return 16; + memcpy(bad,snapshot,16);bad[12]=128;if(mcc_grenades_snapshot_validate(bad,16))return 17; + memcpy(bad,snapshot,16);bad[14]=1;if(mcc_grenades_snapshot_validate(bad,16))return 18; + memcpy(bad,snapshot,16);bad[8]=8;if(mcc_grenades_snapshot_validate(bad,16))return 19; + memcpy(bad,snapshot,16);bad[6]=2;memcpy(bad+16,snapshot+8,8); + if(mcc_grenades_snapshot_validate(bad,24) || mcc_grenades_restore(bad,24))return 20; + if(mcc_grenades_get(unit,2)!=4 || mcc_grenades_get(unit,3)!=5)return 21; + return 0; + } + return 98; +} +''' + path = work / "grenades.c" + path.write_text(source) + output = work / ("grenades.exe" if sys.platform == "win32" else "grenades") + command = [clang, "-std=gnu99", "-O2", "-Wall", "-Wextra", "-Werror", str(path), "-o", str(output)] + if sys.platform == "win32": + command[1:1] = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld", "-D_CRT_SECURE_NO_WARNINGS"] + result = subprocess.run(command, capture_output=True, text=True) + assert result.returncode == 0, result.stderr + return output + + +@pytest.mark.parametrize("case", ["inventory", "roundtrip", "invalid"]) +def test_mcc_inventory_and_snapshots(grenade_tool, case): + result = subprocess.run([str(grenade_tool), case], capture_output=True, text=True) + assert result.returncode == 0, (case, result.returncode, result.stdout, result.stderr) diff --git a/tools/test_mcc_hud.py b/tools/test_mcc_hud.py new file mode 100644 index 0000000000..dcc961353e --- /dev/null +++ b/tools/test_mcc_hud.py @@ -0,0 +1,698 @@ +"""MCC canvas and full-resolution icon geometry, using the real C routines. + +The observed Ruby fixtures use 30x38 unflagged pause glyphs and 93x93 +half-HUD-scale pickup glyphs. Cover their independent sizing and text advances, +including split-screen and the neutral Xbox/CE dispatch. +""" +from pathlib import Path +import shutil +import subprocess +import sys + +import pytest + +from harness import function + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.fixture(scope="module") +def unarmed_hud_tool(tmp_path_factory): + compiler = shutil.which("clang") + if not compiler: + pytest.skip("clang is needed for MCC HUD tests") + work = tmp_path_factory.mktemp("mcc-unarmed-hud") + body = function((ROOT / "port/linux/game/mcc_hud.c").read_text(), "mcc_hud_default") + code = r''' +#include +#include +#include +#define NONE (-1) +#define _hud_anchor_center 4 +#define _error_silent 0 +struct tag_reference {long group_tag;char *name;long length,index;}; +struct weapon_hud_interface_definition { + struct tag_reference parent_hud; + struct {short corner;} absolute_placement; + unsigned char visuals[256]; +}; +struct hud_globals_definition {struct {struct tag_reference default_weapon_hud;} defaults;}; +struct mcc_runtime {unsigned char *tag_index;struct {uint32_t tag_count;} report;}; +static unsigned char arena[2097152], original[1048576]; +static unsigned used, calls, fail_at, warnings; +static void *mcc_runtime_allocate(struct mcc_runtime *r,uint32_t bytes) { + void *p;(void)r; + if (++calls==fail_at || bytes>sizeof(arena)-used) return NULL; + p=arena+used;used=(used+bytes+15)&~15u;memset(p,0,bytes);return p; +} +static void error(short level,char const *text,...) {(void)level;(void)text;warnings++;} +''' + body + r''' +int main(int argc,char **argv) { + struct mcc_runtime r; + struct hud_globals_definition g, second; + struct weapon_hud_interface_definition *hud; + uint32_t empty=UINT32_MAX,*entry,count;unsigned i;int mode,ok; + if(argc!=2)return 2;mode=atoi(argv[1]); + memset(&g,0,sizeof(g));memset(original,0x51,sizeof(original)); + g.defaults.default_weapon_hud.index=mode==1 ? 0x12340001 : NONE; + second=g;r.tag_index=original;count=mode==6 ? 32767 : 2; + r.report.tag_count=mode==2 ? 32768 : count; + if(mode>=3 && mode<=5)fail_at=mode-2; + ok=mcc_hud_default(&r,&g,&empty); + if(mode>=2 && mode<=5) return ok || g.defaults.default_weapon_hud.index!=NONE || + r.tag_index!=original || empty!=UINT32_MAX; + if(!ok)return 3; + if(mode==1)return calls || warnings || r.tag_index!=original || + g.defaults.default_weapon_hud.index!=0x12340001 || empty!=UINT32_MAX; + if(r.report.tag_count!=count+1 || memcmp(r.tag_index,original,count*32) || warnings!=1)return 4; + entry=(uint32_t *)(r.tag_index+count*32); + if(entry[0]!='wphi' || entry[1]!=UINT32_MAX || entry[2]!=UINT32_MAX || + entry[3]!=empty || entry[6] || entry[7] || + g.defaults.default_weapon_hud.group_tag!='wphi' || + (uint32_t)g.defaults.default_weapon_hud.index!=empty || + strcmp((char *)(uintptr_t)entry[4],"mcc_runtime\\unarmed_hud"))return 5; + hud=(void *)(uintptr_t)entry[5]; + if(hud->parent_hud.index!=NONE || hud->parent_hud.group_tag!='wphi' || + hud->absolute_placement.corner!=_hud_anchor_center)return 6; + for(i=0;ivisuals);i++)if(hud->visuals[i])return 7; + if(!mcc_hud_default(&r,&second,&empty) || calls!=3 || warnings!=1 || + second.defaults.default_weapon_hud.index!=g.defaults.default_weapon_hud.index)return 8; + return 0; +} +''' + source = work / "unarmed.c" + source.write_text(code) + binary = work / "unarmed.exe" + target = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld"] if sys.platform == "win32" else ["-m32"] + subprocess.run([compiler, *target, "-std=c89", "-Wall", "-Wextra", "-Werror", + "-Wno-multichar", str(source), "-o", str(binary)], check=True, capture_output=True) + return binary + + +@pytest.mark.parametrize("case", range(7)) +def test_missing_unarmed_hud_is_owned_empty_and_failure_safe(unarmed_hud_tool, case): + result = subprocess.run([str(unarmed_hud_tool), str(case)], capture_output=True) + assert result.returncode == 0, result.stderr + + +@pytest.fixture(scope="module") +def hud_tool(tmp_path_factory): + compiler = shutil.which("clang") + if not compiler: + pytest.skip("clang is needed for MCC HUD tests") + work = tmp_path_factory.mktemp("mcc-hud") + source = (ROOT / "port/linux/game/mcc_hud_draw.c").read_text() + functions = "\n".join(function(source, name) for name in [ + "mcc_hud_glyphs_dispose", "mcc_hud_button_index", "mcc_hud_button_bitmap", "mcc_hud_button_draw", + "mcc_hud_canvas_scale", "mcc_hud_bitmap_scale", "mcc_hud_icon_draw"]) + code = r''' +#include +#include +#include +#include +typedef float real; +typedef unsigned char boolean; +typedef unsigned long pixel32; +typedef struct {short x,y;} point2d; +typedef struct {short x0,y0,x1,y1;} rectangle2d; +typedef struct {float x0,x1,y0,y1;} real_rectangle2d; +struct bitmap_data {short width,height;unsigned long *hardware_format;}; +struct bitmap_group {unsigned flags;}; +struct dynamic_screen_vertex {struct {float x,y;}position,texture_coordinates;pixel32 color;}; +struct rasterizer_dynamic_screen_geometry_parameters { + struct bitmap_data *map[3]; + struct {float i,j;}map_texture_scale[3],map_scale[3]; + short framebuffer_blend_function; +}; +struct icon_hud_element_definition { + short sequence_index,width_offset;point2d offset; + unsigned long color;char frame_rate;unsigned char flags;short text_index; +}; +#define NONE (-1) +#define TRUE 1 +#define FALSE 0 +#define _hud_anchor_bottom_left 2 +static int mcc,players,lookups,draws; +static float drawn_scale; +static point2d drawn_point; +static pixel32 drawn_color; +static real left,top,right,bottom; +static struct bitmap_group group; +static struct {struct bitmap_data *bitmap;long asset;boolean attempted;} mcc_buttons[14]; +static short mcc_buttons_style; +static int high_res,style; +static short controller_glyph_style(void) {return (short)style;} +#define controller_glyph_draw_with_release(style,index,icon,cursor,color,unbind) 0 +#define controller_glyphs_dispose() ((void)0) +static int config_boolean(char const *name) {(void)name;return high_res;} +static struct {struct {struct {long count;void *address;} button_icons;} messaging;} globals,*hud_globals; +static int allocations,registrations,deletions; +static struct bitmap_data native_bitmap; +static unsigned long hardware[2]; +static char const *assets[]={"ui\\shell\\bitmaps\\a_butn","ui\\shell\\bitmaps\\b_butn", + "ui\\shell\\bitmaps\\x_butn","ui\\shell\\bitmaps\\y_butn", + "mcc\\buttons\\black","mcc\\buttons\\white", + "ui\\hud\\buttons\\classic_a","ui\\hud\\buttons\\classic_b","ui\\hud\\buttons\\classic_x","ui\\hud\\buttons\\classic_y", + "ui\\hud\\buttons\\gem_a","ui\\hud\\buttons\\gem_b","ui\\hud\\buttons\\gem_x","ui\\hud\\buttons\\gem_y","ui\\hud\\buttons\\trigger_left","ui\\hud\\buttons\\trigger_right","ui\\hud\\buttons\\thumbstick_left","ui\\hud\\buttons\\thumbstick_right","ui\\hud\\buttons\\thumbstick-halfway_left","ui\\hud\\buttons\\thumbstick-halfway_right","ui\\hud\\buttons\\thumbstick-full_left","ui\\hud\\buttons\\thumbstick-full_right"}; +static long hud_hires_asset_count(void) {return sizeof(assets)/sizeof(*assets);} +static char const *hud_hires_asset_tag(long i) {return assets[i];} +static struct bitmap_data *bitmap_2d_new(short w,short h,short m,short f) { + if((w!=32&&w!=64)||h!=w||m||f!=11)abort();allocations++; + native_bitmap.width=w;native_bitmap.height=h;return &native_bitmap; +} +static int rasterizer_bitmap_new(struct bitmap_data *b) {b->hardware_format=hardware;return 1;} +static void hud_hires_register_placeholder(long a,unsigned long const *t) { + if(a<0||a>=hud_hires_asset_count()||(t&&t!=hardware))abort();registrations+=t?1:-1; +} +static void xgpu_mcc_texture_unbind(unsigned long const *t) {if(t!=hardware)abort();} +static void bitmap_delete(struct bitmap_data *b) {if(b!=&native_bitmap)abort();deletions++;} +static void rasterizer_psuedo_dynamic_screen_quad_draw( + struct rasterizer_dynamic_screen_geometry_parameters *p,struct dynamic_screen_vertex *v) { + if(p->framebuffer_blend_function!=(native_bitmap.width==64?7:0)||p->map[0]!=&native_bitmap||p->map[1]||p->map[2])abort(); + if(p->map_scale[0].i!=1||p->map_scale[0].j!=1|| + p->map_texture_scale[0].i!=1||p->map_texture_scale[0].j!=1)abort(); + if(v[0].texture_coordinates.x||v[0].texture_coordinates.y|| + (native_bitmap.width==32 && (v[2].texture_coordinates.x!=21.0f/32||v[2].texture_coordinates.y!=26.0f/32)))abort(); + left=v[0].position.x;top=v[0].position.y;right=v[2].position.x;bottom=v[2].position.y; + draws++;drawn_scale=(v[2].position.y-v[0].position.y)/26; + drawn_point.x=(short)v[0].position.x;drawn_point.y=(short)v[2].position.y;drawn_color=v[0].color; +} +static int mcc_cache_tags_loaded(void) {return mcc;} +static long game_time_get(void) {return 0;} +static int local_player_count(void) {return players;} +static struct bitmap_group *bitmap_group_get(long id) { + if(id!=17)abort();lookups++;return &group; +} +static short draw_unicode_string_capital_middle(rectangle2d const *bounds,wchar_t const *text) { + if(text[0])abort();return (short)(bounds->y0+8); +} +static void hud_draw_bitmap_direct(struct bitmap_data const *bitmap,short corner, + point2d const *point,real_rectangle2d const *clip,real scale,real theta, + pixel32 color,boolean linear) { + (void)bitmap;(void)clip; + if(corner!=2||theta||linear)abort(); + draws++;drawn_scale=scale;drawn_point=*point;drawn_color=color; +} +''' + (ROOT/'port/linux/game/hud_button_layout.h').read_text() + functions + r''' +int main(int argc,char **argv) { + struct bitmap_data bitmap={256,256,NULL}; + real_rectangle2d clip={0.0f,30.0f/256,0.0f,38.0f/256}; + rectangle2d cursor={100,120,200,140},before=cursor; + struct icon_hud_element_definition icon={0,-6,{-2,15},0xFF123456,0,2,0},saved=icon; + struct icon_hud_element_definition buttons[18],*active=&icon; + int menu,handled; + if(argc!=6 && argc!=7 && argc!=8 && argc!=10 && argc!=12)return 2; + if(argc==12) {high_res=atoi(argv[10]);style=atoi(argv[11]);} + mcc=atoi(argv[1]);players=atoi(argv[2]);menu=atoi(argv[3]); + group.flags=(unsigned)atoi(argv[4]);icon.flags=(unsigned char)atoi(argv[5]); + if(argc==7)icon.offset.y=(short)atoi(argv[6]);saved=icon; + if(argc>=8) { + if(argc>=10) {icon.color=strtoul(argv[9],NULL,16);saved=icon;} + int b=atoi(argv[7]);if(b<0||b>=18)return 8; + memset(buttons,0,sizeof(buttons));buttons[b]=icon;buttons[b].sequence_index=99; + globals.messaging.button_icons.count=18;globals.messaging.button_icons.address=buttons; + hud_globals=&globals;active=&buttons[b]; + } + if(!menu) {clip.x1=clip.y1=93.0f/256;} + handled=mcc_hud_icon_draw(17,&bitmap,&clip,&cursor,argc>=10 ? strtoul(argv[8],NULL,16) : 0xFFABCDEF,active,menu); + if(memcmp(&icon,&saved,sizeof(icon)))return 3; + if(!mcc && (memcmp(&cursor,&before,sizeof(cursor))||draws||lookups||handled))return 4; + if(mcc_hud_bitmap_scale(NONE)!=1.0f)return 5; + if(argc>=8 && mcc && !menu && (atoi(argv[7])<6 || (high_res && (atoi(argv[7])==6 || atoi(argv[7])==7 || atoi(argv[7])>=14)))) { + if(allocations!=1||registrations!=1||lookups)return 9; + if(mcc_hud_button_bitmap(mcc_hud_button_index(active))!=&native_bitmap||allocations!=1)return 10; + mcc_hud_glyphs_dispose();mcc_hud_glyphs_dispose(); + if(registrations||deletions!=1)return 11; + } else if(allocations||registrations)return 12; + printf("%d %d %.3f %d %d %d %lu %.3f\n",handled,draws,drawn_scale, + drawn_point.x,drawn_point.y,cursor.x0,drawn_color,mcc_hud_canvas_scale()); + if(argc==12)printf("%.6f %.6f %.6f %.6f\n",left,top,right,bottom); + return 0; +} +''' + path = work / "hud.c" + binary = work / ("hud.exe" if sys.platform == "win32" else "hud") + path.write_text(code) + command = [compiler, "-std=gnu99", "-Wall", "-Wextra", "-Werror", str(path), "-o", str(binary)] + if sys.platform == "win32": + command[1:1] = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld"] + result = subprocess.run(command, capture_output=True, text=True) + assert result.returncode == 0, result.stderr + return binary + + +@pytest.mark.parametrize("players", [1, 2, 4]) +@pytest.mark.parametrize("menu", [False, True]) +@pytest.mark.parametrize("flags", [0, 0x10, 0x80, 0x90]) +@pytest.mark.parametrize("icon_flags", [0, 2, 4, 6]) +def test_icon_canvas_size_and_cursor_advance(hud_tool, players, menu, flags, icon_flags): + result = subprocess.run([str(hud_tool), "1", str(players), str(int(menu)), str(flags), str(icon_flags)], + capture_output=True, text=True) + assert result.returncode == 0, result.stderr + handled, draws, scale, x, y, cursor, color, canvas = result.stdout.split() + viewport = 0.75 if players > 1 and not menu else 1.0 + expected_scale = viewport * (0.25 if flags else 0.5) + # Native gameplay offsets use bitmap units and truncate before cursor addition. + offset_scale = viewport if menu else expected_scale + expected_x = int(101 - 2 * viewport) if menu else 100 + int(-2 * offset_scale) + expected_y = int(128 + 38 * expected_scale * 0.5) if menu else 140 - int(15 * offset_scale) + advance = -6 * offset_scale + if not icon_flags & 4: + advance += (30 if menu else 93) * expected_scale + assert (handled, draws) == ("1", "1") + assert float(scale) == pytest.approx(expected_scale, abs=0.0006) + assert (int(x), int(y), int(cursor)) == (expected_x, expected_y, int(expected_x + advance)) + assert int(color) == (0xFF123456 if icon_flags & 2 else 0xFFABCDEF) + assert float(canvas) == 0.5 + + +@pytest.mark.parametrize("menu", [False, True]) +def test_xbox_and_ce_dispatch_are_neutral(hud_tool, menu): + result = subprocess.run([str(hud_tool), "0", "2", str(int(menu)), "16", "2"], + capture_output=True, text=True) + assert result.returncode == 0, result.stderr + assert result.stdout.split()[:2] == ["0", "0"] + assert float(result.stdout.split()[-1]) == 1.0 + + +@pytest.mark.parametrize("players", [1, 2]) +@pytest.mark.parametrize("offset_y", [-5, 15]) +def test_messaging_offsets_preserve_stock_and_map_authored_values(hud_tool, players, offset_y): + # Xbox/Mercury/Nitra use -5; Ruby changes only Y to +15. These text + # offsets retain their signs and use the same bitmap units as the icon. + result = subprocess.run([str(hud_tool), "1", str(players), "0", "16", "2", str(offset_y)], + capture_output=True, text=True) + assert result.returncode == 0, result.stderr + viewport = 0.75 if players > 1 else 1.0 + assert int(result.stdout.split()[4]) == 140 - int(offset_y * viewport * 0.25) + + +@pytest.mark.parametrize("button", range(6)) +@pytest.mark.parametrize("players", [1, 2, 4]) +@pytest.mark.parametrize("flags", [0, 16, 128]) +def test_gameplay_native_buttons_ignore_mcc_sheet_and_offsets(hud_tool, button, players, flags): + result=subprocess.run([str(hud_tool),"1",str(players),"0",str(flags),"6","0",str(button)], + capture_output=True,text=True) + assert result.returncode==0,result.stderr + handled,draws,scale,x,y,cursor,color,canvas=result.stdout.split() + viewport=1.0 if players==1 else 0.75 + assert (handled,draws)==("1","1") + assert int(x)==int(100+2*viewport) + assert float(scale)==pytest.approx(viewport*20/26,abs=0.0006) + assert int(y)==int(128+10*viewport) + assert int(cursor)==int(int(100+2*viewport)+(21*20/26-3)*viewport) + assert int(color)==0xFFFFFFFF + + +@pytest.mark.parametrize("loaded,menu,button", [(0,0,0),(0,1,2),(1,1,0),(1,1,1),(1,0,6),(1,0,17)]) +def test_native_glyph_scope_preserves_menus_other_formats_and_icons(hud_tool, loaded, menu, button): + result=subprocess.run([str(hud_tool),str(loaded),"1",str(menu),"16","2","0",str(button)], + capture_output=True,text=True) + assert result.returncode==0,result.stderr + + +@pytest.fixture(scope="module") +def anchor_tool(tmp_path_factory): + compiler = shutil.which("clang") + if not compiler: + pytest.skip("clang is needed") + work = tmp_path_factory.mktemp("mcc-anchors") + source = (ROOT / "port/linux/game/mcc_hud_draw.c").read_text() + routines = "\n".join(function(source, n) for n in ["mcc_hud_weapon_frame_begin", "mcc_hud_weapon_frame_end", + "mcc_hud_edge", "mcc_hud_frame_inset", "mcc_hud_anchor_point", + "mcc_hud_anchor_bounds", "mcc_hud_anchor_number"]) + code = r''' +#include +#include +typedef float real; +typedef int boolean; +typedef struct {short x,y;} point2d; +typedef struct {short x0,y0,x1,y1;} rectangle2d; +typedef struct {float x0,x1,y0,y1;} real_rectangle2d; +struct bitmap_data {short width,height;point2d registration_point;}; +struct hud_placement_definition {point2d offset;short pad;}; +#define MCC_HUD_NATIVE_FRAME 0x4D53 +#define NONE (-1) +static short mcc_weapon_frame=NONE; +static boolean mcc_native_view; +#define TRUE 1 +#define FALSE 0 +#define MIN(a,b) ((a)<(b)?(a):(b)) +static int loaded; +struct weapon_hud_interface_definition { + struct {long index;} parent_hud; + struct {short corner,pad;} absolute_placement; + struct {long count;} statics,meters,numbers,overlays; +}; +static struct weapon_hud_interface_definition hud[2]; +static void *tag_get(long group,long index) {(void)group;return index>=0&&index<2 ? hud+index : NULL;} +static int mcc_cache_contains(void const *p,long size) {(void)size;return p==hud||p==hud+1;} +static long halo_screen_width(void) {return 840;} +static int mcc_cache_tags_loaded(void) {return loaded;} +''' + routines + r''' +int main(int argc,char **argv) { + struct hud_placement_definition placement={{10,20},0}; + rectangle2d window={40,30,840,430},viewport={20,10,860,450}; + point2d point={-99,-99}; + real_rectangle2d bounds={-99,-99,-99,-99}; + short cursor=-99,anchor;int a,b,c;float scale; + if(argc==2) { + int test=atoi(argv[1]); + loaded=test!=0; + hud[0].parent_hud.index=1;hud[1].parent_hud.index=NONE; + hud[0].absolute_placement.pad=hud[1].absolute_placement.pad=MCC_HUD_NATIVE_FRAME; + hud[0].meters.count=hud[1].numbers.count=1; + placement.pad=MCC_HUD_NATIVE_FRAME; + if(test==2)hud[0].absolute_placement.pad=0; + if(test==3)hud[1].absolute_placement.pad=0; + if(test==4)hud[1].parent_hud.index=0; + if(test==5)hud[1].parent_hud.index=9; + if(test==6) {hud[1].numbers.count=0;hud[1].absolute_placement.pad=0;} + if(test==7) {hud[1].numbers.count=0;hud[0].absolute_placement.pad=0;} + if(test==8)hud[1].absolute_placement.corner=1; + if(test==9)hud[0].absolute_placement.pad=hud[1].absolute_placement.pad=0; + mcc_hud_weapon_frame_begin(0); + a=mcc_hud_anchor_point(0,&placement,NULL,1,&window,&viewport,&point); + if(a!=(test==3 || test==4 || test==5 || test>=7))return 10; + if(a && (point.x!=16 || point.y!=26))return 11; + mcc_hud_weapon_frame_end(); + if(mcc_weapon_frame!=NONE || mcc_hud_anchor_point(0,&placement,NULL,1,&window,&viewport,&point))return 12; + placement.pad=0; + if(mcc_hud_anchor_point(0,&placement,NULL,1,&window,&viewport,&point)!=loaded)return 13; + return 0; + } + if(argc!=4 && argc!=5)return 2; + if(argc==5) { + if(atoi(argv[4])==1) {window=(rectangle2d){64,36,422,236};viewport=(rectangle2d){0,0,426,240};} + else {window=(rectangle2d){180,30,700,430};} + } + loaded=atoi(argv[1]);anchor=(short)atoi(argv[2]);scale=(float)atof(argv[3]); + a=mcc_hud_anchor_point(anchor,&placement,NULL,scale,&window,&viewport,&point); + b=mcc_hud_anchor_bounds(anchor,200,80,&bounds); + c=mcc_hud_anchor_number(anchor,100,300,&cursor); + printf("%d %d %d %d %d %.1f %.1f %.1f %.1f %d",a,b,c,point.x,point.y, + bounds.x0,bounds.x1,bounds.y0,bounds.y1,cursor); + return 0; +} +''' + path=work / "anchors.c" + path.write_text(code) + binary=work / ("anchors.exe" if sys.platform=="win32" else "anchors") + command=[compiler,"-std=gnu89","-fsanitize=undefined","-fsanitize-trap=undefined",str(path),"-o",str(binary)] + if sys.platform=="win32": + command[1:1]=["--target=i686-pc-windows-msvc","-fuse-ld=lld"] + result=subprocess.run(command,capture_output=True,text=True) + assert result.returncode==0,result.stderr + return binary + + +@pytest.mark.parametrize("case",range(10)) +def test_weapon_frame_keeps_parent_and_child_together_and_resets(anchor_tool,case): + result=subprocess.run([str(anchor_tool),str(case)],capture_output=True,text=True) + assert result.returncode==0,result.stderr + + +@pytest.fixture(scope="module") +def child_anchor_tool(tmp_path_factory): + compiler=shutil.which("clang") + if not compiler:pytest.skip("clang is needed") + work=tmp_path_factory.mktemp("mcc-child-anchors") + source=(ROOT/"port/linux/game/mcc_hud_draw.c").read_text() + code=r''' +#include +#include +struct hud_absolute_placement_definition {short corner,pad;long unused[8];}; +static int loaded; +static int mcc_cache_tags_loaded(void) {return loaded;} +'''+function(source,"mcc_hud_child_placement")+r''' +int main(int argc,char **argv) { + unsigned short header[18]={0}; + struct hud_absolute_placement_definition parent={4,71,{22}},saved=parent,out={-1,0,{0}}; + struct hud_absolute_placement_definition const *result; + int child; + if(argc!=3)return 2;loaded=atoi(argv[1]);child=atoi(argv[2]);header[3]=(unsigned short)child; + result=mcc_hud_child_placement(&parent,loaded?header:NULL,&out); + if(memcmp(&parent,&saved,sizeof(parent)))return 3; + if(loaded && child>=1 && child<=9) { + if(result!=&out||out.corner!=child-1||out.pad!=71||out.unused[0]!=22)return 4; + } else if(result!=&parent||out.corner!=-1)return 5; + /* Each element must start from the parent, not the previous override. */ + header[3]=0;result=mcc_hud_child_placement(&parent,header,&out); + return result!=&parent||result->corner!=4; +} +''' + path=work/"child.c";path.write_text(code) + binary=work/("child.exe" if sys.platform=="win32" else "child") + command=[compiler,"-std=gnu89","-Wall","-Wextra","-Werror",str(path),"-o",str(binary)] + if sys.platform=="win32":command[1:1]=["--target=i686-pc-windows-msvc","-fuse-ld=lld"] + result=subprocess.run(command,capture_output=True,text=True) + assert result.returncode==0,result.stderr + return binary + + +@pytest.mark.parametrize("loaded",[0,1]) +@pytest.mark.parametrize("child",[-1,*range(11),32767]) +def test_child_anchors_are_mcc_only_bounded_and_do_not_mutate_parent(child_anchor_tool, loaded, child): + result=subprocess.run([str(child_anchor_tool),str(loaded),str(child)],capture_output=True,text=True) + assert result.returncode==0,result.stderr + + +@pytest.mark.parametrize("scale", [1.0, 0.75]) +@pytest.mark.parametrize("anchor,origin,direction,bounds,cursor", [ + (5, (420,6), (1,1), (-100,100,0,80), 350), + (6, (420,434), (1,-1), (-100,100,-80,0), 350), + (7, (6,220), (1,1), (0,200,-40,40), 400), + (8, (834,220), (-1,1), (-200,0,-40,40), 300)]) +def test_mcc_edge_anchors_follow_player_window(anchor_tool,scale,anchor,origin,direction,bounds,cursor): + result=subprocess.run([str(anchor_tool),"1",str(anchor),str(scale)],capture_output=True,text=True) + assert result.returncode==0,result.stderr + values=list(map(float,result.stdout.split())) + assert values[:3]==[1,1,1] + assert values[3:5]==[int(origin[0]+10*scale*direction[0]),int(origin[1]+20*scale*direction[1])] + assert values[5:9]==list(bounds) + assert values[9]==cursor + + +@pytest.mark.parametrize("loaded,anchor", [(0,n) for n in range(10)]+[(1,n) for n in [-1,4,9]]) +def test_edge_dispatch_preserves_legacy_and_unknown_anchors(anchor_tool,loaded,anchor): + result=subprocess.run([str(anchor_tool),str(loaded),str(anchor),"1"],capture_output=True,text=True) + assert result.returncode==0,result.stderr + assert list(map(float,result.stdout.split()))==[0,0,0]+[-99]*7 + + +@pytest.fixture(scope="module") +def terminal_tool(tmp_path_factory): + compiler=shutil.which("clang") + if not compiler: + pytest.skip("clang is needed") + work=tmp_path_factory.mktemp("mcc-terminal") + source=(ROOT / "port/linux/game/mcc_terminal.c").read_text() + routines="\n".join(function(source,n) for n in ["mcc_terminal_scale","mcc_terminal_line_height","mcc_terminal_draw"]) + code=r''' +#include +#include +#include +typedef float real;typedef int boolean; +typedef struct {short x0,y0,x1,y1;} rectangle2d; +struct font_header {short ascending_height,descending_height,leading_height;}; +#define TRUE 1 +#define FALSE 0 +#define NONE (-1) +static int loaded,calls,draws,lookups; +static real current=1,used,origin_x,origin_y; +static rectangle2d drawn; +static struct font_header font; +static int mcc_cache_tags_loaded(void) {return loaded;} +static struct font_header *font_definition_get(long index) {if(index!=7)abort();lookups++;return &font;} +static void rasterizer_text_set_scale(real scale,real x,real y) {current=scale;calls++;if(scale!=1){origin_x=x;origin_y=y;}} +static void rasterizer_draw_string(rectangle2d const *b,void *clip,void *cursor,short height,char const *text) { + if(clip||cursor||height||strcmp(text,"100% unchanged"))abort();draws++;drawn=*b;used=current; +} +'''+routines+r''' +int main(int argc,char **argv) { + rectangle2d bounds={100,400,740,415};struct font_header saved;short h;int handled; + if(argc!=3)return 2;loaded=atoi(argv[1]);font.ascending_height=(short)atoi(argv[2]);saved=font; + h=mcc_terminal_line_height(7,font.ascending_height); + handled=mcc_terminal_draw(7,&bounds,"100% unchanged"); + if(memcmp(&saved,&font,sizeof(font))||current!=1)return 3; + if(!loaded && lookups)return 4; + printf("%d %d %d %d %.6f %.1f %.1f %d %d",h,handled,calls,draws,used,origin_x,origin_y,drawn.x1,drawn.y1); + return 0; +} +''' + path=work / "terminal.c";path.write_text(code) + binary=work / ("terminal.exe" if sys.platform=="win32" else "terminal") + command=[compiler,"-std=gnu89",str(path),"-o",str(binary)] + if sys.platform=="win32":command[1:1]=["--target=i686-pc-windows-msvc","-fuse-ld=lld"] + result=subprocess.run(command,capture_output=True,text=True) + assert result.returncode==0,result.stderr + return binary + + +@pytest.mark.parametrize("loaded,height",[(0,33),(0,15),(0,-1),(1,15),(1,12),(1,33),(1,30),(1,32767)]) +def test_terminal_scales_only_oversized_mcc_text(terminal_tool,loaded,height): + result=subprocess.run([str(terminal_tool),str(loaded),str(height)],capture_output=True,text=True) + assert result.returncode==0,result.stderr + values=list(map(float,result.stdout.split())) + if loaded and height>15: + assert values[:4]==[15,1,2,1] + assert values[4]==pytest.approx(15/height,abs=0.000001) + assert values[5:7]==[100,400] + assert values[7:]==[min(32767,int(100+640/(15/height))),min(32767,401+height)] + else: + assert values[:4]==[height,0,0,0] + + +def test_shoulder_redraws_match_native_controller_order(): + import json + import struct + assets = ROOT / "port/assets/buttons" + entries = json.loads((assets / "buttons.json").read_text())["assets"] + by_tag = {entry["tag"]: entry for entry in entries} + source = (ROOT / "port/linux/game/mcc_hud_draw.c").read_text() + # Controller entries 4/5 are black/white; physical RB/LB map to them. + body = function(source, "mcc_hud_button_bitmap") + assert body.index('buttons\\\\black') < body.index('buttons\\\\white') + for color in ("black", "white"): + entry = by_tag["mcc\\buttons\\" + color] + assert entry["crc"] == 0 + assert (entry["width"], entry["height"], entry["scale"]) == (32, 32, 8) + png = (assets / (entry["name"] + ".png")).read_bytes() + assert png[:8] == b"\x89PNG\r\n\x1a\n" + assert struct.unpack_from(">II", png, 16) == (256, 256) + assert png[24:26] == bytes((8, 6)) # RGBA8 + + +@pytest.mark.parametrize("anchor,expected", [(0,(16,26)),(1,(824,26)),(2,(16,414)),(3,(824,414))]) +def test_mcc_corner_anchors_use_mcc_safe_frame(anchor_tool, anchor, expected): + result=subprocess.run([str(anchor_tool),"1",str(anchor),"1"],capture_output=True,text=True) + assert result.returncode==0,result.stderr + values=list(map(float,result.stdout.split())) + assert values[:3]==[1,0,0] + assert values[3:5]==list(expected) + + +@pytest.mark.parametrize("layout,anchor,expected", [(1,1,(412,32)),(1,3,(412,216)),(2,0,(128,26))]) +def test_mcc_safe_frame_preserves_split_seams_and_zoom_inset(anchor_tool,layout,anchor,expected): + result=subprocess.run([str(anchor_tool),"1",str(anchor),"1",str(layout)],capture_output=True,text=True) + assert result.returncode==0,result.stderr + assert list(map(float,result.stdout.split()))[3:5]==list(expected) + + +@pytest.mark.parametrize("button", range(6)) +@pytest.mark.parametrize("flags,prompt,authored,expected", [ + (2, 0x7FABCDEF, 0xFF123456, 0xFFFFFFFF), + (2, 0x7FABCDEF, 0x40123456, 0x40FFFFFF), + (0, 0x7FABCDEF, 0xFF123456, 0x7FFFFFFF), + (0, 0, 0xFF123456, 0x00FFFFFF), +]) +def test_gameplay_button_authored_opacity(hud_tool, button, flags, prompt, authored, expected): + result = subprocess.run([str(hud_tool), "1", "1", "0", "0", str(flags), "0", str(button), + f"{prompt:x}", f"{authored:x}"], capture_output=True, text=True) + assert result.returncode == 0, result.stderr + assert int(result.stdout.split()[6]) == expected + + +@pytest.mark.parametrize("style", range(3)) +@pytest.mark.parametrize("button", range(4)) +@pytest.mark.parametrize("players", [1, 2]) +def test_high_res_mcc_button_visible_size(hud_tool, style, button, players): + import numpy as np + from PIL import Image + result = subprocess.run([str(hud_tool), "1", str(players), "0", "0", "2", "0", str(button), + "7fffffff", "ffffffff", "1", str(style)], capture_output=True, text=True) + assert result.returncode == 0, result.stderr + fields = result.stdout.split() + left, top, right, bottom = map(float, fields[8:]) + letter = "abxy"[button] + name = ("classic_" + letter if style == 0 else "gem_" + letter if style == 1 else letter + "_butn") + "__0.png" + alpha = np.asarray(Image.open(ROOT / "port/assets/buttons" / name))[..., 3] + ys, xs = np.where(alpha >= 128) + viewport = 1.0 if players == 1 else 0.75 + scale = viewport + assert (right-left) * (xs.max()+1-xs.min()) / 168 == pytest.approx(21*scale, abs=0.0001) + assert (bottom-top) * (ys.max()+1-ys.min()) / 208 == pytest.approx(26*scale, abs=0.0001) + assert left + xs.min()*(right-left)/168 == pytest.approx(100+4*viewport, abs=0.0001) + assert top + ys.min()*(bottom-top)/208 == pytest.approx(128-13*viewport, abs=0.0001) + assert int(fields[5]) == int(100+22*viewport) + + +@pytest.mark.parametrize("style", range(3)) +@pytest.mark.parametrize("button", [6,7,14,15,16,17]) +@pytest.mark.parametrize("players", [1,2]) +def test_high_res_mcc_controls_visible_size(hud_tool, style, button, players): + import numpy as np + from PIL import Image + result = subprocess.run([str(hud_tool), "1", str(players), "0", "0", "0", "0", str(button), + "7fabcdef", "ffffffff", "1", str(style)], capture_output=True, text=True) + assert result.returncode == 0, result.stderr + fields = result.stdout.split() + left, top, right, bottom = map(float, fields[8:]) + name = ('trigger_' if button<8 else 'thumbstick_') + ('left' if button%2==0 else 'right') + alpha = np.asarray(Image.open(ROOT/'port/assets/buttons'/(name+'__0.png')))[...,3] + ys,xs=np.where(alpha>=128) + viewport=1.0 if players==1 else 0.75 + scale=viewport + cw,ch=(400,280) if button<8 else (288,320) + w,h=(44,33) if button<8 else (32,34) + assert (right-left)*(xs.max()+1-xs.min())/cw == pytest.approx(w*scale, abs=0.0001) + assert (bottom-top)*(ys.max()+1-ys.min())/ch == pytest.approx(h*scale, abs=0.0001) + assert left+xs.min()*(right-left)/cw == pytest.approx(100+4*viewport, abs=0.0001) + assert top+ys.min()*(bottom-top)/ch == pytest.approx(128-h*viewport/2, abs=0.0001) + assert int(fields[5]) == int(100+(w+1)*viewport) + assert int(fields[6]) == 0x7fabcdef + +@pytest.fixture(scope="module") +def message_frame_tool(tmp_path_factory): + compiler = shutil.which("clang") + if not compiler: + pytest.skip("clang is needed") + work = tmp_path_factory.mktemp("mcc-message-frame") + source = (ROOT / "port/linux/game/mcc_hud.c").read_text() + code = r''' +#include +#define MCC_HUD_NATIVE_FRAME 0x4d53 +struct hud_placement_definition { + struct {short x,y;} offset; + float scale_x,scale_y; + unsigned short multiplayer_scaling_flags; + short pad; +}; +struct hud_messaging_parameters_definition { + struct {short corner;} absolute_placement; + struct hud_placement_definition placement; +}; +''' + function(source,"mcc_hud_offset") + '\n' + function(source,"mcc_hud_message_frame") + r''' +int main(int argc,char **argv) { + struct hud_messaging_parameters_definition message; + short x,y;unsigned flags; + int expected; + if(argc!=6)return 1; + message.absolute_placement.corner=(short)atoi(argv[1]); + x=message.placement.offset.x=(short)atoi(argv[2]); + y=message.placement.offset.y=(short)atoi(argv[3]); + flags=message.placement.multiplayer_scaling_flags=(unsigned short)atoi(argv[4]); + message.placement.pad=MCC_HUD_NATIVE_FRAME; + expected=atoi(argv[5]); + mcc_hud_offset(&message.placement); + mcc_hud_message_frame(&message); + return (message.placement.pad==MCC_HUD_NATIVE_FRAME)!=expected || + message.placement.offset.x!=(flags&4 ? x : x/2) || + message.placement.offset.y!=(flags&4 ? y : y/2) || + message.placement.multiplayer_scaling_flags!=(flags&~4u); +} +''' + path=work/'message.c';path.write_text(code);binary=work/'message.exe' + target=["--target=i686-pc-windows-msvc","-fuse-ld=lld"] if sys.platform=="win32" else ["-m32"] + result=subprocess.run([compiler,*target,"-std=gnu89","-Wall","-Wextra","-Werror",str(path),"-o",str(binary)],capture_output=True,text=True) + assert result.returncode==0,result.stderr + return binary + + +@pytest.mark.parametrize("anchor,x,y,flags,native", [ + (0,0,120,0,1),(0,0,60,4,1),(0,37,85,4,0),(0,2,120,0,0), + (0,0,118,0,0),(0,0,122,0,0),(1,0,120,0,0),(4,0,120,0,0), + (5,0,120,0,0),(0,0,120,4,0),(0,0,120,3,1)]) +def test_stock_message_margin_preserves_authored_positions(message_frame_tool,anchor,x,y,flags,native): + result=subprocess.run([str(message_frame_tool),*map(str,(anchor,x,y,flags,native))],capture_output=True,text=True) + assert result.returncode==0,result.stderr diff --git a/tools/test_mcc_hud_layout.py b/tools/test_mcc_hud_layout.py new file mode 100644 index 0000000000..3dd812b7c6 --- /dev/null +++ b/tools/test_mcc_hud_layout.py @@ -0,0 +1,137 @@ +"""Bounded stock-layout recognition using the production MCC visitor, no map assets.""" +from pathlib import Path +import shutil +import subprocess +import sys + +import pytest +from harness import function + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.fixture(scope="module") +def layout_tool(tmp_path_factory): + compiler = shutil.which("clang") + if not compiler: + pytest.skip("clang is needed") + work = tmp_path_factory.mktemp("mcc-hud-layout") + source = (ROOT / "port/linux/game/mcc_hud.c").read_text() + code = r''' +#include +#include +#include +#include +#define NUMBEROF(x) (sizeof(x)/sizeof((x)[0])) +struct bitmap_group {short type,format,usage;unsigned short flags;char rest[100];}; +struct mcc_runtime {unsigned char *tag_index;struct {uint32_t tag_count;} report;unsigned used;unsigned char *tags;}; +static unsigned char arena[8192]; +static void *mcc_runtime_pointer(struct mcc_runtime *r,uint32_t p,uint32_t bytes) { + (void)r;return p<=sizeof(arena)&&bytes<=sizeof(arena)-p ? arena+p : NULL; +} +''' + function(source, "mcc_hud_word") + '\n' + function(source, "mcc_hud_block") + '\n' + code += (ROOT / "port/linux/game/mcc_hud_layout.inl").read_text() + r''' +static uint64_t visit(struct mcc_runtime *r,uint32_t const *entry) { + unsigned char original[sizeof(arena)]; + uint64_t hash; + memcpy(original,arena,sizeof(arena)); + hash=mcc_hud_layout_visit(r,entry); + assert(!memcmp(original,arena,sizeof(arena))); + return hash; +} +static void word(unsigned at,uint32_t value) {memcpy(arena+at,&value,4);} +int main(int argc,char **argv) { + struct mcc_runtime r={arena,{2},sizeof(arena),arena}; + uint32_t entry[8]={'wphi',0,0,0,0,256,0,0}; + uint64_t baseline,modified;int test; + unsigned p=256,e=1024,b=2048; + short mark=0x4d53; + if(argc!=2)return 1;test=atoi(argv[1]); + /* One corner static element, one sprite bitmap and empty other blocks. */ + word(p+0x60,1);word(p+0x64,e); + word(e+0x24+0x30,0xe0000001); + word(32,'bitm');word(32+12,0xe0000001);word(32+16,4000);word(32+20,b); + memcpy(arena+4000,"test\\meter",11); + word(b+0x60,1);word(b+0x64,3000); + word(b+0x54,1);word(b+0x58,3100); + word(3100+0x34,1);word(3100+0x38,3200); + if(test>=21) { /* Unit HUD geometry remains part of recognition. */ + static unsigned const elements[]={0x24,0x8c,0xf4,0x17c,0x1e4,0x26c,0x2d4}; + unsigned j; + memset(arena+p,0,0x56c);entry[0]='unhi'; + for(j=0;j=15) { + entry[0]='grhi'; + word(p+0x24+0x30,0xe0000001);word(p+0x8c+0x30,0xe0000001); + word(p+0x158,0xe0000001);word(p+0x15c,1);word(p+0x160,5000); + baseline=visit(&r,entry);if(!baseline)return 12; + if(test==15) { /* Icon artwork/scale/offset/sequence are not the counter frame. */ + word(p+0x158,UINT32_MAX);word(5000,0xfffe00a9); + word(5000+4,0x3faa3d71);word(5000+0x48,7); + } else if(test==16)word(p+0xf4,25); /* counter position */ + else if(test==17)word(p+0x24,21); /* panel position */ + else if(test==18)word(p+0x138,3); /* digit layout */ + else if(test==19)word(p+0x160,8190); /* truncated overlay */ + else if(test==20)word(p+0x158,0xe0010001); /* stale icon reference */ + modified=visit(&r,entry); + if(test==15) { + if(modified!=baseline)return 13; + } else if(test<=18) {if(!modified || modified==baseline)return 16;} + else if(modified)return 17; + return 0; + } + baseline=visit(&r,entry); + if(!baseline || mcc_hud_layout_stock(baseline))return 2; + if(test==0) { /* Colors, padding and crosshairs do not select the corner frame. */ + word(e+0x24+0x34,0xff123456);word(p+0x84,999);word(p+0x88,0xffffffff); + word(e+0x24+0x5c,0xffffffff); /* empty overlay pointer is not layout */ + memcpy(arena+e+0x24+14,&mark,2); + } else if(test==1)word(e+0x24,20); /* placement */ + else if(test==2)word(e+4,0x10000); /* child anchor */ + else if(test==3)word(e+0x24+0x54,2); /* sequence */ + else if(test==4)word(3000+4,64); /* dimensions */ + else if(test==5)word(3200+8,0x3f800000); /* sprite bounds */ + else if(test==6)arena[4000]='X'; /* bitmap identity */ + else if(test==7)word(p+0x64,8190); /* truncated element */ + else if(test==8)word(b+0x60,0xffffffff); /* block overflow */ + else if(test==9)word(e+0x24+0x30,0xe0010001); /* stale bitmap handle */ + else if(test==10)word(32+16,0xffffffff); /* invalid name */ + else if(test==11)word(3100+0x38,8190); /* truncated sprite */ + else if(test==12) {word(32+16,4096);memset(arena+4096,'x',256);} /* unterminated name */ + else if(test==13)word(3000+16,7); /* bitmap registration point */ + else if(test==14)word(e+0x24+0x58,1); /* authored overlay count */ + modified=visit(&r,entry); + if(test==0 && modified!=baseline)return 3; + if((test==1 || test==2 || test==14) && (!modified || modified==baseline))return 4; + if(((test>=3 && test<=6) || test==13) && modified!=baseline)return 19; + if(test>=7 && test<=12 && modified)return 5; + if(test==0) { + if(visit(&r,entry)!=baseline)return 8; + } + return 0; +} +''' + path = work / "layout.c" + path.write_text(code) + binary = work / "layout.exe" + target = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld"] if sys.platform == "win32" else ["-m32"] + result = subprocess.run([compiler, *target, "-std=gnu89", "-Wall", "-Wextra", "-Werror", + "-Wno-multichar", str(path), "-o", str(binary)], capture_output=True, text=True) + assert result.returncode == 0, result.stderr + return binary + + +@pytest.mark.parametrize("case", range(26)) +def test_layout_identity_bounds_and_read_only_hashing(layout_tool, case): + result = subprocess.run([str(layout_tool), str(case)], capture_output=True, text=True) + assert result.returncode == 0, result.stderr diff --git a/tools/test_mcc_hud_mask.py b/tools/test_mcc_hud_mask.py new file mode 100644 index 0000000000..58dfd87c01 --- /dev/null +++ b/tools/test_mcc_hud_mask.py @@ -0,0 +1,79 @@ +"""HUD screen-effect mask units and scoped ownership, using production code.""" +from pathlib import Path + +import pytest +from harness import function +from test_hud_button_style import run_c + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.mark.parametrize('flags,factor', [(0, 1), (0x10, .5), (0x80, .5), (0x90, .5)]) +def test_mask_units_and_lifecycle(tmp_path, flags, factor): + source = (ROOT/'port/linux/game/mcc_hud_draw.c').read_text() + routines = '\n'.join(function(source, name) for name in [ + 'mcc_hud_canvas_scale', 'mcc_hud_bitmap_scale']) + routines += '\n'.join(function(source, name) for name in [ + 'mcc_hud_mask_begin', 'mcc_hud_mask_end', 'mcc_hud_mask_transform']) + run_c(tmp_path, r''' +#include +#include +typedef float real; +typedef struct {float i,j;} real_vector2d; +struct bitmap_data {long tag_index;unsigned short flags;}; +struct bitmap_group {unsigned short flags;}; +#define NONE -1 +static int mcc=1,reads; +static struct bitmap_group group; +static struct bitmap_data const *mcc_hud_mask; +static real mcc_hud_mask_scale=1.0f; +static int mcc_cache_tags_loaded(void) {return mcc;} +static struct bitmap_group *bitmap_group_get(long index) {assert(index==7);reads++;return &group;} +''' + routines + r''' +static void check(struct bitmap_data const *b,float factor) { + real_vector2d size={512,256},scale; + scale.i=(b && (b->flags&16))?1:1.f/512; + scale.j=(b && (b->flags&16))?1:1.f/256; + mcc_hud_mask_transform(b,&size,&scale); + assert(size.i==512*factor && size.j==256*factor); + assert(scale.i==((b && (b->flags&16))?1.f/factor:1.f/(512*factor))); + assert(scale.j==((b && (b->flags&16))?1.f/factor:1.f/(256*factor))); +} +int main(void) { + struct bitmap_data mask={7,16},other={7,16}; + int linear; + group.flags=FLAGS; + for(linear=0;linear<2;linear++) { + mask.flags=linear?16:0; + check(&mask,1); + mcc_hud_mask_begin(&mask); + check(&mask,FACTOR); + check(&other,1); /* Render-target fallback and unrelated cinematic maps. */ + check(NULL,1); + mcc_hud_mask_end();check(&mask,1); + mcc_hud_mask_begin(NULL);check(&mask,1); + } + mcc=0;reads=0; + mcc_hud_mask_begin(&mask);check(&mask,1); + assert(reads==0); /* Xbox/CE never look up an MCC bitmap. */ + mcc_hud_mask_end();mcc=1; + mcc_hud_mask_begin(&mask);mcc=0;check(&mask,1); + mcc_hud_mask_end();mcc=1;check(&mask,1); /* Unload/reused pointer. */ + assert(mask.tag_index==7 && mask.flags==16); /* Original bitmap unchanged. */ + mask.tag_index=NONE;reads=0; + mcc_hud_mask_begin(&mask);check(&mask,1);mcc_hud_mask_end(); + assert(reads==0); /* A generated/render-target bitmap has no MCC tag units. */ + return 0; +} +'''.replace('FLAGS', str(flags)).replace('FACTOR', str(float(factor))+'f')) + + +def test_mask_scope_reaches_renderer_and_ends_before_next_view(): + draw = function((ROOT/'source/interface/interface.c').read_text(), 'interface_draw_screen') + begin = draw.index('mcc_hud_mask_begin(') + end = draw.index('mcc_hud_mask_end(') + assert begin < draw.index('rasterizer_screen_effect(¶meters)') < end + assert 'return' not in draw[begin:end] + renderer = (ROOT/'source/rasterizer/xbox/rasterizer_xbox_screen_effect.c').read_text() + assert renderer.count('mcc_hud_mask_transform(') == 1 + assert renderer.index('custom_edition_hud_mask_transform(') < renderer.index('mcc_hud_mask_transform(') diff --git a/tools/test_mcc_hud_meter_render.py b/tools/test_mcc_hud_meter_render.py new file mode 100644 index 0000000000..47dd0f7506 --- /dev/null +++ b/tools/test_mcc_hud_meter_render.py @@ -0,0 +1,72 @@ +"""Render MCC meter conversion through the real GPU shader, without map assets. + +Uses the existing hidden-GL test builder. Covers all 256 authored shape values, +fill thresholds, empty/full/partial meters and fractional placement at 1440p HUD +scale. Run directly in an environment with SDL3, clang, NumPy, Pillow and SciPy. +""" +from pathlib import Path +import test_hud_ammo_thresholds as gpu +from harness import function + +root = Path(__file__).resolve().parents[1] +channels = function((root / 'port/linux/game/mcc_bitmaps.c').read_text(), 'mcc_channels') +prefix = gpu.HARNESS[:gpu.HARNESS.index('int main(')].replace( + 'CHECK(ok);glDeleteShader', + 'if(!ok){char log[8192];glGetProgramInfoLog(p,sizeof(log),NULL,log);fprintf(stderr,"%s\\n",log);}CHECK(ok);glDeleteShader') +setup = gpu.HARNESS[gpu.HARNESS.index('int main('):gpu.HARNESS.index(' struct meter_parameters meter=')] +setup = setup.replace('1040*272', '1040*800').replace('1040,272', '1040,800') +checks = r''' + struct meter_parameters meter={.gradient_min_color=0xffffffff,.gradient_max_color=0xffffff, + .flash_color=0xff000000,.background_color=0xff000000,.tint_color=0xffffff,.gradient=1}; + struct nv2a_pixel_shader_key key=meter_key(&meter,TRUE); + GLuint fixed=program(&key); + /* A synthetic Gearbox bitmap: luminance is coverage, alpha is fill order. */ + for(int y=0;y<2048;y++)for(int x=0;x<2048;x++) { + unsigned c=mcc_channels(((unsigned)(x%256)<<24)|((unsigned)(y%256)<<16),4); + int at=4*(y*2048+x); + atlas[at]=(c>>16)&255;atlas[at+1]=(c>>8)&255;atlas[at+2]=c&255;atlas[at+3]=c>>24; + } + glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA8,2048,2048,0,GL_RGBA,GL_UNSIGNED_BYTE,atlas); + glGenerateMipmap(GL_TEXTURE_2D); + int rect[4]={0,0,256,256},cutoffs[]={0,1,64,128,254,255};int renders=0; + float scales[]={1,1.65f,3}; + for(int size=0;size<3;size++)for(int offset=0;offset<2;offset++)for(int c=0;c<6;c++) { + int q=cutoffs[c],w=(int)(256*scales[size]),h=w;float shift=offset?0.37f:0; + meter.gradient_min_color=(q<<24)|0xffffff;meter.flash_color=q<<24; + key=meter_key(&meter,TRUE);draw(fixed,&key,rect,w,h,shift,out); + for(int y=2;y2.1f) { + fprintf(stderr,"q=%d scale=%f shift=%f x=%d y=%d channel=%d actual=%d expected=%f\n",q,scales[size],shift,x,y,channel,out[at+channel],expected);return 1; + } + } + } + renders++; + } + printf("PASS: %d MCC meter GPU renders, coverage edges, fill thresholds and native HUD scale\n",renders); + glDeleteTextures(1,&texture);glDeleteTextures(1,&target);glDeleteFramebuffers(1,&fbo); + free(atlas);free(out);free(reference);SDL_GL_DestroyContext(context);SDL_DestroyWindow(window);SDL_Quit();return 0; +} +''' +def main(): + # Reuse the hidden-context builder; leave its stock test harness intact. + original = gpu.HARNESS + try: + gpu.HARNESS = prefix + '\n' + channels + '\n' + setup + checks + gpu.main() + finally: + gpu.HARNESS = original + + +if __name__ == '__main__': + main() diff --git a/tools/test_mcc_hud_normalization.py b/tools/test_mcc_hud_normalization.py new file mode 100644 index 0000000000..74bf12f31f --- /dev/null +++ b/tools/test_mcc_hud_normalization.py @@ -0,0 +1,447 @@ +"""Whole MCC HUD conversion must preserve equivalent shared authored data. + +Synthetic tag arenas use the production structures, converter and layout visitor. +The fixture supplies only allocation, bounds checking, settings and diagnostics. +""" +from pathlib import Path +import json +import re +import shutil +import subprocess +import sys + +import pytest + +from harness import function, structure + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.fixture(scope="module") +def normalization_tool(tmp_path_factory): + compiler = shutil.which("clang") + if not compiler: + pytest.skip("clang is needed for MCC HUD normalization tests") + work = tmp_path_factory.mktemp("mcc-hud-normalization") + hud = (ROOT / "port/linux/game/mcc_hud.c").read_text() + layout = (ROOT / "port/linux/game/mcc_hud_layout.inl").read_text() + declarations = [] + for path in ["source/interface/hud_definitions.h", + "source/interface/weapon_hud_interface_definition.h", + "source/bitmaps/bitmap_group.h"]: + header = (ROOT / path).read_text() + declarations.extend(structure(header, name) for name in re.findall(r"^struct (\w+)\s*\{", header, re.M)) + body = hud.replace('#include "mcc_hud_layout.inl"', layout) + body = body.replace('#include "mcc_hud_ownership.inl"', + (ROOT / "port/linux/game/mcc_hud_ownership.inl").read_text()) + body = "\n".join(line for line in body.splitlines() if not line.startswith("#include ")) + tags = (ROOT / "port/linux/game/mcc_tags.c").read_text() + body += "\n" + "\n".join(function(tags, name) for name in [ + "mcc_word", "mcc_block", "mcc_hud"]) + code = r''' +#include +#include +#include +#include +#include +#include +#define NUMBEROF(a) (sizeof(a)/sizeof((a)[0])) +#define NONE (-1) +#define TRUE 1 +#define FALSE 0 +#define _hud_anchor_center 4 +#define _error_silent 0 +#define MCC_HUD_NATIVE_FRAME 0x4D53 +typedef unsigned char byte; +typedef unsigned short word; +typedef float real; +typedef union point2d {struct {short x,y;};uint32_t value;} point2d; +typedef struct {float i,j;} real_vector2d; +typedef struct {short x0,y0,x1,y1;} rectangle2d; +typedef struct {float alpha,red,green,blue;} real_argb_color; +typedef struct {float red,green,blue;} real_rgb_color; +typedef struct {float x0,x1,y0,y1;} real_rectangle2d; +typedef struct {float x,y;} real_point2d; +struct tag_reference {long group_tag;char *name;long name_length,index;}; +struct tag_block {long count;void *address,*definition;}; +struct tag_data {long size,flags,file_offset;void *address,*definition;}; +struct mcc_runtime { + unsigned char *tags,*tag_index; + uint32_t used,capacity; + struct {uint32_t tag_count;} report; +}; +static unsigned allocation_calls,allocation_fail_at,warnings; +static unsigned heap_calls,heap_fail_at,heap_live; +static uint32_t handle_base; +static void *mcc_runtime_pointer(struct mcc_runtime *r,uint32_t address,uint32_t bytes) { + uintptr_t start=(uintptr_t)r->tags; + return address>=start && address-start<=r->used && bytes<=r->used-(address-start) ? + (void *)(uintptr_t)address : NULL; +} +static void *mcc_runtime_allocate(struct mcc_runtime *r,uint32_t bytes) { + uint32_t at=(r->used+15)&~15u; + void *p; + if(++allocation_calls==allocation_fail_at || at>r->capacity || bytes>r->capacity-at)return NULL; + p=r->tags+at;memset(p,0,bytes);r->used=at+bytes;return p; +} +static void error(short level,char const *text,...) {(void)level;(void)text;warnings++;} +char const *config_string(char const *name) {(void)name;return "tab";} +static void *hud_malloc(size_t bytes) { + void *p; + if(bytes>=0x10000000u) {fputs("engine allocation limit exceeded\n",stderr);exit(92);} + if(++heap_calls==heap_fail_at)return NULL; + p=malloc(bytes);if(p) {memset(p,0xCA,bytes);heap_live++;}return p; +} +/* cseries.h routes free through debug_free, which requires a live pointer. */ +static void hud_free(void *p) { + if(!p || !heap_live) {fputs("engine free requires a live allocation\n",stderr);exit(91);} + heap_live--;free(p); +} +#define malloc hud_malloc +#define free hud_free +''' + "\n".join(declarations) + "\n" + body + r''' +#undef malloc +#undef free +static void put_word(void *p,uint32_t value) {memcpy(p,&value,4);} +static void tag(struct mcc_runtime *r,unsigned index,uint32_t group,void *root,int renamed) { + uint32_t *entry=(uint32_t *)(r->tag_index+index*32); + char *name=mcc_runtime_allocate(r,64); + strcpy(name,renamed ? "unrelated\\replacement" : "synthetic\\hud"); + entry[0]=group;entry[1]=entry[2]=UINT32_MAX; + entry[3]=handle_base|index;entry[4]=(uint32_t)(uintptr_t)name;entry[5]=(uint32_t)(uintptr_t)root; +} +static void placement(struct hud_placement_definition *p,short x,short y,int highres) { + p->offset.x=x;p->offset.y=y;p->scale.i=1.0f;p->scale.j=2.0f; + p->multiplayer_scaling_flags=highres ? 4 : 0;p->pad=0x1234; +} +static unsigned char *elements(struct mcc_runtime *r,unsigned count,unsigned stride,int highres) { + unsigned char *p=mcc_runtime_allocate(r,count*stride); + unsigned i; + for(i=0;itag_index+slot*32))[5]; +} +static void print_placement(struct hud_placement_definition const *p) { + printf("[%d,%d,%.6f,%.6f,%d,%d]",p->offset.x,p->offset.y,p->scale.i,p->scale.j,p->pad,p->multiplayer_scaling_flags); +} +static int post_hud(struct mcc_runtime *r) { + unsigned char *expected=malloc(r->used); + unsigned i,n; + int ok=1; + assert(expected);memcpy(expected,r->tags,r->used); + for(i=0;ireport.tag_count;i++) { + uint32_t const *entry=(void *)(r->tag_index+i*32); + unsigned char *p=(void *)(uintptr_t)entry[5],*block; + uint32_t count; + if(entry[0]=='unhi') { + memset(expected+(p-r->tags)+0xF4+0x58,0,12); + memset(expected+(p-r->tags)+0x1E4+0x58,0,12); + block=mcc_hud_block(r,p+0x3CC,0x144,&count);assert(block); + for(n=0;ntags)+n*0x144+0x7C+0x58,0,12); + } else if(entry[0]=='wphi') { + block=mcc_hud_block(r,p+0x6C,0xB4,&count);assert(block); + for(n=0;ntags)+n*0xB4+0x24+0x58,0,12); + } + if(entry[0]=='unhi' || entry[0]=='wphi' || entry[0]=='grhi' || entry[0]=='hudg') + ok=ok && mcc_hud(r,entry[0],p); + } + ok=ok && !memcmp(expected,r->tags,r->used);free(expected);return ok; +} +int main(int argc,char **argv) { + struct mcc_runtime r={0}; + struct bitmap_group *bitmaps[2]; + struct weapon_hud_interface_definition *weapons[2]; + struct hud_globals_definition *globals[2]; + unsigned char *digits[2],*blocks[2],*items[2],*grenades[2]; + unsigned slots[2],i,j,count,original_used; + unsigned char *original; + int reverse,half,highres,renamed,ok,post_ok=0; + char const *kind,*sharing; + if(argc!=7 && argc!=9)return 2; + kind=argv[1];sharing=argv[2];reverse=atoi(argv[3]);half=atoi(argv[4]);highres=atoi(argv[5]);renamed=atoi(argv[6]); + handle_base=renamed ? 0xF2000000u : 0xE1000000u; + r.capacity=65536;r.tags=calloc(1,r.capacity);assert(r.tags); + r.tag_index=mcc_runtime_allocate(&r,8*32);r.report.tag_count=!strcmp(kind,"globals") ? 5 : 4; + slots[0]=reverse ? 1 : 0;slots[1]=reverse ? 0 : 1; + for(i=0;i<2;i++) { + bitmaps[i]=mcc_runtime_allocate(&r,sizeof(*bitmaps[i])); + bitmaps[i]->flags=i && half ? 0x10 : 0; + tag(&r,2+i,'bitm',bitmaps[i],renamed); + } + if(!strcmp(kind,"bitmaps") || !strcmp(kind,"invalidcount")) { + memcpy(r.tag_index,r.tag_index+64,64); + for(i=0;i<2;i++)put_word(r.tag_index+i*32+12,handle_base|i); + r.report.tag_count=!strcmp(kind,"bitmaps") ? 2 : !strcmp(sharing,"overflow") ? 65536 : 0; + } else if(!strcmp(kind,"globals")) { + struct weapon_hud_interface_definition *empty=mcc_runtime_allocate(&r,sizeof(*empty)); + empty->parent_hud.index=NONE;tag(&r,4,'wphi',empty,renamed); + for(i=0;i<2;i++) { + globals[i]=mcc_runtime_allocate(&r,sizeof(*globals[i])); + placement(&globals[i]->messaging.placement,0,120,highres); + globals[i]->waypoint.top_offset=120; + globals[i]->damage_indicators.top_offset=120; + globals[i]->defaults.default_weapon_hud.group_tag='wphi'; + globals[i]->defaults.default_weapon_hud.index=handle_base|4; + } + if(!strcmp(sharing,"root"))globals[1]=globals[0]; + for(i=0;i<2;i++)tag(&r,slots[i],'hudg',globals[i],renamed); + } else if(!strcmp(kind,"digits")) { + for(i=0;i<2;i++) { + digits[i]=mcc_runtime_allocate(&r,0x64);digits[i][0x11]=12;digits[i][0x14]=4; + } + if(!strcmp(sharing,"root"))digits[1]=digits[0]; + for(i=0;i<2;i++)tag(&r,slots[i],'hud#',digits[i],renamed); + } else if(!strcmp(kind,"unit")) { + static unsigned const placements[]={0x24,0x8C,0xF4,0x17C,0x1E4,0x26C,0x2D4}; + for(i=0;i<2;i++) { + unsigned char *aux=mcc_runtime_allocate(&r,0x84),*meter=mcc_runtime_allocate(&r,0x144); + grenades[i]=mcc_runtime_allocate(&r,0x56C); + for(j=0;jscale.j=1; + p=(void *)(grenades[i]+0x8C);placement(p,164,2,0);p->scale.j=1; + p=(void *)(grenades[i]+0xF4);placement(p,(short)(214+2*i),6,0);p->scale.j=1; + put_word(grenades[i]+0x54,UINT32_MAX);put_word(grenades[i]+0xBC,UINT32_MAX); + grenades[i][0x138]=grenades[i][0x139]=1; + items[i]=elements(&r,1,0x88,highres); + put_word(grenades[i]+0x158,handle_base|(2+i)); + put_word(grenades[i]+0x15C,1); + } + if(!strcmp(sharing,"block"))items[1]=items[0]; + for(i=0;i<2;i++) { + put_word(grenades[i]+0x160,(uint32_t)(uintptr_t)items[i]); + tag(&r,slots[i],'grhi',grenades[i],renamed); + } + } else { + for(i=0;i<2;i++) { + weapons[i]=mcc_runtime_allocate(&r,sizeof(*weapons[i])); + weapons[i]->parent_hud.index=NONE; + } + if(!strcmp(kind,"static") || !strcmp(kind,"meter")) { + for(i=0;i<2;i++) { + blocks[i]=mcc_runtime_allocate(&r,0xB4); + placement((void *)(blocks[i]+0x24),100,-50,highres); + put_word(blocks[i]+0x54,handle_base|2); + if(!strcmp(kind,"meter"))memset(blocks[i]+0x7C,0xA5,12); + } + if(!strcmp(sharing,"block"))blocks[1]=blocks[0]; + for(i=0;i<2;i++) { + struct tag_block *b=!strcmp(kind,"meter") ? &weapons[i]->meters : &weapons[i]->statics; + b->count=1;b->address=blocks[i]; + } + } else { + unsigned extent=!strcmp(sharing,"prefix") || !strcmp(sharing,"shifted") ? 2 : 1; + for(i=0;i<2;i++) { + blocks[i]=mcc_runtime_allocate(&r,0x68); + items[i]=elements(&r,extent,0x88,highres); + put_word(blocks[i]+0x30,handle_base|(2+i)); + put_word(blocks[i]+0x34,extent); + put_word(blocks[i]+0x38,(uint32_t)(uintptr_t)items[i]); + } + if(!strcmp(sharing,"block") || !strcmp(sharing,"prefix")) + put_word(blocks[1]+0x38,(uint32_t)(uintptr_t)items[0]); + if(!strcmp(sharing,"prefix"))put_word(blocks[0]+0x34,1); + if(!strcmp(sharing,"shifted")) { + put_word(blocks[1]+0x34,1); + put_word(blocks[1]+0x38,(uint32_t)(uintptr_t)(items[0]+0x88)); + } + if(!strncmp(sharing,"shifted-fields",14)) { + unsigned char *overlap=mcc_runtime_allocate(&r,0x90); + placement((void *)overlap,100,-50,0); + placement((void *)(overlap+8),300,3,0); + if(!strcmp(sharing,"shifted-fields-copy")) { + memcpy(items[0],overlap,0x88);memcpy(items[1],overlap+8,0x88); + } else {items[0]=overlap;items[1]=overlap+8;} + for(i=0;i<2;i++)put_word(blocks[i]+0x38,(uint32_t)(uintptr_t)items[i]); + } + if(!strcmp(sharing,"owner"))blocks[1]=blocks[0]; + for(i=0;i<2;i++) { + weapons[i]->overlays.count=1;weapons[i]->overlays.address=blocks[i]; + } + if(!strcmp(sharing,"outside"))put_word(blocks[1]+0x38,(uint32_t)(uintptr_t)(r.tags+r.capacity-1)); + } + if(!strcmp(sharing,"root"))weapons[1]=weapons[0]; + for(i=0;i<2;i++)tag(&r,slots[i],'wphi',weapons[i],renamed); + } + original_used=r.used;original=malloc(original_used);assert(original); + memcpy(original,r.tags,original_used); + if(argc==9) {allocation_fail_at=atoi(argv[7]);heap_fail_at=atoi(argv[8]);} + allocation_calls=warnings=heap_calls=0; + ok=mcc_hud_bitmaps_prepare(&r); + if(ok)post_ok=post_hud(&r); + printf("{\"ok\":%d,\"allocations\":%u,\"warnings\":%u,\"heap_calls\":%u,\"heap_live\":%u," + "\"original_unchanged\":%d,\"post_ok\":%d,\"values\":[",ok,allocation_calls,warnings,heap_calls,heap_live, + !memcmp(original,r.tags,original_used),post_ok); + for(i=0;i<2;i++) { + if(i)putchar(','); + if(!strcmp(kind,"bitmaps") || !strcmp(kind,"invalidcount")) { + printf("0"); + } else if(!strcmp(kind,"globals")) { + struct hud_globals_definition const *g=root(&r,slots[i]); + printf("[");print_placement(&g->messaging.placement); + printf(",%.6f,%d]",g->waypoint.top_offset,g->damage_indicators.top_offset); + } else if(!strcmp(kind,"digits")) { + signed char const *p=root(&r,slots[i]);printf("[%d,%d]",p[0x11],p[0x14]); + } else if(!strcmp(kind,"grenade")) { + unsigned char const *p=root(&r,slots[i]); + items[i]=(void *)(uintptr_t)mcc_hud_word(p+0x160); + print_placement((void *)items[i]); + } else if(!strcmp(kind,"unit")) { + print_placement((void *)((unsigned char *)root(&r,slots[i])+0x24)); + } else { + struct weapon_hud_interface_definition const *w=root(&r,slots[i]); + if(!strcmp(kind,"static") || !strcmp(kind,"meter")) + print_placement((void *)((unsigned char *)(!strcmp(kind,"meter") ? w->meters.address : w->statics.address)+0x24)); + else { + unsigned char const *b=w->overlays.address; + count=mcc_hud_word(b+0x34); + items[i]=(void *)(uintptr_t)mcc_hud_word(b+0x38); + printf("["); + if(ok)for(j=0;j +#include +#include +typedef float real; +typedef int boolean; +typedef struct {short x,y;} point2d; +typedef struct {short x0,y0,x1,y1;} rectangle2d; +struct bitmap_data {short width,height;point2d registration_point;}; +struct hud_placement_definition {point2d offset;short pad;}; +struct unit_datum {long definition_index;}; +struct unit_definition {int unused;}; +struct unit_hud_interface_definition {struct {short corner,pad;} absolute_placement;}; +#define NONE -1 +#define FALSE 0 +#define TRUE 1 +#define MIN(a,b) ((a)<(b)?(a):(b)) +#define MCC_HUD_NATIVE_FRAME 0x4d53 +static boolean mcc_native_view; +static short mcc_weapon_frame=NONE; +static int loaded=1,reads,players=1,valid=1; +static long active=9; +static struct unit_datum unit={8}; +static struct unit_definition definition; +static struct unit_hud_interface_definition hud; +static int mcc_cache_tags_loaded(void) {return loaded;} +static struct unit_datum const *unit_try_and_get(long i) {reads++;return i==7?&unit:NULL;} +static struct unit_definition const *unit_definition_get(long i) {assert(i==8);return &definition;} +static long unit_definition_get_active_hud_index(struct unit_definition const *d,int split) { + assert(d==&definition && split==(players>1));return active; +} +static int local_player_count(void) {return players;} +static void *tag_get(long group,long i) {assert(group=='unhi' && i==9);return &hud;} +static int mcc_cache_contains(void const *p,unsigned size) {assert(p==&hud && size==sizeof(hud));return valid;} +static long halo_screen_width(void) {return 840;} +''' + routines + r''' +int main(void) { + struct hud_placement_definition p={{19,65},0},original; + rectangle2d window={63,36,777,444},viewport={0,0,840,480}; + point2d point; + int anchor,split; + original=p; + for(split=0;split<2;split++) { + players=split+1; + hud.absolute_placement.pad=MCC_HUD_NATIVE_FRAME; + mcc_hud_view_begin(7); + mcc_weapon_frame=FALSE; /* Customized ballistic panel; message uses NONE. */ + for(anchor=0;anchor<4;anchor++) { + assert(!mcc_hud_anchor_point(anchor,&p,NULL,1,&window,&viewport,&point)); + mcc_weapon_frame=NONE; + assert(!mcc_hud_anchor_point(anchor,&p,NULL,1,&window,&viewport,&point)); + } + assert(!memcmp(&p,&original,sizeof(p))); /* No digit/message offset rewrite. */ + assert(!mcc_hud_anchor_point(4,&p,NULL,1,&window,&viewport,&point)); + for(anchor=5;anchor<9;anchor++) + assert(mcc_hud_anchor_point(anchor,&p,NULL,1,&window,&viewport,&point)); + mcc_hud_view_end(); + assert(mcc_hud_anchor_point(0,&p,NULL,1,&window,&viewport,&point)); + assert(point.x==40 && point.y==77); + /* Unknown custom unit layouts retain the component policy. */ + hud.absolute_placement.pad=0;mcc_hud_view_begin(7); + assert(!mcc_native_view); + assert(mcc_hud_anchor_point(0,&p,NULL,1,&window,&viewport,&point)); + p.pad=MCC_HUD_NATIVE_FRAME; + assert(!mcc_hud_anchor_point(0,&p,NULL,1,&window,&viewport,&point)); + p=original;mcc_hud_view_end(); + } + hud.absolute_placement.pad=MCC_HUD_NATIVE_FRAME; + mcc_hud_view_begin(7);mcc_hud_view_begin(NONE);assert(!mcc_native_view); + active=NONE;mcc_hud_view_begin(7);assert(!mcc_native_view);active=9; + valid=0;mcc_hud_view_begin(7);assert(!mcc_native_view);valid=1; + loaded=0;reads=0;mcc_hud_view_begin(7);assert(!mcc_native_view && !reads); + assert(!mcc_hud_anchor_point(0,&p,NULL,1,&window,&viewport,&point)); + mcc_hud_view_end();loaded=1;assert(!mcc_native_view); + return 0; +} +''') + + +def test_scope_encloses_weapon_and_message_draws(): + draw = function((ROOT/'source/interface/hud.c').read_text(), 'hud_draw_screen') + begin = draw.index('mcc_hud_view_begin(') + end = draw.index('mcc_hud_view_end(') + for call in ('hud_render_weapon_interface(', 'hud_render_unit_interface(', 'hud_messaging_update('): + assert begin < draw.index(call) < end + assert 'return' not in draw[begin:end] diff --git a/tools/test_mcc_identity.py b/tools/test_mcc_identity.py new file mode 100644 index 0000000000..1d734dc90b --- /dev/null +++ b/tools/test_mcc_identity.py @@ -0,0 +1,578 @@ +"""MCC content matching uses all digest bytes and never rewrites wire paths.""" +from pathlib import Path +import hashlib +import shutil +import subprocess +import sys +import pytest +from harness import function, structure + +ROOT = Path(__file__).resolve().parents[1] + + +def compile_tool(work, sources): + clang = shutil.which("clang") + if not clang: + pytest.skip("clang required") + exe = work / ("test.exe" if sys.platform == "win32" else "test") + flags = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld", "-D_CRT_SECURE_NO_WARNINGS"] if sys.platform == "win32" else [] + result = subprocess.run([clang, *flags, "-std=gnu89", "-Wall", "-Wextra", "-Werror", + "-I", str(work), "-I", str(ROOT / "port/linux/game"), + *map(str, sources), "-o", str(exe)], capture_output=True, text=True) + assert result.returncode == 0, result.stderr + return exe + + +@pytest.fixture(scope="module") +def sha_tool(tmp_path_factory): + work = tmp_path_factory.mktemp("mcc-sha256") + source = work / "test.c" + source.write_text(r''' +#include "mcc_sha256.h" +#include +#include +int main(int argc,char **argv) { + struct mcc_sha256 hash;unsigned char data[32768],digest[32];size_t count;unsigned i; + FILE *f;if(argc!=3)return 2;f=fopen(argv[1],"rb");if(!f)return 3; + count=(size_t)atoi(argv[2]);if(!count || count>sizeof(data))return 4; + mcc_sha256_begin(&hash); + while((i=(unsigned)fread(data,1,count,f))!=0)mcc_sha256_add(&hash,data,(int)i); + if(ferror(f))return 5;fclose(f);mcc_sha256_end(&hash,digest); + for(i=0;i<32;i++)printf("%02x",digest[i]);return 0; +} +''') + return compile_tool(work, [source, ROOT / "port/linux/game/mcc_sha256.c"]) + + +@pytest.mark.parametrize("data", [b"", b"abc", b"a" * 55, b"a" * 56, b"a" * 64, + b"a" * 65, bytes(range(256)) * 4096], + ids=["empty", "abc", "55-bytes", "56-bytes", "64-bytes", "65-bytes", "1-MiB"]) +@pytest.mark.parametrize("chunk", [1, 63, 32768]) +def test_sha256_vectors(sha_tool, tmp_path, data, chunk): + path = tmp_path / "bytes" + path.write_bytes(data) + result = subprocess.run([str(sha_tool), str(path), str(chunk)], capture_output=True, text=True) + assert result.returncode == 0 + assert result.stdout == hashlib.sha256(data).hexdigest() + + +def test_session_resolution_and_validation(tmp_path): + headers = { + "cseries.h": "#include \ntypedef int boolean;\ntypedef unsigned char byte;\ntypedef unsigned short word;\n#define FALSE 0\n#define TRUE 1\nint csstrcasecmp(char const *,char const *);\nFILE *fixture_fopen(char const *,char const *);\n#define fopen fixture_fopen\n", + "errors.h": "#define _error_silent 0\nvoid error(short,char const *,...);\n", + "interface/ui_widget.h": "#include \nvoid display_error_text_when_main_menu_loaded(wchar_t const *);\n", + "game/game.h": "enum { _game_connection_local, _game_connection_network_client, _game_connection_network_server };\nint game_connection(void);\nvoid network_game_abort(void);\n", + "networking/network_game_globals.h": "void network_game_abort(void);\n", + "networking/network_game_manager.h": "struct network_game {struct {long version;char name[128];} map;unsigned char mcc_content_sha256[32];unsigned char mcc_metadata_sha256[32];};\n", + } + for name, text in headers.items(): + path = tmp_path / name + path.parent.mkdir(exist_ok=True) + path.write_text(text) + source = tmp_path / "test.c" + source.write_text(r''' +#include "cseries.h" +#include "mcc_identity.h" +#include "mcc_precache.h" +#include "mcc_validation.h" +#include +#include "mcc_workshop.h" +#include "networking/network_game_manager.h" +#include +#include +#include +#include +#undef fopen +#define CHECK(x) do{if(!(x)){fprintf(stderr,"line %d: %s\n",__LINE__,#x);return 1;}}while(0) +static struct {char name[64];unsigned char digest[32],metadata[32];unsigned stamp;int invalid_metadata;} files[20]; +static int count,probes,errors,connection,changing,denied,clears,hash_loads,rescan_install; +static int lease,lease_wait,lease_begins,aborts,open_checks,ready_blocked; +void network_game_abort(void){aborts++;} +int mcc_admission_client_begin(struct network_game const *g){(void)g;lease=1;lease_begins++;return 1;} +int mcc_admission_client_status(void){return lease_wait ? 0 : lease;} +int mcc_admission_client_pending(void){return lease>0;} +void mcc_admission_client_clear(void){lease=0;} +void mcc_admission_client_finish(int ready){if(!ready || !ready_blocked)lease=0;} +void mcc_admission_disconnect(void){lease=0;} +static struct mcc_validation_proof cached; +static char const *sidecar; +/* Controlled virtual filesystem, retaining the real sidecar parser/reader. */ +FILE *fixture_fopen(char const *path,char const *mode){ + FILE *file;(void)mode;if(!sidecar || !strstr(path,"workshop_id.txt"))return NULL; + file=tmpfile();if(file){fputs(sidecar,file);rewind(file);}return file; +} +int csstrcasecmp(char const *a,char const *b){while(*a && tolower(*a)==tolower(*b)){a++;b++;}return tolower(*a)-tolower(*b);} +int game_connection(void){return connection;} +void error(short level,char const *format,...){(void)level;(void)format;} +static char last_error[256]; +void display_error_text_when_main_menu_loaded(wchar_t const *text){int k;errors++;for(k=0;text[k] && k<255;k++)last_error[k]=(char)text[k];last_error[k]=0;} +void mcc_share_game_disconnect(void) {} +void mcc_cache_validation_clear(void) {memset(&cached,0,sizeof(cached));} +void mcc_validation_cancel(void) {} +void mcc_cache_precache_clear(void){clears++;} +void mcc_maps_rescan(void){ + if(rescan_install){count=1;strcpy(files[0].name,"mcc_maps\\2899609719\\pat_beavercreek");memset(files[0].digest,42,32);} +} +boolean mcc_maps_workshop_title(char const *id,char *title,unsigned size){(void)id;(void)title;(void)size;return 0;} +short mcc_maps_count(boolean multiplayer){(void)multiplayer;return (short)count;} +char const *mcc_maps_level_name(short i){return files[i].name;} +boolean mcc_level_name(char const *s){return !strncmp(s,"mcc_maps",8);} +static int find(char const *s){int i;for(i=0;i=0){out->files[0].present=1;out->files[0].written_low=files[i].stamp;}return 1; +} +int mcc_content_probe(char const *s,unsigned char digest[32]){ + int i=find(s);probes++;if(i<0)return 0;memcpy(digest,files[i].digest,32); + if(changing)files[i].stamp++;return 1; +} + +struct mcc_validation_check {char name[64];struct mcc_precache_snapshot before;int steps;}; +int mcc_validation_lookup(char const *s,uint32_t *sum,unsigned char digest[32]){ + struct mcc_precache_snapshot now; + if(strcmp(s,cached.name) || !mcc_precache_snapshot(s,&now) || memcmp(&now,&cached.files,sizeof(now)))return 0; + if(sum)*sum=cached.checksum;if(digest)memcpy(digest,cached.digest,32);return 1; +} +int mcc_validation_publish(char const *s,struct mcc_validation_proof const *proof){ + struct mcc_precache_snapshot now; + if(strcmp(s,proof->name) || !mcc_precache_snapshot(s,&now) || memcmp(&now,&proof->files,sizeof(now)))return 0; + cached=*proof;return 1; +} +int mcc_validation_request(char const *s,uint32_t *sum,unsigned char digest[32]){ + struct mcc_validation_proof proof;struct mcc_precache_snapshot after; + if(mcc_validation_lookup(s,sum,digest))return 1; + memset(&proof,0,sizeof(proof));strcpy(proof.name,s);proof.checksum=123; + if(!mcc_precache_snapshot(s,&proof.files) || !mcc_content_probe(s,proof.digest) || + !mcc_precache_snapshot(s,&after) || memcmp(&after,&proof.files,sizeof(after)))return -1; + if(sum)*sum=123;if(digest)memcpy(digest,proof.digest,32);return mcc_validation_publish(s,&proof); +} +struct mcc_validation_check *mcc_validation_check_begin(char const *s,char const *dir){ + struct mcc_validation_check *check=malloc(sizeof(*check));(void)dir; + if(!check)return NULL;memset(check,0,sizeof(*check));strcpy(check->name,s); + mcc_precache_snapshot(s,&check->before);open_checks++;return check; +} +int mcc_validation_check_step(struct mcc_validation_check *check,struct mcc_validation_proof *proof,char *reason,size_t size){ + struct mcc_precache_snapshot after;(void)reason;(void)size; + if(!check->steps++)return 0; + memset(proof,0,sizeof(*proof));strcpy(proof->name,check->name);proof->checksum=123; + if(!mcc_content_probe(check->name,proof->digest) || !mcc_precache_snapshot(check->name,&after) || + memcmp(&after,&check->before,sizeof(after)))return -1; + proof->files=after;return 1; +} +void mcc_validation_check_end(struct mcc_validation_check *check){if(check){open_checks--;free(check);}} +/* Most legacy cases await the real asynchronous state machine. Separate cases + * below observe each pending boundary before allowing the next frame. */ +static int complete_accept(struct network_game const *game){ + int before=aborts,n; + if(!mcc_identity_accept(game))return 0; + for(n=0;n<200 && mcc_identity_pending(NULL);n++)mcc_identity_update(); + return !mcc_identity_pending(NULL) && aborts==before; +} +#define mcc_identity_accept(game) complete_accept(game) +int mcc_resources_fingerprint(struct mcc_runtime *r,unsigned char digest[32]){ + (void)r;hash_loads++;memcpy(digest,files[0].digest,32);return 1; +} +int main(void){ + struct network_game game,copy;unsigned char wanted[32];int old,i; + memset(&game,0,sizeof(game));memset(wanted,42,32); + strcpy(game.map.name,"mcc_maps\\Host\\a10");memcpy(game.mcc_content_sha256,wanted,32); + count=1;strcpy(files[0].name,"mcc_maps\\Client\\a10");memcpy(files[0].digest,wanted,32); + CHECK(mcc_identity_accept(&game));CHECK(!strcmp(game.map.name,"mcc_maps\\Host\\a10")); + CHECK(!strcmp(mcc_identity_local_name(game.map.name),files[0].name)); + old=probes;CHECK(mcc_identity_check(game.map.name));CHECK(probes==old); + /* Full loading rehashes the open map/resources, even with unchanged metadata. */ + connection=1;CHECK(mcc_identity_loaded(game.map.name,NULL));CHECK(hash_loads==1); + files[0].digest[31]^=1;CHECK(!mcc_identity_loaded(game.map.name,NULL)); + files[0].stamp++;CHECK(!mcc_identity_check(game.map.name)); + CHECK(!mcc_identity_accept(&game));CHECK(!strcmp(mcc_identity_local_name(game.map.name),game.map.name)); + files[0].digest[31]^=1;CHECK(mcc_identity_accept(&game)); + /* Duplicate fallback matches are refused, but an exact verified path wins. */ + files[1]=files[0];strcpy(files[1].name,"mcc_maps\\Duplicate\\a10");count=2; + CHECK(!mcc_identity_accept(&game));strcpy(files[1].name,game.map.name); + CHECK(mcc_identity_accept(&game));CHECK(!strcmp(mcc_identity_local_name(game.map.name),game.map.name)); + files[1].digest[0]^=1;files[1].stamp++;CHECK(mcc_identity_accept(&game)); + CHECK(!strcmp(mcc_identity_local_name(game.map.name),files[0].name)); + changing=1;CHECK(!mcc_identity_accept(&game));changing=0; + denied=1;CHECK(!mcc_identity_accept(&game));denied=0; + /* No zero digest, traversal, or stale alias after a legacy map/disconnect. */ + memset(game.mcc_content_sha256,0,32);CHECK(!mcc_identity_accept(&game)); + memcpy(game.mcc_content_sha256,wanted,32);strcpy(game.map.name,"mcc_maps\\..\\a10"); + CHECK(!mcc_identity_accept(&game));strcpy(game.map.name,"mcc_maps\\Host\\a10"); + CHECK(mcc_identity_accept(&game));mcc_identity_disconnect(); + CHECK(!strcmp(mcc_identity_local_name(game.map.name),game.map.name)); + CHECK(!mcc_identity_loaded(game.map.name,NULL));connection=0;CHECK(mcc_identity_loaded(game.map.name,NULL)); + strcpy(game.map.name,"levels\\test\\bloodgulch\\bloodgulch"); + memset(game.mcc_content_sha256,0,32);CHECK(mcc_identity_accept(&game)); + /* Prepare before opening the lobby: even a slow fingerprint must not be + * repeated by the first settings send while a client waits to join. */ + strcpy(game.map.name,files[0].name);game.map.version=123;old=probes; + CHECK(mcc_identity_prepare_host(game.map.name));CHECK(probes==old+1); + CHECK(mcc_identity_host_settings(&game,sizeof(game),©)==©);CHECK(probes==old+1); + CHECK(!memcmp(copy.mcc_content_sha256,wanted,32));CHECK(!game.mcc_content_sha256[0]); + CHECK(mcc_identity_host_settings(&game,sizeof(game),©));CHECK(probes==old+1); + /* The local admission reuses this exact snapshot, but neither a changed + * file nor a different wire digest can use it. Loading still rehashes. */ + CHECK(mcc_identity_accept(©));CHECK(probes==old+1); + files[0].stamp++;CHECK(mcc_identity_accept(©));CHECK(probes==old+2); + files[0].stamp--;copy.mcc_content_sha256[31]^=1; + CHECK(!mcc_identity_accept(©));CHECK(probes>old+2); + CHECK(mcc_validation_request(game.map.name,NULL,NULL)==1); + CHECK(mcc_identity_host_settings(&game,sizeof(game),©)); + old=probes; + files[0].stamp++;CHECK(!mcc_identity_host_settings(&game,sizeof(game),©));CHECK(probes==old); + CHECK(mcc_identity_prepare_host(game.map.name));CHECK(probes==old+1); + CHECK(mcc_identity_host_settings(&game,sizeof(game),©)); + mcc_identity_disconnect();changing=1;CHECK(!mcc_identity_host_settings(&game,sizeof(game),©));changing=0; + CHECK(!mcc_identity_host_settings(&game,sizeof(game)-1,©)); + /* Invalid or unreadable preparation drops a previously cached identity. */ + CHECK(mcc_identity_prepare_host(game.map.name));old=probes; + denied=1;CHECK(!mcc_identity_prepare_host(game.map.name));denied=0; + CHECK(!mcc_identity_host_settings(&game,sizeof(game),©));CHECK(probes==old); + CHECK(mcc_identity_prepare_host(game.map.name));CHECK(probes==old); + CHECK(mcc_identity_host_settings(&game,sizeof(game),©)); + CHECK(!mcc_identity_prepare_host("custom_maps/a10")); + CHECK(!mcc_identity_prepare_host("levels/test/bloodgulch/bloodgulch")); + /* Bound same-filename work before any fallback fingerprints. */ + strcpy(game.map.name,"mcc_maps\\Host\\a10");memcpy(game.mcc_content_sha256,wanted,32);count=17; + for(i=0;i\ntypedef int boolean;\ntypedef unsigned char byte;\n") + source = tmp_path / "settings.c" + source.write_text('#include "'+(ROOT / "port/linux/include/halo_port_limits.h").as_posix()+'"\n'+r''' +#include +#include +#include +#include +#include "mcc_workshop.h" +typedef int boolean;typedef unsigned char byte;typedef uint16_t word; +int mcc_maps_workshop_title(char const *id,char *title,unsigned size) { + (void)id;(void)title;(void)size;return 0; +} +#define TRUE 1 +#define FALSE 0 +#define NETWORK_CLIENT_MESSAGE_HANDLER_FILE "test" +#define NETWORK_GAME_MESSAGE_VERSION 2 +#define _network_game_client_state_pregame 3 +#define _message_server_game_settings_update 4 +#define _network_game_packet_class_pregame 5 +#define match_assert(file,line,value) ((void)0) +#define network_event(...) ((void)0) +#define csmemcpy memcpy +#define csmemset memset +#define CHECK(x) do{if(!(x)){fprintf(stderr,"line %d: %s\n",__LINE__,#x);return 1;}}while(0) +struct network_game {union {byte previous[1030];struct {char name[128];} map;};byte mcc_content_sha256[32];byte mcc_metadata_sha256[32];}; +struct network_game_client {int dummy;};struct transport_address {int host;}; +static int applies,decodes,state=3;static struct network_game received; +static struct network_game network_game_client_settings_staging; +static long network_game_client_settings_staging_size,network_game_client_settings_staging_total; +static boolean network_game_client_game_settings_updated(struct network_game_client *c,struct network_game *g){(void)c;received=*g;applies++;return 1;} +static boolean network_game_client_address_matches_server(struct network_game_client *c,struct transport_address *a){(void)c;return a->host;} +static int network_game_client_get_state(struct network_game_client *c,void *unused){(void)c;(void)unused;return state;} +''' + structure(native, "message_server_game_settings_update") + r''' +static struct message_server_game_settings_update decoded; +static boolean decode_network_game_message(void *out,word *m,short *size,short *type,short *version,int cls){ + (void)m;(void)size;(void)type;(void)version;(void)cls;decodes++;memcpy(out,&decoded,sizeof(decoded));return 1; +} +''' + function(native, "network_game_client_receive_game_settings_piece") + "\n" + + function(native, "network_game_client_handle_message_server_game_settings_update") + r''' +int main(void){ + struct network_game_client c;struct transport_address address={0};word packet[4]={0}; + struct network_game original;struct mcc_workshop_item item,back;unsigned offset,n; + memset(&original,42,sizeof(original)); + memset(original.mcc_metadata_sha256,17,sizeof(original.mcc_metadata_sha256)); + strcpy((char *)original.previous,"mcc_maps\\2899609719\\pat_beavercreek"); + strcpy(item.id,"2899609719");strcpy(item.title,"Better Creek"); + mcc_workshop_wire_pack((char *)original.previous,&item); + memset(&decoded,0,sizeof(decoded));decoded.total_size=sizeof(original); + CHECK(network_game_client_handle_message_server_game_settings_update(&c,packet,8,&address)); + CHECK(!decodes && !applies);address.host=1; + for(offset=0;offsetsizeof(decoded.data))n=sizeof(decoded.data); + decoded.offset=(word)offset;decoded.length=(word)n;memcpy(decoded.data,(byte *)&original+offset,n); + CHECK(network_game_client_handle_message_server_game_settings_update(&c,packet,8,&address)); + CHECK(applies==(offset+n==sizeof(original))); + } + CHECK(!memcmp(&received,&original,sizeof(original))); + CHECK(mcc_workshop_wire_unpack((char const *)received.previous,&back)); + CHECK(!strcmp(back.id,item.id) && !strcmp(back.title,item.title)); + decoded.total_size-=32;CHECK(!network_game_client_receive_game_settings_piece(&c,&decoded)); + decoded.total_size=sizeof(original);decoded.offset=sizeof(original)-1;decoded.length=2; + CHECK(!network_game_client_receive_game_settings_piece(&c,&decoded)); + decoded.offset=0;decoded.length=sizeof(decoded.data)+1; + CHECK(!network_game_client_receive_game_settings_piece(&c,&decoded)); + decoded.offset=20;decoded.length=1;CHECK(network_game_client_receive_game_settings_piece(&c,&decoded)); + CHECK(applies==1 && !network_game_client_settings_staging_size); + state=0;CHECK(network_game_client_handle_message_server_game_settings_update(&c,packet,8,&address)); + CHECK(applies==1);return 0; +} +''') + exe = compile_tool(tmp_path, [source, ROOT / "port/linux/game/mcc_workshop.c", + ROOT / "port/linux/game/mcc_package.c"]) + result = subprocess.run([str(exe)], capture_output=True, text=True) + assert result.returncode == 0, result.stderr + + +def test_settings_origin_change_restarts_only_mcc_admission(tmp_path): + native = (ROOT / "source/networking/network_client_manager.c").read_text() + source = tmp_path / "settings.c" + source.write_text(r''' +#include +#include +typedef int boolean; +#define TRUE 1 +#define FALSE 0 +#define MAXIMUM_NETWORK_MACHINE_COUNT 128 +#define MAXIMUM_NUMBER_OF_PLAYERS 128 +#define NUMBER_OF_GAME_DIFFICULTY_LEVELS 4 +#define VALID_INDEX(i,n) ((unsigned)(i)<(unsigned)(n)) +#define match_assert(...) ((void)0) +#define network_event(...) ((void)0) +#define csstrcmp strcmp +#define csmemcpy memcpy +#define _error_network_failed_to_join_game 1 +#define CHECK(x) do{if(!(x)){fprintf(stderr,"line %d: %s\n",__LINE__,#x);return 1;}}while(0) +struct network_game {int machine_count,player_count,maximum_players,cooperative_flags,difficulty; + struct {char name[128];long version;} map;unsigned char mcc_content_sha256[32],mcc_metadata_sha256[32];int local_data;}; +struct network_game_client {struct network_game game;}; +static int admits,precache,present; +static int third_person_match_flags_valid(int flags){return flags==0;} +static int network_game_client_map_name_is_valid(char const *name,unsigned size){return memchr(name,0,size)!=NULL;} +static int network_game_client_game_record_is_valid(struct network_game *game){(void)game;return 1;} +static int mcc_level_name(char const *name){return !strncmp(name,"mcc_maps\\",9);} +static int mcc_identity_accept(struct network_game *game){(void)game;admits++;return 1;} +static int network_game_is_splitscreen_local(void){return 0;} +static int cache_files_map_present(char const *name,unsigned long version){(void)name;(void)version;present++;return 1;} +static int cache_files_map_plays_multiplayer(char const *name,char *build){(void)name;(void)build;return 1;} +static void cache_files_show_multiplayer_unavailable(char const *name,char const *build){(void)name;(void)build;} +static void display_error_when_main_menu_loaded(int error){(void)error;} +static void main_set_multiplayer_map_name(char const *name){(void)name;precache++;} +''' + function(native, "network_game_client_game_settings_updated") + r''' +int main(void){ + struct network_game_client client;struct network_game next; + memset(&client,0,sizeof(client));client.game.maximum_players=4;client.game.local_data=123; + strcpy(client.game.map.name,"mcc_maps\\Host\\a10");next=client.game; + CHECK(network_game_client_game_settings_updated(&client,&next));CHECK(!admits && !present && !precache); + next.map.name[64]=7;next.local_data=99; + CHECK(network_game_client_game_settings_updated(&client,&next));CHECK(admits==1 && present==1 && precache==1); + CHECK(client.game.local_data==123 && client.game.map.name[64]==7); + CHECK(network_game_client_game_settings_updated(&client,&next));CHECK(admits==1); + next.mcc_metadata_sha256[31]=1;CHECK(network_game_client_game_settings_updated(&client,&next));CHECK(admits==2); + strcpy(next.map.name,"custom_maps\\a10");CHECK(network_game_client_game_settings_updated(&client,&next));CHECK(admits==3); + next.map.name[64]++;CHECK(network_game_client_game_settings_updated(&client,&next));CHECK(admits==3); + strcpy(next.map.name,"levels\\test\\bloodgulch\\bloodgulch");CHECK(network_game_client_game_settings_updated(&client,&next));CHECK(admits==4); + next.map.name[64]++;CHECK(network_game_client_game_settings_updated(&client,&next));CHECK(admits==4); + return 0; +} +''') + exe = compile_tool(tmp_path, [source]) + result = subprocess.run([str(exe)], capture_output=True, text=True) + assert result.returncode == 0, result.stderr diff --git a/tools/test_mcc_lifecycle.py b/tools/test_mcc_lifecycle.py new file mode 100644 index 0000000000..dd3ec06d78 --- /dev/null +++ b/tools/test_mcc_lifecycle.py @@ -0,0 +1,455 @@ +"""Exercise real scenario-load dispatch against a failed initial MCC BSP.""" +from pathlib import Path +import shutil +import subprocess +import sys + +import pytest +from harness import function + +ROOT = Path(__file__).resolve().parents[1] + + +def test_explicit_campaign_completion_is_host_owned_and_has_no_retained_state(tmp_path): + from test_mcc_identity import compile_tool + adapter = function((ROOT / "port/linux/game/mcc_main.c").read_text(), "mcc_main_campaign_won") + source = tmp_path / "campaign_completion.c" + source.write_text(r''' +#include +#include +typedef int boolean; +#define FALSE 0 +#define TRUE 1 +#define _error_silent 0 +#define _game_connection_local 0 +#define _game_connection_network_server 1 +#define _game_connection_network_client 2 +struct network_game {struct {char name[64];} map;}; +static struct network_game game={{"mcc_maps\\Host\\z10"}}; +static int active=1,type,enabled=1,connection,state=1,lookups,queued,persistent,rounds,errors; +static char selected[64]; +static int completions; +static int game_difficulty_level_get(void){return 2;} +static void mcc_progress_complete(char const *name,short difficulty){ + if(difficulty==2 && !strcmp(name,connection==1 ? game.map.name : "mcc_maps\\Local\\z10"))completions++; +} +static int mcc_cache_tags_loaded(void){return active;} +static int mcc_cache_scenario_type(void){return type;} +static int config_boolean(char const *key){(void)key;return enabled;} +static int game_connection(void){return connection;} +static struct network_game *network_game_get_game(void){return &game;} +static char const *main_get_map_name(void){return "mcc_maps\\Local\\z10";} +static int mcc_maps_next_mission(char const *name,char next[64]) { + lookups++; + if(strcmp(name,connection==1 ? game.map.name : main_get_map_name()))return -1; + strcpy(next,"mcc_maps\\Pack\\a10");return state; +} +static void error(int severity,char const *message,...){(void)severity;(void)message;} +static void mcc_error_text(char const *name,char const *reason,wchar_t *text,int size){(void)name;(void)reason;(void)size;text[0]=0;} +static void display_error_text_deferred(wchar_t const *text,int controller){(void)text;(void)controller;errors++;} +static void mcc_ui_network_campaign_won(char const *next){rounds++;strcpy(selected,next ? next : "lobby");} +static void main_set_map_name(char const *next){strcpy(selected,next);} +static void main_disallow_persistent_storage(void){persistent++;} +static void main_goto_main_menu(void){queued++;} +''' + adapter + r''' +int main(void) { + int i; + for(i=0;i<3;i++) { + active=i!=0;type=i==1;enabled=i!=2; + if(mcc_main_campaign_won() || lookups || queued || rounds || completions)return 1; + } + active=enabled=1;type=0; + if(!mcc_main_campaign_won() || strcmp(selected,"mcc_maps\\Pack\\a10") || persistent!=1 || queued)return 2; + state=2;if(!mcc_main_campaign_won() || queued!=1)return 3; + state=-1;if(!mcc_main_campaign_won() || queued!=2 || errors!=1)return 4; + state=0;if(!mcc_main_campaign_won() || queued!=3)return 5; + connection=1;state=1; + if(!mcc_main_campaign_won() || rounds!=1 || strcmp(selected,"mcc_maps\\Pack\\a10") || persistent!=1)return 6; + state=2;if(!mcc_main_campaign_won() || rounds!=2 || strcmp(selected,"lobby"))return 7; + state=-1;if(!mcc_main_campaign_won() || rounds!=3 || errors!=2)return 8; + connection=2;i=lookups; + if(!mcc_main_campaign_won() || lookups!=i || rounds!=3 || queued!=3 || completions!=7)return 9; + /* Switching back to an unaffected family cannot retain campaign state. */ + active=0;connection=0;if(mcc_main_campaign_won() || lookups!=i)return 10; + return 0; +} +''') + binary = compile_tool(tmp_path, [source]) + result = subprocess.run([str(binary)], capture_output=True, text=True, timeout=10) + assert result.returncode == 0, result.stdout + result.stderr + + +def test_network_mcc_load_failure_schedules_abort_without_initializing_players(tmp_path): + from test_mcc_identity import compile_tool + + manager = (ROOT / "source/networking/network_game_manager.c").read_text() + adapter = (ROOT / "port/linux/game/mcc_main.c").read_text() + code = r''' +#include +#include +#include "mcc_errors.h" +#define custom_edition_level_name(p) (!strncmp(p,"custom_maps\\",12)) +#define custom_edition_cache_load_error(p) "CE fixture load failed" +#include +typedef int boolean; +#define TRUE 1 +#define FALSE 0 +#define _error_silent 2 +#define _game_connection_network_client 1 +#define _game_connection_network_server 2 +#define _game_connection_film_playback 3 +#define NETWORK_GAME_PLAYER_SLOTS 2 +#define match_assert(a,b,c) ((void)0) +#define csstrncpy strncpy +struct game_options {char map_name[64];int difficulty,random_seed;}; +struct player {int player_list_index;}; +struct network_game { + struct {char name[64];} map; + struct {int game_engine_index;} variant; + struct {int game_objects_loaded;} local_data; + struct player players[2]; + int difficulty,random_seed,variant_options; +}; +static int fatal,aborts,popups,clears,menus,initialized,spawned,refuse=1,connection=1; +static void error(int priority,char const *format,...) {(void)format;if(priority==0)fatal++;} +static void game_options_new(struct game_options *p) {memset(p,0,sizeof(*p));} +static int game_connection(void) {return connection;} +static int network_game_get_random_seed(void) {return 1;} +static void game_precache_new_map(char *p,int v) {(void)p;(void)v;} +static void main_menu_unload(void) {} +static int game_in_progress(void) {return 0;} +static int game_map_loaded(void) {return 0;} +static void game_dispose_from_old_map(void) {} +static void game_unload(void) {} +static void game_set_game_variant(void *p) {(void)p;} +static void game_set_game_variant_options(void *p) {(void)p;} +static int game_load(struct game_options *p) {(void)p;return !refuse;} +static void game_initialize_for_new_map(void) {initialized++;} +static int network_player_is_valid(struct player *p) {(void)p;return 1;} +static int network_game_spawn_player(struct player *p) {(void)p;spawned++;return 1;} +static int mcc_level_name(char const *p) {return !strncmp(p,"mcc_maps\\",9);} +static void errors_clear(void) {clears++;} +static void display_error_text_when_main_menu_loaded(wchar_t const *p) {(void)p;popups++;} +static void network_game_abort(void) {aborts++;} +static void main_goto_main_menu(void) {menus++;} +''' + function(adapter, "mcc_main_network_load_failed") + function(manager, "network_game_create_game_objects") + r''' +#define CHECK(c) do{if(!(c)){fprintf(stderr,"line%d\n",__LINE__);return 1;}}while(0) +int main(void) { + struct network_game game={0}; + for(connection=1;connection<=2;connection++) { + strcpy(game.map.name,"mcc_maps\\Floodslayer\\c10_flood"); + game.local_data.game_objects_loaded=1; + CHECK(!network_game_create_game_objects(&game)); + CHECK(!game.local_data.game_objects_loaded && !fatal && !initialized && !spawned); + CHECK(aborts==connection && popups==connection && clears==connection && menus==connection); + } + game.local_data.game_objects_loaded=0; + strcpy(game.map.name,"levels\\a10\\a10"); + CHECK(!network_game_create_game_objects(&game));CHECK(fatal==1 && aborts==2); + strcpy(game.map.name,"custom_maps\\test"); + CHECK(!network_game_create_game_objects(&game));CHECK(fatal==2 && aborts==2); + strcpy(game.map.name,"mcc_maps\\good");refuse=0; + CHECK(network_game_create_game_objects(&game)); + CHECK(initialized==1 && spawned==2 && aborts==2 && clears==2); + return 0; +} +''' + source = tmp_path / "network_failure.c" + source.write_text(code) + binary = compile_tool(tmp_path, [source, ROOT / "port/linux/game/mcc_errors.c"]) + subprocess.run([str(binary)], check=True, capture_output=True, text=True) + + +def test_mcc_completion_defers_menu_load_without_starting_xbox_credits(tmp_path): + compiler = shutil.which("clang") or shutil.which("cc") + if not compiler: + pytest.skip("a C compiler is required") + native = (ROOT / "source/main/main.c").read_text() + adapter = (ROOT / "port/linux/game/mcc_main.c").read_text() + source = r''' +typedef int boolean; +#define TRUE 1 +#define FALSE 0 +#define _error_silent 0 +static int active,queued,loaded,movies,logged; +static boolean mcc_cache_tags_loaded(void) {return active;} +static void error(int level,char const *text,...) {(void)level;(void)text;logged++;} +static void main_goto_main_menu(void) {queued++;} +static void main_menu_load(void) {loaded++;active=0;} +static void game_end_credits_start(void) {movies++;} +''' + function(adapter, "mcc_main_map_completed") + function(native, "main_roll_credits") + r''' +int main(void) { + int i; + /* Repeated MCC loads and completion do not retain transition state. */ + for(i=0;i<2;i++) { + active=1;main_roll_credits(); + if(queued!=i+1 || loaded!=i || movies || logged!=i+1 || !active)return 1; + /* The main loop performs the queued transition, after this returns. */ + main_menu_load(); + } + /* With MCC inactive, both Xbox and CE retain the exact native sequence. */ + for(i=0;i<2;i++) { + main_roll_credits(); + if(queued!=2 || loaded!=3+i || movies!=1+i || logged!=3+i)return 2; + } + return 0; +} +''' + path = tmp_path / "completion.c" + path.write_text(source) + binary = tmp_path / ("completion.exe" if sys.platform == "win32" else "completion") + flags = (["--target=i686-pc-windows-msvc", "-fuse-ld=lld"] if sys.platform == "win32" else []) + built = subprocess.run([compiler, *flags, "-std=gnu89", "-Wall", "-Wextra", "-Werror", + str(path), "-o", str(binary)], capture_output=True, text=True) + assert built.returncode == 0, built.stderr + result = subprocess.run([str(binary)], capture_output=True, text=True, timeout=10) + assert result.returncode == 0, result.stdout + result.stderr + + +def test_initial_mcc_bsp_failure_balances_state_and_preserves_legacy_rollback(tmp_path): + """Exercise real BSP switching with and without the MCC dispatch active.""" + compiler = shutil.which("clang") or shutil.which("cc") + if not compiler: + pytest.skip("a C compiler is required") + current = function((ROOT / "source/scenario/scenario.c").read_text(), "scenario_switch_structure_bsp") + prefix = r''' +#include +#include +#include +typedef int boolean; +#define FALSE 0 +#define TRUE 1 +#define NONE (-1) +#define _error_silent 0 +#define _error_immediate 1 +#define MAXIMUM_STRUCTURE_BSPS_PER_SCENARIO 32 +#define match_assert(file,line,condition) do {if(!(condition))exit(20);}while(0) +#define TAG_BLOCK_GET_ELEMENT(block,index,type) ((type *)(block)->address+(index)) +struct block {int count;void *address;}; +struct scenario_structure_bsp_reference {struct {int index;} structure_bsp;}; +struct collision_bsp {int unused;}; +struct bsp3d {int unused;}; +struct structure_bsp {struct block collision_bsp;}; +static struct {struct block structure_bsp_references;} scenario,*global_scenario=&scenario; +static struct {int structure_bsp_index;} globals,*scenario_globals=&globals; +static struct scenario_structure_bsp_reference references[2]={{{0}},{{1}}}; +static struct collision_bsp collision; +static struct structure_bsp bsp={{1,&collision}}; +static struct structure_bsp *global_structure_bsp; +static struct collision_bsp *global_collision_bsp; +static struct bsp3d *global_bsp3d; +static short global_structure_bsp_index; +static int mcc,mode; +static struct results { + int stopped,started,collision_disabled,collision_enabled,disconnects,reconnects, + unloads,loads,verifies,modal,silent,menu,returned,index,scenario_index,pointers; +} observed; +static int mcc_cache_tags_loaded(void) {return mcc;} +static void main_stop_time(void) {observed.stopped++;} +static void main_start_time(void) {observed.started++;} +static void collision_log_enable(int enabled) { + if(enabled)observed.collision_enabled++;else observed.collision_disabled++; +} +static void scenario_call_disconnect_from_structure_bsp_procs(void) {observed.disconnects++;} +static void scenario_call_reconnect_to_structure_bsp_procs(void) {observed.reconnects++;} +static void scenario_structure_bsp_unload(struct scenario_structure_bsp_reference *reference) { + (void)reference;observed.unloads++; +} +static int scenario_structure_bsp_load(struct scenario_structure_bsp_reference *reference) { + (void)reference;observed.loads++; + return mode==0 || mode==4 || (mode==2&&observed.loads==2); +} +static struct structure_bsp *structure_bsp_definition_get(int index) {(void)index;return &bsp;} +static int structure_bsp_port_verify(struct structure_bsp *value) { + (void)value;observed.verifies++;return mode!=4 || observed.verifies>1; +} +static void structure_culling_structure_bsp_loaded(void) {} +static void main_goto_main_menu(void) {observed.menu++;} +static void error(int priority,char const *format,...) { + (void)format;if(priority==_error_immediate)observed.modal++;else observed.silent++; +} +static void reset(int old) { + memset(&observed,0,sizeof(observed)); + scenario.structure_bsp_references.count=2;scenario.structure_bsp_references.address=references; + global_structure_bsp_index=globals.structure_bsp_index=(short)old; + global_structure_bsp=old==NONE?NULL:&bsp; + global_collision_bsp=old==NONE?NULL:&collision; + global_bsp3d=old==NONE?NULL:(void *)&collision; +} +static void finish(int result) { + observed.returned=result;observed.index=global_structure_bsp_index; + observed.scenario_index=globals.structure_bsp_index; + observed.pointers=!!global_structure_bsp+!!global_collision_bsp+!!global_bsp3d; +} +''' + current + r''' +int main(void) { + int old,requested; + for(old=NONE;old<=0;old++) + for(requested=NONE;requested<=2;requested++)for(mode=0;mode<=4;mode++) { + struct results expected; + /* Xbox and CE share the inactive MCC gate. Their preserved flow + * remains the reference for all non-admission cases. */ + mcc=0;reset(old);finish(scenario_switch_structure_bsp((short)requested));expected=observed; + if(old==NONE&&requested>=0&&requested<2&&mode!=0) { + if(expected.modal!=1||expected.returned||expected.pointers||expected.loads!=1|| + expected.stopped!=1||expected.started!=1||expected.collision_disabled!=1|| + expected.collision_enabled!=1||expected.menu||expected.index!=NONE)return 3; + } + if(old==0&&requested==1&&mode==2) { + if(expected.modal!=1||expected.loads!=2||expected.returned||expected.pointers!=3|| + expected.disconnects!=1||expected.reconnects!=1||expected.menu|| + expected.index!=0||expected.scenario_index!=0)return 4; + } + mcc=1;reset(old);finish(scenario_switch_structure_bsp((short)requested)); + if(old==NONE&&requested>=0&&requested<2&&mode!=0) { + if(observed.modal||observed.returned||observed.pointers||observed.loads!=1|| + observed.stopped!=1||observed.started!=1||observed.collision_disabled!=1|| + observed.collision_enabled!=1||observed.disconnects||observed.reconnects|| + observed.menu||observed.index!=NONE||observed.scenario_index!=NONE)return 1; + /* The sole behavioral difference is avoiding the modal error. */ + observed.modal=expected.modal;observed.silent=expected.silent; + } + if(memcmp(&observed,&expected,sizeof(expected))) { + fprintf(stderr,"dispatch changed: old=%d new=%d mode=%d\n",old,requested,mode); + return 2; + } + } + return 0; +} +''' + path = tmp_path / "bsp_dispatch.c" + path.write_text(prefix) + binary = tmp_path / ("bsp_flow.exe" if sys.platform == "win32" else "bsp_flow") + flags = (["--target=i686-pc-windows-msvc", "-fuse-ld=lld"] if sys.platform == "win32" else []) + built = subprocess.run([compiler, *flags, "-std=c99", "-Wall", "-Wextra", "-Werror", + str(path), "-o", str(binary)], capture_output=True, text=True) + assert built.returncode == 0, built.stderr + result = subprocess.run([str(binary)], capture_output=True, text=True, timeout=10) + assert result.returncode == 0, result.stdout + result.stderr + + +def test_failed_mcc_bsp_releases_io_owner(tmp_path): + compiler = shutil.which("clang") or shutil.which("cc") + if not compiler: + pytest.skip("a C compiler is required") + actual = function((ROOT / "source/scenario/scenario.c").read_text(), "scenario_load") + prefix = r''' +#include +#include +typedef int boolean; +#define FALSE 0 +#define TRUE 1 +#define NONE (-1) +#define GAME_GLOBALS_TAG 0 +#define _error_delayed 0 +static int scenario_memory_status_attributed, global_scenario_index; +static int mcc_owner, bsp_result, unloads, tag_result = 1; +static void *global_game_globals; +struct scenario { struct { int count; } structure_bsp_references; }; +static struct scenario scenario = {{1}}, *global_scenario; +static void check_memory_status(int a, char const *b) {(void)a;(void)b;} +static int scenario_tags_load(char const *name) {(void)name;return tag_result;} +static struct scenario *scenario_definition_get(int index) {(void)index;return &scenario;} +static int tag_loaded(int group,char const *name) {(void)group;(void)name;return 0;} +static void *game_globals_definition_get(int index) {(void)index;return &scenario;} +static int scenario_switch_structure_bsp(int index) {(void)index;return bsp_result;} +static void error(int priority,char const *format,...) {(void)priority;(void)format;} +static int mcc_cache_tags_loaded(void) {return mcc_owner;} +static void scenario_unload(void) {unloads++;mcc_owner=0;global_scenario=NULL;} +''' + checks = r''' +int main(void) { + mcc_owner=1; + if(scenario_load("mcc_maps\\a10") || unloads!=1 || mcc_owner || global_scenario || global_game_globals!=&scenario) return 1; + /* A subsequent ordinary map must retain its existing lifetime behavior. */ + unloads=0; + if(scenario_load("a10") || unloads || mcc_owner) return 2; + bsp_result=1; + if(!scenario_load("custom_maps\\hugeass") || unloads) return 3; + mcc_owner=1; + if(!scenario_load("mcc_maps\\dangercanyon") || unloads || !mcc_owner) return 4; + /* Failed conversion already disposed its private state; no double unload. */ + mcc_owner=0;tag_result=NONE; + if(scenario_load("mcc_maps\\bad") || unloads) return 5; + return 0; +} +''' + source = tmp_path / "lifecycle.c" + source.write_text(prefix + actual + checks) + binary = tmp_path / ("lifecycle.exe" if sys.platform == "win32" else "lifecycle") + flags = (["--target=i686-pc-windows-msvc", "-fuse-ld=lld"] if sys.platform == "win32" else []) + built = subprocess.run([compiler, *flags, "-std=c99", "-Wall", "-Wextra", "-Werror", + str(source), "-o", str(binary)], capture_output=True, text=True) + assert built.returncode == 0, built.stderr + result = subprocess.run([str(binary)], capture_output=True, text=True, timeout=10) + assert result.returncode == 0, result.stdout + result.stderr + + +def test_failed_mcc_map_returns_to_ui_before_game_initialization(tmp_path): + compiler = shutil.which("clang") or shutil.which("cc") + if not compiler: + pytest.skip("a C compiler is required") + main = function((ROOT / "source/main/main.c").read_text(), "main_new_map") + recovery = function((ROOT / "port/linux/game/mcc_main.c").read_text(), "mcc_main_load_failed") + source = r''' +#include +#include +#include "mcc_errors.h" +#define custom_edition_level_name(p) (!strncmp(p,"custom_maps\\",12)) +#define custom_edition_cache_load_error(p) "CE fixture load failed" +typedef int boolean; +#define TRUE 1 +#define FALSE 0 +#define NONE -1 +#define _error_immediate 1 +#define _error_silent 0 +struct game_options {char const *map_name;}; +static struct {int reset_map,defer_map_change,revert_map,skip_cinematic,saving_map, + won_map,lost_map,respawn,save_core,switch_to_structure_bsp_index,load_core, + load_core_at_startup,allow_persistent_storage;} main_globals; +static int loads,initialized,players,pulses,menus,popups,clears,errors,gotos,refuse=1; +static void main_new_map(struct game_options *options); +static void input_flush(void) {} +static int game_load(struct game_options *options) { + loads++; return !strcmp(options->map_name,"levels\\ui\\ui") || !refuse; +} +static void game_initialize_for_new_map(void) {initialized++;} +static void error(int priority,char const *format,...) {(void)format;if(priority)errors++;} +static int errors_handle(void) {return errors!=0;} +static void create_local_players(void) {players++;} +static void game_time_start(void) {} +static void game_initial_pulse(void) {pulses++;} +static void game_state_try_and_load_from_persistent_storage(void) {} +static void ui_widgets_disable_pause_game(int ticks) {(void)ticks;} +static int mcc_level_name(char const *name) {return !strncmp(name,"mcc_maps\\",9);} +static void display_error_text_when_main_menu_loaded(wchar_t const *text) {(void)text;popups++;} +static void errors_clear(void) {errors=0;clears++;} +static void main_goto_main_menu(void) {gotos++;} +static void main_menu_load(void) { + struct game_options ui={"levels\\ui\\ui"};menus++;main_new_map(&ui); +} +''' + recovery + main + r''' +int main(void) { + struct game_options options={"mcc_maps\\bad_bsp"}; + errors=1; /* A failed initial BSP already reported a native error. */ + main_new_map(&options); + if(loads!=2 || initialized!=1 || players!=1 || pulses!=1 || menus!=1 || + popups!=1 || clears!=1 || gotos!=1 || errors) return 1; + options.map_name="a10";main_new_map(&options); + if(menus!=1 || clears!=1 || initialized!=1 || loads!=3) return 2; + options.map_name="custom_maps\\bad";main_new_map(&options); + if(menus!=1 || clears!=1 || initialized!=1 || loads!=4) return 3; + options.map_name="mcc_maps\\good";refuse=0;errors=0;main_new_map(&options); + if(menus!=1 || clears!=1 || initialized!=2 || loads!=5) return 4; + return 0; +} +''' + path = tmp_path / "recovery.c" + path.write_text(source) + binary = tmp_path / ("recovery.exe" if sys.platform == "win32" else "recovery") + flags = (["--target=i686-pc-windows-msvc", "-fuse-ld=lld"] if sys.platform == "win32" else []) + built = subprocess.run([compiler, *flags, "-std=c99", "-Wall", "-Wextra", "-Werror", + "-I", str(ROOT / "port/linux/game"), str(path), str(ROOT / "port/linux/game/mcc_errors.c"), "-o", str(binary)], capture_output=True, text=True) + assert built.returncode == 0, built.stderr + result = subprocess.run([str(binary)], capture_output=True, text=True, timeout=10) + assert result.returncode == 0, result.stdout + result.stderr diff --git a/tools/test_mcc_loading.py b/tools/test_mcc_loading.py new file mode 100644 index 0000000000..e1f1663629 --- /dev/null +++ b/tools/test_mcc_loading.py @@ -0,0 +1,191 @@ +"""Exercise the real MCC progress controller with a recording device backend.""" +from pathlib import Path +import re +import subprocess + +import pytest +from test_mcc_pause_runtime import _compile + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.fixture(scope="module") +def loading_tool(tmp_path_factory): + work = tmp_path_factory.mktemp("mcc-loading") + implementation = (ROOT / "port/linux/game/mcc_loading.c").read_text() + implementation = re.sub(r'^#include [<"][^\n]+[>"]\s*$', '', implementation, flags=re.M) + source = r''' +#include +#include +#include +#include +#include +#include "mcc_loading.h" +typedef float real; +typedef uint32_t DWORD; +typedef int IDirect3DSurface8; +typedef struct {DWORD X,Y,Width,Height;float MinZ,MaxZ;} D3DVIEWPORT8; +typedef struct {DWORD Width,Height;} D3DSURFACE_DESC; +#define FALSE 0 +#define _error_silent 0 +static void error(int level,char const *format,...) {(void)level;(void)format;} +static int network_begins,network_ends,network_work,network_pulses; +static void mcc_load_network_begin(char const *name) {if(name && !strncmp(name,"mcc_maps/",9))network_begins++;} +static void mcc_load_network_pulse(void) {network_work++;network_pulses++;} +static void mcc_load_network_work(int stage,unsigned long done,unsigned long total) {(void)stage;(void)done;(void)total;network_work++;} +static void mcc_load_network_end(void) {network_ends++;} +static int device, surface, null_renderer, native_active, starts, ends, frames, releases; +static int failure, reenter; +static int require_target, stale_color, stale_depth, target_sets; +static IDirect3DSurface8 *draw_target=&stale_color, *draw_depth=&stale_depth; +static DWORD clock_ms; +static real drawn; +static void *global_d3d_device=&device; +static DWORD GetTickCount(void) {return clock_ms;} +static int config_boolean(char const *name) {(void)name;return null_renderer;} +static int mcc_level_name(char const *name) {return name && !strncmp(name,"mcc_maps/",9);} +static int progress_bar_is_active(void) {return native_active;} +static void progress_bar_eachframe(void) { } +static void progress_bar_begin(int skip) {(void)skip;starts++;native_active=1;} +static void progress_bar_end(void) {ends++;native_active=0;} +static void progress_bar_display(real value) { + if(require_target)assert(draw_target==&surface && draw_depth==NULL); + assert(value>=0 && value<=1);assert(value>=drawn);drawn=value; + if(reenter){clock_ms+=100;mcc_loading_pulse();} +} +static int IDirect3DDevice8_GetBackBuffer(void *d,int a,int b,IDirect3DSurface8 **s) { + (void)d;(void)a;(void)b;if(failure==1)return -1;if(failure==2)return 0;*s=&surface;return 0; +} +static int IDirect3DSurface8_GetDesc(IDirect3DSurface8 *s,D3DSURFACE_DESC *desc) { + assert(s==&surface);desc->Width=1280;desc->Height=720;return failure==3 ? -1 : 0; +} +static void IDirect3DSurface8_Release(IDirect3DSurface8 *s) {assert(s==&surface);releases++;} +static void IDirect3DDevice8_SetRenderTarget(void *d,IDirect3DSurface8 *color,IDirect3DSurface8 *depth) { + (void)d;assert(color==&surface && depth==NULL);draw_target=color;draw_depth=depth;target_sets++; +} +static void IDirect3DDevice8_SetViewport(void *d,D3DVIEWPORT8 *v) { + (void)d;assert(v->Width==1280 && v->Height==720 && v->MaxZ==1); +} +static void IDirect3DDevice8_BeginScene(void *d) {(void)d;} +static void IDirect3DDevice8_EndScene(void *d) {(void)d;} +static void IDirect3DDevice8_Present(void *d,void *a,void *b,void *c,void *e) { + (void)d;(void)a;(void)b;(void)c;(void)e;frames++; +} +''' + implementation + r''' +int main(int argc,char **argv) { + int test=argc>1 ? atoi(argv[1]) : -1, before; + require_target=test==12; + if(test<4 || test==6 || test==7) { + if(test==1)null_renderer=1; + if(test==2)global_d3d_device=NULL; + if(test==3)native_active=1; + mcc_loading_begin(test==0 ? "maps/a10" : test==6 ? "custom_maps/a10" : test==7 ? NULL : "mcc_maps/a10"); + mcc_loading_pulse();mcc_loading_stage(MCC_LOADING_AUDIO);mcc_loading_end(1); + assert(!starts && !frames && !ends && !target_sets);assert(native_active==(test==3)); + assert(draw_target==&stale_color && draw_depth==&stale_depth); + assert(network_begins==(test>=1 && test<=3));assert(network_ends==1); + if(test>=1 && test<=3)assert(network_work>0);return 0; + } + if(test==4)clock_ms=UINT32_MAX-20; + if(test>=8 && test<=10)failure=test-7; + if(test==11)reenter=1; + assert(mcc_loading_begin("mcc_maps/a10"));assert(starts==1); + assert(!mcc_loading_begin("mcc_maps/b30"));assert(starts==1); + if(failure) { + assert(!frames);assert(releases==(failure==3)); + failure=0;clock_ms+=50;mcc_loading_pulse();assert(frames==1); + } + before=frames;mcc_loading_pulse();assert(frames==before); + /* The prior scene can leave an offscreen color/depth pair. Every standalone + * loading draw must select its own target, including later work pulses. */ + if(require_target){draw_target=&stale_color;draw_depth=&stale_depth;} + clock_ms+=50;mcc_loading_stage(MCC_LOADING_AUDIO);assert(frames==before+1); + clock_ms+=50;mcc_loading_update(MCC_LOADING_AUDIO,5,10);assert(drawn>0.3f && drawn<0.55f); + before=network_pulses;clock_ms+=5000; + mcc_loading_update(MCC_LOADING_AUDIO,5,10);mcc_loading_update(MCC_LOADING_AUDIO,4,10); + assert(network_pulses==before); + before=frames;clock_ms+=50; + mcc_loading_update(MCC_LOADING_AUDIO,11,10); + mcc_loading_update(MCC_LOADING_AUDIO,0,0); + mcc_loading_update((enum mcc_loading_stage)-1,1,1); + mcc_loading_update(MCC_LOADING_STAGES,1,1); + mcc_loading_stage((enum mcc_loading_stage)-1);mcc_loading_stage(MCC_LOADING_STAGES); + mcc_loading_stage(MCC_LOADING_TAGS);assert(frames==before); + mcc_loading_update(MCC_LOADING_AUDIO,1,10);assert(drawn>0.3f); + mcc_loading_end(test!=5);assert(ends==1 && !native_active && !mcc_loading.active); + assert(test==5 ? drawn<1 : drawn==1); + before=frames;clock_ms+=100;mcc_loading_pulse();mcc_loading_end(1);assert(frames==before && ends==1); + drawn=0;mcc_loading_begin("mcc_maps/b30");assert(starts==2);mcc_loading_end(0);assert(ends==2); + if(require_target)assert(target_sets==frames && releases==target_sets); + return 0; +} +''' + path = work / "loading.c" + path.write_text(source) + output = work / "loading.exe" + _compile(path, output) + return output + + +@pytest.mark.parametrize("case", range(13)) +def test_loading_lifetime_progress_and_device_failures(loading_tool, case): + subprocess.run([str(loading_tool), str(case)], check=True, capture_output=True) + + +def test_loading_wraps_scenario_load_without_normal_frame_callbacks(): + from harness import function + load = function((ROOT / "source/game/game.c").read_text(), "game_load") + assert load.index("mcc_loading_begin") < load.index("scenario_load(") < load.index("mcc_loading_end") + controller = (ROOT / "port/linux/game/mcc_loading.c").read_text() + for unsafe in ["main_loop(", "main_pregame_render(", "render_frame_pregame(", "network_game_update("]: + assert unsafe not in controller + + +def test_menu_probe_never_opens_a_loading_screen(tmp_path): + from harness import function + implementation = (ROOT / "port/linux/game/mcc_resources.c").read_text() + source = r''' +#include +#include +#include +#include +#include "mcc_cache_format.h" +#include "mcc_errors.c" +struct mcc_runtime {char level_name[64];struct mcc_cache_source source; + struct {int external_bitmap_count,external_sound_count;} report;char failure[320];}; +static int owns,starts,ends,last_success,fail; +static int mcc_package_name(char const *name,char *out) {(void)name;out[0]=0;return 1;} +enum mcc_cache_status mcc_cache_identify(void const *h,size_t b,uint64_t s,struct mcc_cache_identity *i) { + (void)h;(void)b;(void)s;i->tag_data_size=16;return fail==5 ? MCC_CACHE_WRONG_VERSION : MCC_CACHE_OK; +} +static int read_source(void *c,uint32_t o,uint32_t b,void *out) {(void)c;(void)o;memset(out,0,b);return fail!=4;} +static int mcc_loading_begin(char const *name) {(void)name;starts++;return owns;} +static void mcc_loading_end(int success) {assert(owns);ends++;last_success=success;} +static enum mcc_cache_status load_stub(struct mcc_cache_source const *s,void *r,uint32_t n,void *report) { + (void)s;(void)r;(void)n;(void)report;return fail==6 ? MCC_CACHE_BAD_SOUND : MCC_CACHE_OK; +} +#define mcc_cache_load load_stub +static int mcc_resources_select(struct mcc_runtime *r,void *raw) {(void)r;(void)raw;return fail!=1;} +static int mcc_resources_fingerprint(struct mcc_runtime *r,unsigned char *d) {(void)r;(void)d;return fail!=2;} +static int mcc_resources_checksum(struct mcc_runtime *r,unsigned bits,uint32_t *sum) {(void)r;(void)bits;*sum=1;return fail!=3;} +static void mcc_resources_dispose(struct mcc_runtime *r) {(void)r;} +''' + function(implementation, "mcc_resources_inspect") + r''' +int main(void) { + struct mcc_cache_source source;unsigned char digest[32];uint32_t sum;int expected,started;char reason[320]; + source.context=NULL;source.read=read_source;source.size=2048; + for(owns=0;owns<=1;owns++)for(fail=0;fail<7;fail++) { + starts=ends=0;last_success=-1;expected=fail==0; + started=fail!=4 && fail!=5;strcpy(reason,"stale failure"); + assert(mcc_resources_inspect("mcc_maps/a10",&source,&sum,digest,reason,sizeof(reason))==expected); + (void)started;(void)mcc_loading_begin;(void)mcc_loading_end; + assert(starts==0 && ends==0 && last_success==-1); + assert((reason[0]==0)==expected); + } + return 0; +} +''' + path = tmp_path / "probe.c" + path.write_text(source) + output = tmp_path / "probe.exe" + _compile(path, output) + subprocess.run([str(output)], check=True, capture_output=True) diff --git a/tools/test_mcc_loading_progress.py b/tools/test_mcc_loading_progress.py new file mode 100644 index 0000000000..904a39dace --- /dev/null +++ b/tools/test_mcc_loading_progress.py @@ -0,0 +1,240 @@ +"""Real bounded MCC loading leases, transport adapter and server deadline branch.""" +from pathlib import Path +import re +import shutil +import subprocess +import pytest +from harness import function, structure +from test_mcc_identity import compile_tool + +ROOT = Path(__file__).resolve().parents[1] +GAME = ROOT / "port/linux/game" + + +@pytest.fixture(scope="module") +def load_tool(tmp_path_factory): + work = tmp_path_factory.mktemp("mcc-load-network") + headers = { + "cseries.h": "#pragma once\n#include \ntypedef int boolean;typedef unsigned short word;typedef unsigned char byte;\n#define NONE -1\n", + "networking/network_game_manager.h": "#pragma once\nstruct network_game {struct {long version;char name[128];} map;unsigned char mcc_content_sha256[32],mcc_metadata_sha256[32];long number_of_games_played;struct {int name;} machines[4];};\n", + "networking/network_game_globals.h": "#pragma once\n#include \"networking/network_game_manager.h\"\nstruct network_game_server_client_machine {int flags,machine_index;};struct network_game_server {int state;unsigned long time_of_first_client_loading_completion,time_of_last_keep_alive;struct network_game game;struct network_game_server_client_machine client_machines[4];};struct network_game_client {int dummy;};\nstruct network_game_server *global_network_game_server_get(void);struct network_game_client *global_network_game_client_get(void);struct network_game *network_game_get_game(void);\n", + "networking/network_client_manager.h": "struct network_game *network_game_client_get_game(struct network_game_client *);\nboolean network_game_client_server_has_started_game(struct network_game_client *);\n", + } + for name, text in headers.items(): + path = work / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + path = work / "bungie_net/common/message_header.h" + path.parent.mkdir(parents=True) + path.write_text((ROOT / "source/bungie_net/common/message_header.h").read_text()) + distributed = (GAME / "network_distributed.h").read_text() + wire = structure(distributed, "distributed_message_header") + # Every game build uses ILP32; the asset-free Linux runner may be LP64. + wire = re.sub(r"\bunsigned long\b", "uint32_t", wire) + wire = re.sub(r"\blong\b", "int32_t", wire) + (work / "network_distributed.h").write_text('#pragma once\n#include \n#include "bungie_net/common/message_header.h"\n' + + wire + '\ntypedef char wire_header_size[sizeof(struct distributed_message_header)==12 ? 1 : -1];\n' + + 'enum {_distributed_message_mcc_load_progress=106};\n') + adapter = work / "adapter.c" + adapter.write_text((GAME / "mcc_load_network_game.c").read_text()) + server_source = (ROOT / "source/networking/network_server_manager.c").read_text() + pregame = function(server_source, "network_game_server_idle_pregame_tasks") + deadline = pregame[pregame.index("else if (server->time_of_first_client_loading_completion)"):pregame.rindex("return success;")] + source = work / "test.c" + source.write_text(DRIVER + '\nstatic void deadline(struct network_game_server *server) {long now=(long)clock_ms;if(0){}' + deadline + '}\n' + MAIN) + return compile_tool(work, [source, adapter, GAME / "mcc_load_network.c"]) + + +DRIVER = r''' +#include "cseries.h" +#include "networking/network_game_globals.h" +#include "network_distributed.h" +#include "mcc_load_network.h" +#include +#include +#include +#define CHECK(x) do {if(!(x)){fprintf(stderr,"line%d: %s\n",__LINE__,#x);return 1;}}while(0) +static struct network_game_server server; +static struct network_game_client client; +static struct network_game game; +static int hosting=1,joined=1,connected=1,started,sends,blocked,removed,complete; +static unsigned long clock_ms=1000,revision=1; +static struct {struct distributed_message_header header;struct mcc_load_message body;} packet,last; +typedef char wire_packet_size[sizeof(packet)==216 ? 1 : -1]; +struct network_game_server *global_network_game_server_get(void){return hosting ? &server : NULL;} +struct network_game_client *global_network_game_client_get(void){return connected ? &client : NULL;} +struct network_game *network_game_get_game(void){return &game;} +struct network_game *network_game_client_get_game(struct network_game_client *c){(void)c;return &game;} +boolean network_game_client_server_has_started_game(struct network_game_client *c){(void)c;return started;} +struct network_game_server_client_machine *network_game_server_get_client_machine_at_index(struct network_game_server *s,long n){(void)s;return n==2 ? &server.client_machines[2] : NULL;} +boolean network_game_server_client_machine_is_joined_to_game(struct network_game_server *s,struct network_game_server_client_machine *p){(void)s;return joined && p==&server.client_machines[2];} +boolean mcc_level_name(char const *name){return name && !strncmp(name,"mcc_maps\\",9);} +unsigned long mcc_identity_host_revision(void){return revision;} +void const *mcc_identity_host_settings(void const *g,long size,struct network_game *copy){if(size!=sizeof(*copy))return NULL;memcpy(copy,g,size);return copy;} +unsigned long system_milliseconds(void){return clock_ms;} +void build_message_header(word *out,word size,byte type,byte flags){*out=(word)((size<<4)|(type<<2)|flags);} +boolean network_distributed_client_send_reliably(void *p,word size){if(size!=sizeof(last))return 0;memcpy(&last,p,size);sends++;return !blocked;} +boolean network_distributed_server_send_to_machine_reliably(long n,void *p,word size){return n==2 ? network_distributed_client_send_reliably(p,size) : 0;} +#define TRUE 1 +#define FALSE 0 +#define MAXIMUM_NETWORK_MACHINE_COUNT 4 +#define MAXIMUM_MACHINE_NAME_LENGTH 32 +#define MILLISECONDS_PER_SECOND 1000 +#define NETWORK_GAME_SERVER_MAXIMUM_WAIT_TIME_FOR_LEVEL_LOADING 60000 +#define NETWORK_SERVER_MANAGER_FILE "network_server_manager.c" +#define TEST_FLAG(flags,bit) (((flags)&(1u<<(bit)))!=0) +#define _network_client_machine_connected_bit 0 +#define _network_client_machine_level_loaded_bit 1 +#define _network_game_server_state_pregame 0 +#define _message_server_pregame_keep_alive 0 +struct message_server_pregame_keep_alive {int unused;}; +struct network_message {int unused;}; +static struct network_message *create_network_game_message(int type,void *data,unsigned size){(void)type;(void)data;(void)size;return NULL;} +static void network_game_server_send_message_to_all_machines(struct network_game_server *s,struct network_message *m){(void)s;(void)m;} +static int map_share_machine_needs_map(long index){(void)index;return 0;} +static void network_event(char const *format,...){(void)format;} +static char const *wide_to_ascii(int n,char *text,unsigned size){(void)n;(void)text;(void)size;return "peer";} +static int network_game_server_remove_client_machine_from_game(struct network_game_server *s,struct network_game_server_client_machine *m){(void)s;m->flags=0;removed++;return 1;} +static void network_game_server_all_machines_have_loaded(struct network_game_server *s){(void)s;complete++;} +#define match_assert(file,line,x) do {if(!(x))abort();}while(0) +''' + +MAIN = r''' +static void setup(void){ + strcpy(game.map.name,"mcc_maps\\package\\level");game.map.name[64]=7; + game.map.version=123;game.mcc_content_sha256[31]=42;game.mcc_metadata_sha256[0]=19;game.number_of_games_played=4; + server.client_machines[2].machine_index=2;server.client_machines[2].flags=1; + server.time_of_first_client_loading_completion=1000; + mcc_load_network_start(&game);mcc_load_network_begin(game.map.name);packet=last; +} +static void receive(void){mcc_load_network_handle_message(2,&packet,sizeof(packet),1);} +int main(int argc,char **argv){ + int test,i,old;struct mcc_load_network state;struct mcc_load_message message; + if(argc!=2)return 2;test=atoi(argv[1]);setup();CHECK(sends==1 && packet.body.sequence==1); + if(test==0){ + for(i=1;i<=24;i++){clock_ms=1000+i*5000;packet.body.sequence++;receive();deadline(&server);CHECK(!removed && !complete);} + CHECK(mcc_load_network_host_waiting(2)); + server.client_machines[2].flags|=2;deadline(&server);CHECK(complete==1 && !removed); + }else if(test==1){ + receive();clock_ms+=29000;receive();clock_ms+=1000;CHECK(!mcc_load_network_host_waiting(2)); + packet.body.sequence++;receive();CHECK(!mcc_load_network_host_waiting(2));clock_ms=61000;deadline(&server);CHECK(removed==1 && complete==1); + }else if(test==2){ + for(i=0;i<48;i++){clock_ms=1000+i*5000;packet.body.sequence++;receive();CHECK(mcc_load_network_host_waiting(2));} + clock_ms=241000;packet.body.sequence++;receive();CHECK(!mcc_load_network_host_waiting(2)); + mcc_load_network_start(&game);receive();CHECK(!mcc_load_network_host_waiting(2));deadline(&server);CHECK(removed==1 && complete==1); + }else if(test==3){ + mcc_load_network_handle_message(2,&packet,sizeof(packet),0);CHECK(!mcc_load_network_host_waiting(2)); + mcc_load_network_handle_message(2,&packet,sizeof(packet)-1,1);CHECK(!mcc_load_network_host_waiting(2)); + packet.header.count=2;receive();CHECK(!mcc_load_network_host_waiting(2));packet.header.count=1; + packet.header.header|=1;receive();CHECK(!mcc_load_network_host_waiting(2));packet.header.header&=~1; + packet.body.round++;receive();CHECK(!mcc_load_network_host_waiting(2));packet.body.round--; + packet.body.identity.name[64]++;receive();CHECK(!mcc_load_network_host_waiting(2));packet.body.identity.name[64]--; + packet.body.identity.content[0]++;receive();CHECK(!mcc_load_network_host_waiting(2));packet.body.identity.content[0]--; + packet.body.identity.metadata[0]++;receive();CHECK(!mcc_load_network_host_waiting(2));packet.body.identity.metadata[0]--; + joined=0;receive();CHECK(!mcc_load_network_host_waiting(2));joined=1; + receive();CHECK(mcc_load_network_host_waiting(2));revision++;CHECK(!mcc_load_network_host_waiting(2)); + }else if(test==4){ + receive();CHECK(mcc_load_network_host_waiting(2));mcc_load_network_peer_left(2);packet.body.sequence++;receive();CHECK(!mcc_load_network_host_waiting(2)); + game.number_of_games_played++;mcc_load_network_start(&game);receive();CHECK(!mcc_load_network_host_waiting(2));packet.body.round++;receive();CHECK(mcc_load_network_host_waiting(2)); + mcc_load_network_disconnect();CHECK(!mcc_load_network_host_waiting(2));old=sends;clock_ms+=5000;mcc_load_network_pulse();CHECK(old==sends); + }else if(test==5){ + old=sends;for(i=0;i<100;i++){clock_ms++;mcc_load_network_pulse();}CHECK(sends==old); + clock_ms+=5000;blocked=1;mcc_load_network_pulse();CHECK(sends==old+1);blocked=0; + clock_ms+=5000;mcc_load_network_pulse();CHECK(sends==old+2 && last.body.sequence>packet.body.sequence); + mcc_load_network_end();clock_ms+=5000;mcc_load_network_pulse();CHECK(sends==old+2); + }else if(test==6){ + mcc_load_network_disconnect();hosting=0;mcc_load_network_begin(game.map.name);CHECK(sends==2); + packet=last;mcc_load_network_handle_message(NONE,&packet,sizeof(packet),1); + clock_ms=121000;CHECK(!mcc_load_network_client_expired());clock_ms=241000;CHECK(mcc_load_network_client_expired()); + started=1;CHECK(!mcc_load_network_client_expired());started=0;game.mcc_metadata_sha256[0]++;CHECK(!mcc_load_network_client_expired()); + old=sends;mcc_load_network_pulse();CHECK(sends==old); + }else if(test==7){ + mcc_load_network_disconnect();strcpy(game.map.name,"maps\\bloodgulch");mcc_load_network_start(&game);mcc_load_network_begin(game.map.name); + receive();clock_ms=61000;deadline(&server);CHECK(removed==1 && complete==1 && sends==1); + }else if(test==8){ + memset(&state,0,sizeof(state));message=packet.body;mcc_load_network_bind(&state,&message.identity,message.round,0xfffffff0u); + CHECK(mcc_load_network_receive(&state,2,&message,0xfffffff0u));CHECK(mcc_load_network_active(&state,2,100u)); + CHECK(!mcc_load_network_receive(&state,-1,&message,100u));message.sequence=0;CHECK(!mcc_load_network_receive(&state,2,&message,100u)); + CHECK(!mcc_load_network_active(&state,2,30000u)); + }else if(test==9){ + memset(&state,0,sizeof(state));message=packet.body; + mcc_load_network_bind(&state,&message.identity,message.round,1000); + CHECK(mcc_load_network_receive(&state,2,&message,1000));message.sequence++; + CHECK(!mcc_load_network_receive(&state,2,&message,5999));CHECK(state.peers[2].sequence==1); + CHECK(mcc_load_network_receive(&state,2,&message,6000)); + }else if(test==10){ + old=sends;mcc_load_network_work(3,1,100);clock_ms+=5000; + mcc_load_network_work(3,1,100);mcc_load_network_work(2,90,100);mcc_load_network_work(3,2,99); + CHECK(sends==old);mcc_load_network_work(3,2,100);CHECK(sends==old+1); + clock_ms+=5000;mcc_load_network_work(4,0,0);CHECK(sends==old+2); + mcc_load_network_end();clock_ms+=5000;mcc_load_network_work(5,0,0);CHECK(sends==old+2); + }else return 2; + return 0; +} +''' + + +@pytest.mark.parametrize("case", range(11), ids=["slow-client-real-deadline", "no-progress-replay", "absolute-cap", + "untrusted-binding", "round-and-peer-lifetime", "send-only-rate-backpressure", "slow-host-client-limit", + "legacy-deadline", "clock-wrap", "receive-rate", "monotonic-headless-stage-work"]) +def test_loading_progress(load_tool, case): + result = subprocess.run([str(load_tool), str(case)], capture_output=True, text=True) + assert result.returncode == 0, result.stderr + + +def test_before_fix_deadline_drops_progressing_client(load_tool, tmp_path): + for source in load_tool.parent.rglob("*"): + if source.is_file() and source.suffix in (".h", ".c"): + target = tmp_path / source.relative_to(load_tool.parent) + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, target) + source = tmp_path / "test.c" + text = source.read_text() + guard = "if (mcc_load_network_host_waiting(server->client_machines[i].machine_index))" + assert text.count(guard) == 1 + source.write_text(text.replace(guard, "if (0)")) + exe = compile_tool(tmp_path, [source, tmp_path / "adapter.c", GAME / "mcc_load_network.c"]) + result = subprocess.run([str(exe), "0"], capture_output=True, text=True) + assert result.returncode == 1 and "!removed && !complete" in result.stderr, result.stderr + + +def test_real_transport_wrappers_only_write_while_loading(load_tool, tmp_path): + for source in load_tool.parent.rglob("*"): + if source.is_file() and source.suffix in (".h", ".c"): + target = tmp_path / source.relative_to(load_tool.parent) + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, target) + source = tmp_path / "test.c" + text = source.read_text() + client_stub = "boolean network_distributed_client_send_reliably(void *p,word size){if(size!=sizeof(last))return 0;memcpy(&last,p,size);sends++;return !blocked;}" + host_stub = "boolean network_distributed_server_send_to_machine_reliably(long n,void *p,word size){return n==2 ? network_distributed_client_send_reliably(p,size) : 0;}" + assert client_stub in text and host_stub in text + server = (ROOT / "source/networking/network_server_message_handler.c").read_text() + client = (ROOT / "source/networking/network_client_manager.c").read_text() + globals_source = (ROOT / "source/networking/network_game_globals.c").read_text() + wrappers = r''' +#define FALSE 0 +#define NETWORK_MESSAGE_BUFFER_SIZE 4096 +#define MAXIMUM_NETWORK_MACHINE_COUNT 4 +#define VALID_INDEX(i,n) ((unsigned long)(i)<(unsigned long)(n)) +#define csmemcpy memcpy +#define global_network_game_client (connected ? &client : NULL) +struct network_connection {int unused;}; +struct transport_address {int unused;}; +static struct network_connection connection; +static struct network_connection *network_game_client_get_connection(struct network_game_client *c){(void)c;return &connection;} +static struct network_connection *network_game_server_get_client_connection(struct network_game_server_client_machine *m){(void)m;return &connection;} +static int network_connection_active(struct network_connection *c){(void)c;return connected;} +static int network_game_server_get_client_machine(struct network_game_server *s,struct network_game_server_client_machine *m,long *index){(void)s;*index=m->machine_index;return 1;} +static boolean network_connection_write(struct network_connection *c,void *data,word size,struct transport_address *a,boolean reliable){ + if(c!=&connection || a || !reliable || size!=sizeof(last))abort(); + memcpy(&last,data,size);sends++;((byte *)data)[0]^=255;return !blocked; +} +''' + function(server, "network_game_server_write") + function(client, "network_game_client_write") + function( + globals_source, "network_distributed_client_send_reliably") + function(server, + "network_game_server_client_machine_in_game") + function(server, "network_distributed_server_send_to_machine_reliably") + source.write_text(text.replace(client_stub, wrappers).replace(host_stub, "")) + exe = compile_tool(tmp_path, [source, tmp_path / "adapter.c", GAME / "mcc_load_network.c"]) + for case in (5, 6): + result = subprocess.run([str(exe), str(case)], capture_output=True, text=True) + assert result.returncode == 0, result.stderr diff --git a/tools/test_mcc_maps.py b/tools/test_mcc_maps.py new file mode 100644 index 0000000000..e148d8b020 --- /dev/null +++ b/tools/test_mcc_maps.py @@ -0,0 +1,882 @@ +"""Compile the real MCC catalog with narrow host filesystem stubs. + +Generated maps contain only a header; the catalog must not read tag payloads. +The stubs require every discovery/open operation to name d:\\mcc_maps\\, so +an accidental fallback to Xbox or CE directories fails the executable. +""" +import os +import re +from pathlib import Path +import shutil +import struct +import subprocess +import sys + +import pytest +from harness import function + +ROOT = Path(__file__).resolve().parents[1] + + +def header(version=13, scenario=0, internal="different_internal_name"): + data = bytearray(0x828) + for offset, value in {0: 0x68656164, 4: version, 8: len(data), + 16: 0x800, 20: 40, 0x7FC: 0x666F6F74}.items(): + struct.pack_into(" +#include +#include +#include +typedef unsigned char boolean; +typedef unsigned char byte; +#define TRUE 1 +#define FALSE 0 +#define NONE (-1) +#define FLAG(x) (1u << (x)) +#ifdef _WIN32 +#define csstrcasecmp _stricmp +#else +#include +#define csstrcasecmp strcasecmp +#define _strnicmp strncasecmp +#endif +FILE *mcc_test_fopen(char const *,char const *); +size_t mcc_test_fread(void *,size_t,size_t,FILE *); +#define fopen mcc_test_fopen +#define fread mcc_test_fread +#endif +''') + (work / "errors.h").write_text('#define _error_silent 0\nvoid error(short,const char *,...);\n') + (work / "xtl.h").write_text(r''' +#pragma once +#ifndef _WIN32 +#define __stdcall +#endif +#define TRUE 1 +#define FALSE 0 +#define WAIT_OBJECT_0 0 +#define INFINITE (~0u) +#define CreateEventA(a,b,c,d) ((void *)0) +#define CreateThread(a,b,c,d,e,f) ((void)(c),(void *)0) +#define WaitForSingleObject(h,t) ((void)(h),(void)(t),0) +#define SetEvent(h) ((void)(h)) +typedef void *HANDLE; +typedef struct {unsigned long dwFileAttributes;char cFileName[256];} WIN32_FIND_DATAA; +#define FILE_ATTRIBUTE_DIRECTORY 16 +#define INVALID_HANDLE_VALUE ((HANDLE)-1) +HANDLE FindFirstFileA(char const *,WIN32_FIND_DATAA *); +int FindNextFileA(HANDLE,WIN32_FIND_DATAA *); +int CloseHandle(HANDLE); +''') + source = work / "catalog.c" + source_code = r''' +#include "cseries.h" +#include "xtl.h" +#include "mcc_maps.h" +#include "mcc_package.h" +#include "mcc_cache_format.h" +#include "mcc_errors.h" +#include +#include +#include +#undef fopen +#undef fread +static char const *root; +static char const *listing="list.txt"; +static unsigned inventories; +static int admission_reads; +static int identities_prepared; +static unsigned reads, largest, scans, closed; +void mcc_cache_precache_clear(void) {} +void mcc_menu_preview_clear(void) {} +int config_boolean(char const *name) { + if(!strcmp(name,"game.mcc_campaigns"))return getenv("TEST_MISSIONS")!=NULL; + char const *disabled=getenv("TEST_COLLECTIONS_DISABLED");(void)name;return !disabled; +} +#include "../src/mcc_manifest.h" +#include "../src/mcc_menu_metadata.h" +int mcc_manifest_package_root(char const *level,char path[1024]) { + (void)level;path[0]=0;return getenv("TEST_MENU_METADATA")!=NULL; +} +int mcc_menu_metadata_load(char const *folder,int campaign,struct mcc_menu_metadata *metadata) { + (void)folder;(void)campaign;memset(metadata,0,sizeof(*metadata)); + strcpy(metadata->title,"Offline package title");metadata->count=1; + strcpy(metadata->maps[0].name,"arena");strcpy(metadata->maps[0].title,"Authored offline level");return 1; +} +struct steam_workshop_map_text const *mcc_menu_metadata_find(struct mcc_menu_metadata const *metadata,char const *name) { + return metadata->count && !strcmp(name,metadata->maps[0].name) ? &metadata->maps[0] : NULL; +} +int mcc_manifest_for_level(char const *level,struct mcc_manifest *manifest,char reason[128]) { + char buffer[512],*name;int count=0;(void)level;reason[0]=0; + memset(manifest,0,sizeof(*manifest)); + if(!getenv("TEST_MISSIONS"))return 0; + snprintf(buffer,sizeof(buffer),"%s",getenv("TEST_MISSIONS")); + for(name=strtok(buffer,",");name&&count<64;name=strtok(NULL,",")) { + snprintf(manifest->missions[count].name,64,"%s",name); + snprintf(manifest->missions[count].title,64,"Explicit mission %s",name);count++; + } + strcpy(manifest->title,"Example campaign");manifest->count=count;return 1; +} +#include "../src/steam_workshop.h" +static int workshop_items; +static struct steam_workshop_map workshop_list[4]; +#define workshop_item workshop_list[0] +int steam_workshop_scan(void) {return workshop_items;} +int steam_workshop_count(void) {return workshop_items;} +struct steam_workshop_map const *steam_workshop_map(int index) {return index>=0 && index|")) exit(20); + snprintf(translated,sizeof(translated),"%s/mcc_maps/%s",root,path+12); + {char *p;for(p=translated;*p;p++)if(*p=='\\')*p='/';} + return fopen(translated,mode); +} +size_t mcc_test_fread(void *out,size_t size,size_t count,FILE *file) { + size_t bytes=size*count; + if (bytes>2048 && !admission_reads) exit(21); + if (bytes>largest) largest=(unsigned)bytes; + reads++; + return fread(out,size,count,file); +} +void error(short priority,char const *format,...) {(void)priority;(void)format;} +HANDLE FindFirstFileA(char const *pattern,WIN32_FIND_DATAA *data) { + char path[1024];FILE *inventory;size_t n;char *p; + if (strncmp(pattern,"d:\\mcc_maps\\",12)) exit(23); + snprintf(path,sizeof(path),"%s/mcc_maps/%s",root,pattern+12); + for(p=path;*p;p++)if(*p=='\\')*p='/'; + n=strlen(path);if(n<3 || strcmp(path+n-3,"*.*"))exit(23); + strcpy(path+n-3,listing); + inventory=fopen(path,"r");scans++; + if (!inventory)return INVALID_HANDLE_VALUE; + if (FindNextFileA(inventory,data)){inventories++;return inventory;} + fclose(inventory);return INVALID_HANDLE_VALUE; +} +int FindNextFileA(HANDLE handle,WIN32_FIND_DATAA *data) { + FILE *inventory=(FILE *)handle; + if (!fgets(data->cFileName,sizeof(data->cFileName),inventory))return FALSE; + data->cFileName[strcspn(data->cFileName,"\r\n")]=0; + data->dwFileAttributes=0; + if (data->cFileName[0]=='/') { + data->dwFileAttributes=FILE_ATTRIBUTE_DIRECTORY; + memmove(data->cFileName,data->cFileName+1,strlen(data->cFileName)); + } + return TRUE; +} +int CloseHandle(HANDLE handle) { + fclose((FILE *)handle);inventories--;closed++;return TRUE; +} + +int main(int argc,char **argv) { + short count,i; + if(argc<2)return 2; + if(argc>=4 && !strcmp(argv[2],"browse")) { + struct mcc_map_browser b={0};int step; + root=argv[1];workshop_from_environment();mcc_map_browser_open(&b,atoi(argv[3])); + for(step=4;step<=argc;step++) { + int row;wchar_t text[64]; + printf("view%d=%s|%d|%d\n",step-4,b.package,b.count,b.chosen); + for(row=0;row2 && !strcmp(argv[2],"workshop")) { + /* one subscribed item: its maps folder is root/mcc_maps/2899609719, as the platform's path translation has it */ + workshop_items=1; + strcpy(workshop_item.item_id,"2899609719");strcpy(workshop_item.item_title,"Pro Edition"); + strcpy(workshop_item.name,"pat_beavercreek");strcpy(workshop_item.title,"Better Creek"); + argc=2; + } + count=mcc_maps_count(FALSE); + if(workshop_items) { + struct mcc_map_browser browser;wchar_t text[64]; + memset(&browser,0,sizeof(browser)); + mcc_map_browser_open(&browser,FALSE); + mcc_map_browser_text(&browser,0,text); + {wchar_t const *d=mcc_maps_description(0); + printf("folder=%ls\ndescription=",text); + while(*d && *d!='\r')putchar((int)*d++); + printf("\n");} + } + printf("count=%d\nmultiplayer=%d\nsingleplayer=%d\n",count,mcc_maps_count(TRUE),mcc_maps_type_count(TRUE)); + if(mcc_maps_type_count(FALSE)!=mcc_maps_count(TRUE) || + mcc_maps_type_count(TRUE)+mcc_maps_type_count(FALSE)!=count)return 30; + { + int campaign; + for(campaign=0;campaign<=1;campaign++) { + short total=mcc_maps_type_count((boolean)campaign),previous=NONE; + if(mcc_maps_type_index(-1,(boolean)campaign)!=NONE || + mcc_maps_type_index(total,(boolean)campaign)!=NONE)return 31; + for(i=0;i=count || mcc_maps_campaign(index)!=campaign)return 32; + if(argc==3 && !strcmp(argv[2],"types")) + printf("%s_%d=%s\n",campaign ? "singleplayer" : "multiplayer",i,mcc_maps_level_name(index)); + previous=index; + } + } + } + for(i=0;i63)return 25; + printf("map=%s|%d\n",level,mcc_maps_campaign(i)); + printf("label_%d=%ls\n",i,mcc_maps_name(i)); + if(getenv("TEST_MISSIONS")) { + char next[64];int state=mcc_maps_next_mission(level,next); + printf("next_%d=%d|%s\n",i,state,next); + } + } + for(i=0;i2 && !strcmp(argv[2],"rescan")) { + listing="list2.txt"; + printf("cached=%d\n",mcc_maps_count(FALSE)); + mcc_maps_rescan();printf("rescanned=%d\n",mcc_maps_count(FALSE)); + } else if(argc>2) printf("found=%d\n",mcc_maps_find(argv[2])); + printf("scans=%u\nreads=%u\nlargest_read=%u\n",scans,reads,largest); + printf("closed=%u\n",closed); + if(inventories)return 33; + return 0; +} +''' + # Exercise the actual side-effect-free runtime admission functions too. + cache_source = (ROOT / "port/linux/game/mcc_cache.c").read_text() + admission = re.search(r"static struct \{.*?\} mcc_validation;", cache_source, re.S).group() + "\n" + "\n".join(function(cache_source, name) for name in + ("mcc_cache_validation_clear", "mcc_cache_probe", "mcc_path", "mcc_scenario_identity", "mcc_file_read", "mcc_open_explain", "mcc_cache_checksum", "mcc_cache_present")) + admission += "\n" + (ROOT / "port/linux/game/mcc_validation.inl").read_text() + source.write_text(source_code.replace("int main(int argc,char **argv)", "#define fopen mcc_test_fopen\n#define fread mcc_test_fread\n" + admission + "\n#undef fopen\n#undef fread\nint main(int argc,char **argv)")) + output = work / ("catalog.exe" if sys.platform == "win32" else "catalog") + command = [compiler, "-include", str(ROOT / "port/linux/game/mcc_loading.h"), str(ROOT / "tools/mcc_loading_stub.c"), "-std=c99", "-Wall", "-Wextra", "-Werror", "-DZ_PREFIX", + "-I", str(work), "-I", str(ROOT / "port/linux/game"), str(source), + str(ROOT / "port/linux/game/mcc_maps.c"), + str(ROOT / "port/linux/game/mcc_workshop.c"), + str(ROOT / "port/linux/game/mcc_package.c"), str(ROOT / "port/linux/src/workshop_collections.c"), + str(ROOT / "port/linux/game/mcc_cache_format.c"), str(ROOT / "port/linux/game/mcc_resources.c"), str(ROOT / "port/linux/game/mcc_errors.c"), str(ROOT / "port/linux/game/mcc_sha256.c"), str(ROOT / "port/third_party/zlib/crc32.c"), "-o", str(output)] + if sys.platform == "win32": + command[1:1] = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld", "-D_CRT_SECURE_NO_WARNINGS"] + result = subprocess.run(command, capture_output=True, text=True) + assert result.returncode == 0, result.stderr + return output + + +def install(root, entries): + directory = root / "mcc_maps" + directory.mkdir(exist_ok=True) + for name, contents in entries.items(): + (directory / name).write_bytes(contents) + (directory / "list.txt").write_text("\n".join(entries)) + + +def run(tool, root, *args, items=None): + environment = dict(os.environ) + if items: + environment["CATALOG_ITEMS"] = ";".join(":".join(item) for item in items) + result = subprocess.run([str(tool), str(root), *args], capture_output=True, text=True, timeout=10, cwd=root, + env=environment) + assert result.returncode == 0, result.stdout + result.stderr + fields = dict(line.split("=", 1) for line in result.stdout.splitlines() if not line.startswith("map=")) + maps = [line[4:] for line in result.stdout.splitlines() if line.startswith("map=")] + return fields, maps + + +def test_versions_and_folders_are_isolated(catalog_tool, tmp_path): + install(tmp_path, {"a10.map": header(), "bloodgulch.map": header(scenario=1), + "xbox.map": header(version=5), "custom.map": header(version=609), + "ui.map": header(scenario=2), "truncated.map": header()[:300], + "ignored.yelo": header()}) + for folder in ("maps", "custom_maps"): + (tmp_path / folder).mkdir() + for name in ("a10", "bloodgulch", "outside_only"): + (tmp_path / folder / (name + ".map")).write_bytes(header()) + fields, maps = run(catalog_tool, tmp_path) + assert fields["count"] == "2" + assert fields["multiplayer"] == "1" + assert maps == ["mcc_maps\\a10|1", "mcc_maps\\bloodgulch|0"] + assert fields["largest_read"] == "2048" + assert fields["scans"] == "1" + + +@pytest.mark.parametrize("entries,singleplayer,multiplayer", [ + ({}, [], []), + ({"only_sp": 0}, ["only_sp"], []), + ({"only_mp": 1}, [], ["only_mp"]), + ({"a10": 1, "bloodgulch": 0}, ["bloodgulch"], ["a10"]), + ({"a_mp": 1, "b_sp": 0, "c_mp": 1, "d_sp": 0}, ["b_sp", "d_sp"], ["a_mp", "c_mp"]), +]) +def test_scenario_type_lists_keep_catalog_identity(catalog_tool, tmp_path, entries, singleplayer, multiplayer): + install(tmp_path, {name + ".map": header(scenario=kind) for name, kind in entries.items()}) + fields, _ = run(catalog_tool, tmp_path, "types") + for label, expected in [("singleplayer", singleplayer), ("multiplayer", multiplayer)]: + assert int(fields[label]) == len(expected) + assert [fields[f"{label}_{row}"] for row in range(len(expected))] == [ + "mcc_maps\\" + name for name in expected] + + +def test_filename_identity_case_and_duplicate_filter(catalog_tool, tmp_path): + install(tmp_path, {"UPPER.map": header(internal="a10"), "lower.map": header()}) + (tmp_path / "mcc_maps/list.txt").write_text("UPPER.MAP\nUPPER.map\nlower.map\n") + fields, maps = run(catalog_tool, tmp_path, "MCC_MAPS\\upper") + assert fields["count"] == "2" + assert fields["found"] == "1" + assert maps == ["mcc_maps\\lower|1", "mcc_maps\\UPPER|1"] + + +def test_listing_skips_directories_and_closes_its_handle(catalog_tool, tmp_path): + install(tmp_path, {"folder.map": header(), "level.map": header()}) + (tmp_path / "mcc_maps/list.txt").write_text("/folder.map\nlevel.map\nno_extension\n") + fields, maps = run(catalog_tool, tmp_path) + assert maps == ["mcc_maps\\level|1"] + assert fields["closed"] == "1" + + +def test_missing_directory_has_no_handle_to_close(catalog_tool, tmp_path): + fields, maps = run(catalog_tool, tmp_path) + assert maps == [] + assert fields["scans"] == "1" + assert fields["closed"] == "0" + + +def test_filename_length_limit(catalog_tool, tmp_path): + install(tmp_path, {"a" * 54 + ".map": header(), "b" * 55 + ".map": header()}) + fields, maps = run(catalog_tool, tmp_path) + assert fields["count"] == "1" + assert maps[0] == "mcc_maps\\" + "a" * 54 + "|1" + + +def test_rescan_rebuilds_only_mcc_catalog(catalog_tool, tmp_path): + install(tmp_path, {"first.map": header(), "second.map": header(scenario=1)}) + (tmp_path / "mcc_maps/list.txt").write_text("first.map\n") + (tmp_path / "mcc_maps/list2.txt").write_text("second.map\nfirst.map\n") + fields, _ = run(catalog_tool, tmp_path, "rescan") + assert fields["count"] == fields["cached"] == "1" + assert fields["rescanned"] == "2" + assert fields["scans"] == "2" + + +def test_catalog_limit(catalog_tool, tmp_path): + install(tmp_path, {f"map{i:04}.map": header(scenario=i % 2) for i in range(1025)}) + fields, maps = run(catalog_tool, tmp_path) + assert fields["count"] == "1024" + assert fields["multiplayer"] == "512" + assert len(maps) == 1024 + + +def test_empty_or_missing_mcc_directory(catalog_tool, tmp_path): + fields, maps = run(catalog_tool, tmp_path) + assert fields["count"] == fields["multiplayer"] == "0" + assert maps == [] + + +def test_unsafe_or_unlaunchable_names_are_not_opened(catalog_tool, tmp_path): + install(tmp_path, {"valid.map": header()}) + unsafe = ["../a10.map", "..\\a10.map", "bad?.map", "bad*.map", "bad|.map", + 'bad".map', "bad<.map", "bad>.map", "d:a10.map", ".map"] + (tmp_path / "mcc_maps/list.txt").write_text("\n".join(unsafe + ["valid.map"])) + fields, maps = run(catalog_tool, tmp_path) + assert fields["count"] == "1" + assert maps == ["mcc_maps\\valid|1"] + + +@pytest.mark.parametrize("name,accepted", [ + ("mcc_maps\\a10", True), ("MCC_MAPS/bloodgulch", True), + ("mcc_maps\\" + "a" * 54, True), ("mcc_maps\\" + "a" * 55, False), + ("a10", False), ("custom_maps\\a10", False), ("maps\\a10", False), + ("mcc_maps\\..\\a10", False), ("mcc_maps/../a10", False), + ("mcc_maps\\", False), ("mcc_maps\\a10.", False), + ("mcc_maps\\a10 ", False), ("mcc_maps\\a?0", False), +]) +def test_runtime_path_admission(catalog_tool, tmp_path, name, accepted): + fields, _ = run(catalog_tool, tmp_path, "path", name) + assert fields["accepted"] == str(int(accepted)) + if accepted: + assert fields["path"] == "d:\\mcc_maps\\" + name[9:] + ".map" + + +@pytest.mark.parametrize("name,expected", [ + ("mcc_maps\\a10", "mcc_maps\\a10"), + ("MCC_MAPS/BloodGulch", "mcc_maps\\BloodGulch"), + ("mcc_maps/" + "a" * 54, "mcc_maps\\" + "a" * 54), + ("custom_maps\\a10", None), +]) +def test_saved_identity_keeps_mcc_namespace(catalog_tool, tmp_path, name, expected): + fields, _ = run(catalog_tool, tmp_path, "identity", name) + assert fields["accepted"] == str(int(expected is not None)) + if expected: + assert fields["identity"] == expected + + +def test_saved_identity_allocation_failure_does_not_modify_tags(catalog_tool, tmp_path): + fields, _ = run(catalog_tool, tmp_path, "identity_fail", "mcc_maps\\a10") + assert fields["accepted"] == "0" + + +def test_package_catalog_duplicates_and_resource_files(catalog_tool, tmp_path): + install(tmp_path, {"a10.map": header(), "solo.map": header()}) + root = tmp_path / "mcc_maps" + (root / "list.txt").write_text("a10.map\nsolo.map\n/one\n/two\n/..\n") + for package, scenario in (("one", 0), ("two", 1)): + folder = root / package + folder.mkdir() + (folder / "a10.map").write_bytes(header(scenario=scenario)) + # Even a resource file that resembles a level header is not a level. + (folder / "sounds.map").write_bytes(header()) + (folder / "list.txt").write_text("a10.map\nsounds.map\n/nested\n../solo.map\n") + (folder / (package + ".map")).write_bytes(header(scenario=scenario)) + with (folder / "list.txt").open("a") as listing: + listing.write(package + ".map\n") + fields, maps = run(catalog_tool, tmp_path, "mcc_maps/two/a10") + assert maps == ["mcc_maps\\a10|1", "mcc_maps\\one\\a10|1", "mcc_maps\\one\\one|1", "mcc_maps\\solo|1", "mcc_maps\\two\\a10|0", "mcc_maps\\two\\two|0"] + assert fields["found"] == "4" + assert fields["label_0"] == "A10" + assert fields["label_1"] == "A10 [one]" + assert fields["label_2"] == "One [one]" + assert fields["label_3"] == "Solo" + assert fields["label_4"] == "A10 [two]" + assert fields["label_5"] == "Two [two]" + assert fields["closed"] == fields["scans"] == "3" + + +@pytest.mark.parametrize("stem", ["pkg/level", "pkg\\level", "p/" + "a" * 52]) +def test_package_saved_identity(catalog_tool, tmp_path, stem): + fields, _ = run(catalog_tool, tmp_path, "identity", "mcc_maps/" + stem) + assert fields["accepted"] == "1" + assert fields["identity"] == "mcc_maps\\" + stem.replace("/", "\\") + + +@pytest.mark.parametrize("stem", ["p/q/level", "p//level", "./level", "p/../level", "p /level", "p./level", "/level", "p/", "p/" + "a" * 53]) +def test_package_invalid_paths(catalog_tool, tmp_path, stem): + fields, _ = run(catalog_tool, tmp_path, "path", "mcc_maps/" + stem) + assert fields["accepted"] == "0" + + +def test_network_admission_checks_package_resources(catalog_tool, tmp_path): + folder = tmp_path / "mcc_maps/pkg" + folder.mkdir(parents=True) + from test_mcc_cache_format import resource_dependency_map + level = resource_dependency_map() + struct.pack_into("\\, shown by its Workshop title.""" + install(tmp_path, {"a10.map": header()}) + item = tmp_path / "mcc_maps" / "2899609719" + item.mkdir() + (item / "pat_beavercreek.map").write_bytes(header(scenario=1)) + fields, maps = run(catalog_tool, tmp_path, "workshop") + assert maps == ["mcc_maps\\2899609719\\pat_beavercreek|0", "mcc_maps\\a10|1"] + # the title, not the file name and not a "[package]" suffix + assert fields["label_0"] == "Better Creek" + # the package folder is named by the item's title, and the description says where it is from + assert fields["folder"] == "[Pro Edition]" + assert fields["description"].startswith("Steam Workshop") + # the same data root without the item: only the ordinary map + fields, maps = run(catalog_tool, tmp_path) + assert maps == ["mcc_maps\\a10|1"] + + +COLLECTION_ITEMS = [ + # in PRO EDITION + ("2899666869", "Item One", "alpha_map_file", "Alpha Arena"), + # in SOCIAL MAP PACK and 2V2 MAPS + ("2899747345", "Item Two", "beta_map_file", "Beta Arena"), + # in no collection + ("12345", "Lone Item", "gamma_map_file", "Gamma Arena"), +] + + +def collection_install(tmp_path): + install(tmp_path, {"solo.map": header(scenario=0), "arena.map": header(scenario=1)}) + base = tmp_path / "mcc_maps" + for item, _, name, _ in COLLECTION_ITEMS: + (base / item).mkdir() + (base / item / f"{name}.map").write_bytes(header(scenario=1)) + + +def test_workshop_collections_are_folders_of_their_items_maps(catalog_tool, tmp_path): + """An item in a collection is listed in that collection's folder; an item in none keeps its own.""" + collection_install(tmp_path) + fields, _ = run(catalog_tool, tmp_path, "browse", "0", "enter:0", "back", items=COLLECTION_ITEMS) + # the folders: collections in the table's order, then an uncollected item's, then the loose map + assert fields["row0_0"] == "[PRO EDITION]|folder" + assert fields["row0_1"] == "[SOCIAL MAP PACK]|folder" + assert fields["row0_2"] == "[2V2 MAPS]|folder" + assert fields["row0_3"] == "[Lone Item]|folder" + assert fields["row0_4"].endswith("|mcc_maps\\arena") + assert fields["view0"] == "|5|0" + # inside a collection, the maps of its items by their Workshop titles + assert fields["view1"] == "PRO EDITION|1|0" + assert fields["row1_0"] == "Alpha Arena|mcc_maps\\2899666869\\alpha_map_file" + # back lands on the collection's own row + assert fields["view2"] == "|5|0" + + +def test_an_item_in_two_collections_is_in_both(catalog_tool, tmp_path): + collection_install(tmp_path) + fields, _ = run(catalog_tool, tmp_path, "browse", "0", "enter:1", "back", "enter:2", items=COLLECTION_ITEMS) + assert fields["row1_0"] == "Beta Arena|mcc_maps\\2899747345\\beta_map_file" + assert fields["view2"] == "|5|1" + assert fields["row3_0"] == "Beta Arena|mcc_maps\\2899747345\\beta_map_file" + + +def test_an_item_in_no_collection_keeps_its_own_folder(catalog_tool, tmp_path): + collection_install(tmp_path) + fields, _ = run(catalog_tool, tmp_path, "browse", "0", "enter:3", "back", items=COLLECTION_ITEMS) + assert fields["view1"] == "12345|1|0" + assert fields["row1_0"] == "Gamma Arena|mcc_maps\\12345\\gamma_map_file" + assert fields["view2"] == "|5|3" + + +def test_a_collection_folder_shows_only_items_the_player_has(catalog_tool, tmp_path): + collection_install(tmp_path) + fields, _ = run(catalog_tool, tmp_path, "browse", "0", items=COLLECTION_ITEMS[2:]) + # nothing subscribed from any collection: no collection folder + assert fields["view0"] == "|2|0" + assert fields["row0_0"] == "[Lone Item]|folder" + + +def local_packages(root, names): + install(root, {}) + base = root / "mcc_maps" + for name in names: + folder = base / name + folder.mkdir() + (folder / "arena.map").write_bytes(header(scenario=1)) + (folder / "list.txt").write_text("arena.map\n") + (base / "list.txt").write_text("\n".join("/" + name for name in names)) + return base + + +def test_collection_rows_do_not_exceed_browser_storage(catalog_tool, tmp_path): + # One map in two groups plus 1023 independent package folders: 1025 rows. + local_packages(tmp_path, ["2899747345"] + [f"package{i:04}" for i in range(1023)]) + fields, _ = run(catalog_tool, tmp_path, "browse", "0", "enter:1024", "back") + assert fields["view0"] == "|1025|0" + assert fields["view1"] == "package1022|1|0" + assert fields["row1_0"] == "Arena|mcc_maps\\package1022\\arena" + assert fields["view2"] == "|1025|1024" + + +def test_collection_and_package_names_have_distinct_selection_keys(catalog_tool, tmp_path): + local_packages(tmp_path, ["2899666869", "PRO EDITION"]) + fields, _ = run(catalog_tool, tmp_path, "browse", "0", "enter:1", "back", "enter:0", "back") + assert fields["view0"] == "|2|0" + assert fields["row1_0"] == "Arena|mcc_maps\\PRO EDITION\\arena" + assert fields["view2"] == "|2|1" + assert fields["row3_0"] == "Arena|mcc_maps\\2899666869\\arena" + assert fields["view4"] == "|2|0" + + +def test_collection_identity_uses_sidecar_without_steam(catalog_tool, tmp_path): + base = local_packages(tmp_path, ["MyPack"]) + (base / "MyPack/workshop_id.txt").write_text("2899666869\nPro Edition\n") + fields, _ = run(catalog_tool, tmp_path, "browse", "0", "enter:0") + assert fields["row0_0"] == "[PRO EDITION]|folder" + assert fields["row1_0"] == "Arena|mcc_maps\\MyPack\\arena" + + +def test_disabled_collections_keep_package_folders(catalog_tool, tmp_path, monkeypatch): + local_packages(tmp_path, ["2899747345"]) + monkeypatch.setenv("TEST_COLLECTIONS_DISABLED", "1") + fields, _ = run(catalog_tool, tmp_path, "browse", "0", "enter:0") + assert fields["view0"] == "|1|0" + assert fields["row0_0"] == "[MCC package]|folder" + assert fields["row1_0"] == "Arena|mcc_maps\\2899747345\\arena" + + +def test_campaign_browser_orders_explicit_missions_and_keeps_full_titles(catalog_tool, tmp_path, monkeypatch): + base = local_packages(tmp_path, ["Campaign"]) + for name in ("z10", "a10", "extra"): + (base / f"Campaign/{name}.map").write_bytes(header(scenario=0)) + (base / "Campaign/list.txt").write_text("z10.map\na10.map\nextra.map\n") + monkeypatch.setenv("TEST_MISSIONS", "z10,a10") + fields, maps = run(catalog_tool, tmp_path) + assert [m.split("|")[0] for m in maps] == ["mcc_maps\\Campaign\\z10", "mcc_maps\\Campaign\\a10", "mcc_maps\\Campaign\\extra"] + assert fields["next_0"] == "1|mcc_maps\\Campaign\\a10" + assert fields["next_1"] == "2|" and fields["next_2"] == "0|" + fields, _ = run(catalog_tool, tmp_path, "browse", "1", "enter:0", "back") + assert fields["row0_0"] == "[Example campaign]|folder" + assert fields["row1_0"] == "Explicit mission z10|mcc_maps\\Campaign\\z10" + assert fields["view2"] == "|1|0" + + +def test_missing_campaign_mission_is_not_skipped(catalog_tool, tmp_path, monkeypatch): + base = local_packages(tmp_path, ["Campaign"]) + for name in ("z10", "a10"): + (base / f"Campaign/{name}.map").write_bytes(header(scenario=0)) + (base / "Campaign/list.txt").write_text("z10.map\na10.map\n") + monkeypatch.setenv("TEST_MISSIONS", "z10,missing,a10") + fields, _ = run(catalog_tool, tmp_path) + assert fields["next_0"] == "-1|mcc_maps\\Campaign\\missing" + assert fields["next_1"] == "2|" + + +@pytest.mark.parametrize("candidates", [1, 2]) +def test_downloaded_campaign_does_not_splice_other_snapshots(catalog_tool, tmp_path, monkeypatch, candidates): + # The real catalog receives identical ordered metadata for every package. + # Even one same-Workshop candidate cannot prove the intended binary version: + # campaign JSON names missions but does not contain their gameplay digests. + # This is a catalog boundary test, not receipt validation or network testing. + first = "dl_" + "1" * 20 + folders = [first] + ["dl_" + str(i + 2) * 20 for i in range(candidates)] + install(tmp_path, {}) + root = tmp_path / "mcc_maps" + (root / "list.txt").write_text("\n".join("/" + name for name in folders)) + for index, folder in enumerate(folders): + package = root / folder + package.mkdir() + mission = "z10" if index == 0 else "a10" + (package / "list.txt").write_text(mission + ".map\n") + (package / (mission + ".map")).write_bytes(header(scenario=0, internal=f"revision_{index}")) + (package / "workshop_id.txt").write_text("12345\nExample campaign\n") + monkeypatch.setenv("TEST_MISSIONS", "z10,a10") + fields, maps = run(catalog_tool, tmp_path) + assert len(maps) == candidates + 1 + assert maps[0] == f"mcc_maps\\{first}\\z10|1" + assert fields["next_0"] == f"-1|mcc_maps\\{first}\\a10" + # The following mission remains available as an individual selection. + assert all(name.endswith("\\a10|1") for name in maps[1:]) + assert all(fields[f"next_{i}"] == "2|" for i in range(1, candidates + 1)) + + +def test_workshop_browser_keeps_title_longer_than_filename(catalog_tool, tmp_path): + local_packages(tmp_path, ["12345"]) + fields, _ = run(catalog_tool, tmp_path, "browse", "0", "enter:0", items=[("12345", "Item", "arena", "A much longer mission title")]) + assert fields["row1_0"] == "A much longer mission title|mcc_maps\\12345\\arena" + + +def test_imported_package_titles_do_not_depend_on_steam(catalog_tool,tmp_path,monkeypatch): + install(tmp_path,{}) + root=tmp_path/"mcc_maps" + (root/"list.txt").write_text("/12345\n") + (root/"12345").mkdir() + (root/"12345/list.txt").write_text("arena.map\n") + (root/"12345/arena.map").write_bytes(header(scenario=1)) + fields,_=run(catalog_tool,tmp_path,"browse","0","enter:0") + assert fields["row0_0"].startswith("[MCC package]|") + assert fields["row1_0"]=="Arena|mcc_maps\\12345\\arena" + monkeypatch.setenv("TEST_MENU_METADATA","1") + fields,_=run(catalog_tool,tmp_path,"browse","0","enter:0") + assert fields["row0_0"].startswith("[Offline package title]|") + assert fields["row1_0"]=="Authored offline level|mcc_maps\\12345\\arena" diff --git a/tools/test_mcc_media.py b/tools/test_mcc_media.py new file mode 100644 index 0000000000..c34adc1f5f --- /dev/null +++ b/tools/test_mcc_media.py @@ -0,0 +1,600 @@ +"""Asset-free codec vectors and stream ownership tests for MCC-only media. + +Compile the actual private routines, not copies. Pixel vectors check channel +ordering, partial blocks and BC7 mode 6. PCM tests independently decode the +serialized Xbox ADPCM blocks in Python, including stereo interleave. +""" +import math +import os +from pathlib import Path +import re +import shutil +import struct +import subprocess +import sys + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from harness import function, structure + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.fixture(scope="session") +def media_tool(tmp_path_factory): + clang = shutil.which("clang") + if not clang: + pytest.skip("clang is needed for the MCC media tests") + work = tmp_path_factory.mktemp("mcc-media") + audio = (ROOT / "port/linux/game/mcc_audio.c").read_text() + bitmap = (ROOT / "port/linux/game/mcc_bitmaps.c").read_text() + native_bitmap = (ROOT / "source/bitmaps/bitmaps.c").read_text() + native_swizzle = (ROOT / "source/rasterizer/rasterizer_swizzle.c").read_text() + hud = (ROOT / "port/linux/game/mcc_hud.c").read_text() + declarations = "\n".join(structure(audio, name) for name in ["mcc_audio_storage", "mcc_audio_tags", "mcc_pcm", "mcc_ima"]) + tables = "\n".join(re.search(r"static int const " + name + r"\[.*?\};", audio, re.S).group() + for name in ["mcc_ima_steps", "mcc_ima_changes"]) + functions = "\n".join(function(audio, name) for name in ["mcc_ima_advance", "mcc_ima_quantize", + "mcc_pcm_sample", "mcc_resampled", "mcc_audio_reserve", "mcc_audio_store", "mcc_audio_tag_storage", "mcc_audio_contains"]) + functions += "\n" + function(native_swizzle, "rasterizer_xbox_bitmap_get_max_mipmap_count") + functions += "\n" + function(native_bitmap, "bitmap_2d_address") + functions += "\n" + "\n".join(function(bitmap, name) for name in ["mcc_bitmap_bytes", "mcc_pixel", + "mcc_channels", "mcc_bitmap_decode", "mcc_morton_axis", "mcc_bitmap_pack"]) + functions += "\n" + function(hud, "mcc_hud_offset") + functions += "\n" + function(hud, "mcc_hud_scale") + functions += "\n" + function(hud, "mcc_hud_score_text") + source = r''' +#include +#include +#include +#include +#include +#define MIN(a,b) ((a)<(b)?(a):(b)) +#define MAX(a,b) ((a)>(b)?(a):(b)) +#define PIN(x,a,b) ((x)<(a)?(a):((x)>(b)?(b):(x))) +#define MCC_AUDIO_BASE 0x50000000u +#define MCC_AUDIO_LIMIT 0x10000000u +#define MCC_AUDIO_FRAME_LIMIT 0x1000000u +struct sound_permutation {struct {uint32_t file_offset,size;} samples; uint32_t sample_buffer_size; int compression;}; +struct mcc_runtime {void *audio;}; +static int test_reserve; +static size_t reserve_request; +static void *media_malloc(size_t n) { + if(test_reserve){reserve_request=n;return NULL;} + return malloc(n); +} +#define malloc media_malloc +struct hud_placement_definition {struct {short x,y;} offset;struct {float i,j;} scale; short multiplayer_scaling_flags,pad;}; +struct bitmap_data {short type,width,height,depth,format,mipmap_count;unsigned short flags;void *base_address;}; +typedef unsigned char byte; +#define FALSE 0 +#define NONE (-1) +#define _bitmap_type_2d 0 +#define _bitmap_has_power_of_two_dimensions_bit 0 +#define _bitmap_compressed_bit 1 +#define _bitmap_swizzled_bit 3 +#define _bitmap_linear_bit 4 +#define TEST_FLAG(value,bit) ((value)&(1u<<(bit))) +#define match_assert(file,line,condition) do {if(!(condition))abort();} while(0) +#define match_vassert(file,line,condition,description) match_assert(file,line,condition) +static int bitmap_verify(struct bitmap_data *bitmap,int pixels) {(void)bitmap;(void)pixels;return 1;} +static short floor_log2(unsigned value) {short result=0;while(value>1){value>>=1;result++;}return result;} +static long bitmap_format_get_bits_per_pixel(short format) {return format==14 ? 4 : 8;} +uint32_t global_vector_palette[256]; +#define BCDEC_STATIC +#define BCDEC_IMPLEMENTATION +#include "bcdec.h" +''' + declarations + "\n" + tables + "\n" + functions + r''' +int main(int argc,char **argv) { + if (argc<2) return 2; + if (!strcmp(argv[1],"audio-limit")) { + struct mcc_audio_storage output={0}; + output.limit=MCC_AUDIO_LIMIT-1; + test_reserve=1;output.used=MCC_AUDIO_LIMIT-32; + if(mcc_audio_reserve(&output,32) || reserve_request)return 40; + if(mcc_audio_reserve(&output,31) || reserve_request!=MCC_AUDIO_LIMIT-1)return 41; + output.used=MCC_AUDIO_LIMIT+1;reserve_request=0; + if(mcc_audio_reserve(&output,1) || reserve_request)return 42; + return 0; + } + if (!strcmp(argv[1],"audio")) { + int channels=atoi(argv[2]), input_rate=atoi(argv[3]), output_rate=atoi(argv[4]); + struct mcc_audio_storage output={0}; + output.limit=MCC_AUDIO_LIMIT-1; + struct sound_permutation permutation={0}; + struct mcc_pcm pcm; + uint32_t i; + pcm.frames=4096;pcm.channels=channels;pcm.rate=input_rate; + pcm.samples=malloc(pcm.frames*channels*sizeof(short)); + for (i=0;i>level)/4,1)*block; + unsigned char *address=bitmap_2d_address(&bitmap,0,0,(short)level); + if(address!=packed+1+offset || memcmp(address,input+offset,size))return 34; + offset+=size; + } + if(offset!=source_bytes || packed[0]!=0xDD || packed[allocation+1]!=0xDD)return 35; + for(i=source_bytes;i> (frame % 2 * 4) & 15 + value = steps[step] + delta = value // 8 + (value // 4 if code & 1 else 0) + (value // 2 if code & 2 else 0) + (value if code & 4 else 0) + predictor = max(-32768, min(32767, predictor + (-delta if code & 8 else delta))) + step = max(0, min(88, step + adjustments[code & 7])) + samples[channel].append(predictor) + return samples + + +@pytest.mark.parametrize("channels,source_rate,target_rate", [(1,22050,22050),(2,44100,44100),(1,44100,22050)]) +def test_xbox_adpcm_waveform(media_tool, tmp_path, channels, source_rate, target_rate): + target = tmp_path / "encoded.bin" + run(media_tool, "audio", channels, source_rate, target_rate, target) + data = target.read_bytes() + frames = 4096 * target_rate // source_rate + assert len(data) == ((frames + 63) // 64) * 36 * channels + decoded = decode_adpcm(data, channels) + for channel in range(channels): + signal = [(math.sin(i * source_rate / target_rate * 0.035) * 14000 if channel == 0 + else math.cos(i * source_rate / target_rate * 0.051) * 9000) for i in range(frames)] + # Skip the initial codec predictor warmup; wrong stereo block order + # or sample-rate conversion produces errors thousands of times larger. + rms = math.sqrt(sum((decoded[channel][i] - signal[i]) ** 2 for i in range(64, frames)) / (frames - 64)) + assert rms < 160 + + +def test_virtual_audio_ranges_do_not_alias_raw_file(media_tool): + run(media_tool, "contains") + + +def test_hud_canvas_and_bitmap_scale_are_independent(media_tool): + run(media_tool, "hud") + + +def test_mcc_score_hint_resolves_binding_without_mutating_source(media_tool): + run(media_tool, "score-hint") + + +def test_hardware_packing_swizzle_rows_faces_and_mips(media_tool): + run(media_tool, "pack") + + +def test_cpu_dxt_tiny_mips_preserve_source_at_native_addresses(media_tool): + run(media_tool, "compressed-tail") + + +def test_shared_bitmap_consumers_get_independent_metadata(tmp_path): + clang = shutil.which("clang") + if not clang: + pytest.skip("clang is needed for the MCC bitmap ownership test") + bitmap = (ROOT / "port/linux/game/mcc_bitmaps.c").read_text() + header = (ROOT / "source/bitmaps/bitmap_group.h").read_text() + declarations = "\n".join(structure(header, n) for n in ["bitmap_data", "bitmap_group_sprite", + "bitmap_group_sequence", "bitmap_group"]) + declarations += "\n" + "\n".join(structure(bitmap, n) for n in ["mcc_texture", "mcc_bitmap_clone", "mcc_textures"]) + routines = "\n".join(function(bitmap, n) for n in ["mcc_bitmap_tag", "mcc_bitmap_block", + "mcc_bitmap_clone_block", "mcc_bitmap_specialize", "mcc_bitmaps_contains", "mcc_bitmaps_read"]) + source = r''' +#include +#include +#include +#include +typedef float real; +union point2d {struct {short x,y;};uint32_t n;}; +typedef struct {float x0,x1,y0,y1;} real_rectangle2d; +typedef struct {float x,y;} real_point2d; +struct tag_block {long count;void *address,*definition;}; +struct tag_data {long size,flags,file_offset;void *address,*definition;}; +#define BITMAP_GROUP_TAG 'bitm' +#define MCC_BITMAP_BASE 0x60000000u +struct mcc_runtime {unsigned char *tags,*tag_index;uint32_t used;struct {uint32_t tag_count;} report;void *bitmaps;}; +static void *mcc_runtime_pointer(struct mcc_runtime *r,uint32_t p,uint32_t size) { + uintptr_t start=(uintptr_t)r->tags; + return p>=start && p-start<=r->used && size<=r->used-(p-start) ? (void *)(uintptr_t)p : NULL; +} +static void *mcc_runtime_allocate(struct mcc_runtime *r,uint32_t size) { + uint32_t at=(r->used+15)&~15u; + if(size>65536-at)return NULL; + r->used=at+size;return r->tags+at; +} +''' + declarations + '\n' + routines + r''' +int main(void) { + struct mcc_runtime r={0};struct mcc_textures textures={0}; + struct bitmap_group *original,*copy,*meter;struct bitmap_data *pixels; + struct bitmap_group_sequence *sequence;struct bitmap_group_sprite *sprite; + uint32_t *entry,source=0xE1740000,material=source,meter_handle=source,repeated=source; + r.tags=calloc(1,65536);r.tag_index=r.tags;r.used=512;r.report.tag_count=1; + original=mcc_runtime_allocate(&r,sizeof(*original));pixels=mcc_runtime_allocate(&r,sizeof(*pixels)); + sequence=mcc_runtime_allocate(&r,sizeof(*sequence));sprite=mcc_runtime_allocate(&r,sizeof(*sprite)); + original->bitmaps.count=1;original->bitmaps.address=pixels; + original->sequences.count=1;original->sequences.address=sequence; + sequence->sprites.count=1;sequence->sprites.address=sprite; + pixels->width=64;pixels->pixels_offset=2048;sprite->bitmap_index=0; + entry=(uint32_t *)r.tag_index;entry[0]='bitm';entry[3]=source;entry[5]=(uint32_t)original; + textures.capacity=8;textures.tag_capacity=8; + textures.items=calloc(8,sizeof(*textures.items));textures.clones=calloc(8,sizeof(*textures.clones)); + if(!mcc_bitmap_specialize(&r,&textures,&material,2) || material==source || r.report.tag_count!=2)return 1; + copy=mcc_bitmap_tag(&r,material,'bitm',sizeof(*copy)); + if(!copy || copy==original || copy->bitmaps.address==pixels || copy->sequences.address==sequence)return 2; + if(((struct bitmap_group_sequence *)copy->sequences.address)->sprites.address==sprite)return 3; + ((struct bitmap_data *)copy->bitmaps.address)->width=32; + if(pixels->width!=64 || pixels->pixels_offset!=2048)return 4; + if(!mcc_bitmap_specialize(&r,&textures,&repeated,2) || repeated!=material || r.report.tag_count!=2)return 5; + if(!mcc_bitmap_specialize(&r,&textures,&meter_handle,4) || meter_handle==material || r.report.tag_count!=3)return 6; + meter=mcc_bitmap_tag(&r,meter_handle,'bitm',sizeof(*meter)); + if(!meter || ((struct bitmap_data *)meter->bitmaps.address)->width!=64)return 7; + if(textures.items[0].channels!=2 || textures.items[1].channels!=4)return 8; + r.bitmaps=&textures;textures.items[0].offset=MCC_BITMAP_BASE;textures.items[0].size=128; + textures.items[0].pixels=calloc(1,128);textures.items[0].pixels[127]=0xAB; + { + unsigned char out[3]={0xCC,0,0xDD}; + if(!mcc_bitmaps_contains(&r,MCC_BITMAP_BASE,128) || mcc_bitmaps_contains(&r,MCC_BITMAP_BASE,129))return 9; + if(mcc_bitmaps_read(&r,material,MCC_BITMAP_BASE+127,1,out+1)!=1 || out[1]!=0xAB || out[0]!=0xCC || out[2]!=0xDD)return 10; + if(mcc_bitmaps_read(&r,source,MCC_BITMAP_BASE,1,out+1)!=0 || mcc_bitmaps_read(&r,material,MCC_BITMAP_BASE+127,2,out+1)!=0)return 11; + if(mcc_bitmaps_read(&r,material,2048,1,out+1)!=-1)return 12; + } + free(textures.items[0].pixels); + free(textures.clones);free(textures.items);free(r.tags);return 0; +} +''' + path = tmp_path / "ownership.c" + path.write_text(source) + output = tmp_path / ("ownership.exe" if sys.platform == "win32" else "ownership") + command = [clang, "-std=gnu99", "-O2", "-Wall", "-Wextra", "-Werror", "-Wno-multichar", str(path), "-o", str(output)] + if sys.platform == "win32": + command[1:1] = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld", "-D_CRT_SECURE_NO_WARNINGS"] + else: + command[1:1] = ["-m32"] + result = subprocess.run(command, capture_output=True, text=True) + assert result.returncode == 0, result.stderr + run(output) + + +def test_mcc_owned_pixels_survive_pressure_without_legacy_cache(tmp_path): + """Direct bindings retain original pixels above the legacy staging budget.""" + clang = shutil.which("clang") + if not clang: + pytest.skip("clang is needed for MCC bitmap ownership tests") + bitmap = (ROOT / "port/linux/game/mcc_bitmaps.c").read_text() + declarations = "\n".join(structure(bitmap, n) for n in ["mcc_texture", "mcc_bitmap_clone", "mcc_textures"]) + routines = "\n".join(function(bitmap, n) for n in [ + "mcc_bitmap_valid_texture", "mcc_bitmaps_valid", "mcc_bitmaps_pixels", "mcc_bitmaps_dispose"]) + source = r''' +#include +#include +#include +#include +#include "halo_port_capacity.h" +#define FALSE 0 +#define NONE (-1) +struct bitmap_data { + uint32_t tag_index,pixels_offset,pixels_size; + short width,height,depth,format,mipmap_count; + void *base_address; +}; +struct mcc_runtime {void *bitmaps;}; +static int verify_calls,size_calls; +static int bitmap_verify(struct bitmap_data *bitmap,int import) { + (void)import; + verify_calls++; + return bitmap->width==2048 && bitmap->height==2048 && bitmap->depth==1 && + bitmap->format==11 && bitmap->mipmap_count==11; +} +static long rasterizer_xbox_bitmap_get_pixel_data_size(struct bitmap_data *bitmap) { + (void)bitmap;size_calls++;return 22369664; +} +''' + declarations + '\n' + routines + r''' +static void check_lookup(struct mcc_runtime *runtime,struct bitmap_data *bitmap, + struct mcc_texture const *expected,int verify_count,int size_count) { + struct bitmap_data before; + uint32_t bytes=123; + int coverage=99; + void const *pixels; + if(bitmap)memcpy(&before,bitmap,sizeof(before)); + verify_calls=size_calls=0; + pixels=mcc_bitmaps_pixels(runtime,bitmap,&bytes,&coverage); + assert(pixels==(expected ? expected->pixels : NULL)); + assert(bytes==(expected ? expected->size : 0)); + assert(coverage==(expected ? expected->channels==4 : 0)); + assert(verify_calls==verify_count && size_calls==size_count); + if(bitmap)assert(!memcmp(bitmap,&before,sizeof(before))); + /* valid requires a runtime; pixels also accepts a missing runtime. */ + if(runtime) { + verify_calls=size_calls=0; + assert(mcc_bitmaps_valid(runtime,bitmap)==(expected!=NULL)); + assert(verify_calls==verify_count && size_calls==size_count); + if(bitmap)assert(!memcmp(bitmap,&before,sizeof(before))); + } +} +int main(void) { + enum {count=13,chain_bytes=22369664}; + struct bitmap_data bitmaps[count],copy; + struct mcc_texture items[count]; + struct mcc_textures textures={0}; + struct mcc_runtime runtime; + uint32_t bytes,i,frame,offset=0x60000000; + memset(bitmaps,0,sizeof(bitmaps));memset(items,0,sizeof(items)); + textures.items=items;textures.count=count;runtime.bitmaps=&textures; + /* Thirteen real 2K ARGB mip chains exceed the desktop cache's 256MiB. + * Only boundary pages need touching: the API must return, never copy, + * the owned immutable allocation, so no legacy allocator is linked. */ + if((uint64_t)count*chain_bytes<=HALO_PORT_TEXTURE_CACHE_SIZE)return 1; + for(i=0;itag_index=0xE1000000+i;bitmap->pixels_offset=offset;bitmap->pixels_size=chain_bytes; + bitmap->width=bitmap->height=2048;bitmap->depth=1;bitmap->format=11;bitmap->mipmap_count=11; + item->bitmap=bitmap;item->handle=bitmap->tag_index;item->offset=offset;item->size=chain_bytes; + item->pixels=malloc(chain_bytes);if(!item->pixels)return 2; + item->pixels[0]=(unsigned char)i;item->pixels[chain_bytes-1]=(unsigned char)(255-i); + offset+=chain_bytes; + } + for(frame=0;frame<3;frame++)for(i=0;iitems=calloc(2,sizeof(*owned->items));owned->count=2; + owned->items[0].pixels=malloc(128);owned->items[0].bitmap=&bitmaps[0]; + owned->items[1].pixels=malloc(128);owned->items[1].bitmap=&bitmaps[1]; + bitmaps[0].base_address=owned->items[0].pixels;bitmaps[1].base_address=&foreign; + runtime.bitmaps=owned;mcc_bitmaps_dispose(&runtime); + if(runtime.bitmaps || bitmaps[0].base_address || bitmaps[1].base_address!=&foreign)return 14; + mcc_bitmaps_dispose(&runtime); + } + return 0; +} +''' + path = tmp_path / "residency.c" + path.write_text(source) + output = tmp_path / ("residency.exe" if sys.platform == "win32" else "residency") + command = [clang, "-std=gnu99", "-O2", "-Wall", "-Wextra", "-Werror", + "-I", str(ROOT / "port/linux/include"), str(path), "-o", str(output)] + if sys.platform == "win32": + command[1:1] = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld", "-D_CRT_SECURE_NO_WARNINGS"] + result = subprocess.run(command, capture_output=True, text=True) + assert result.returncode == 0, result.stderr + run(output) + + +def pixel_vector(media_tool, tmp_path, data, format, usage=0, side=4): + path = tmp_path / "block.bin" + path.write_bytes(data) + return [int(line, 16) for line in run(media_tool, "pixels", format, usage, side, path).splitlines()] + + +def test_bc1_red_and_partial_block(media_tool, tmp_path): + block = struct.pack(" +#include +#include +#include +#include +#define MAP_FAILED ((void *)-1) +#define MAP_PRIVATE 1 +#define MAP_ANONYMOUS 2 +#define MAP_NORESERVE 4 +#define MAP_FIXED_NOREPLACE 8 +#define MAP_FIXED 16 +#define PROT_NONE 0 +#define PROT_READ 1 +#define PROT_WRITE 2 +#define __attribute__(x) +#define platform_log(...) ((void)0) +static void *owned; +static int blocked, commit_fail, maps, releases, wrong_address; +static void *mmap(void *p, unsigned n, int prot, int flags, int fd, long offset) { + (void)fd;(void)offset; maps++; + if(n!=0x4000000u) {fprintf(stderr,"size\n");return MAP_FAILED;} + if(flags & MAP_FIXED) { + if(p!=owned || !owned) {fprintf(stderr,"foreign replacement\n");return MAP_FAILED;} + if(prot && commit_fail) {errno=ENOMEM;return MAP_FAILED;} + return p; + } + if(!(flags & MAP_FIXED_NOREPLACE) || blocked || owned) {errno=ENOMEM;return MAP_FAILED;} + owned=wrong_address ? (void *)(uintptr_t)0x60000000u : p; + return owned; +} +static int munmap(void *p, unsigned n) { + if(p!=owned || !p || n!=0x4000000u) return -1; + owned=NULL; releases++; return 0; +} +''' + ("\n#define HALO_WINDOWS 1\n" if windows else "") + implementation() + r''' +#define CHECK(c) do {if(!(c)) {fprintf(stderr,"line %d\n",__LINE__);return 1;}}while(0) +int main(void) { + void *p; int before; + CHECK(!mcc_memory_reserve(0x40440000u,0x4000000u)); + CHECK(!mcc_memory_reserve(0x50000001u,0x4000000u)); + CHECK(!mcc_memory_reserve(0x50000000u,0x4000001u)); + CHECK(!mcc_memory_reserve(0x71000000u,0x4000000u)); + CHECK(maps==0); + blocked=1; +#ifdef HALO_WINDOWS + mcc_window_initialize(); CHECK(!mcc_window); +#endif + CHECK(!mcc_memory_reserve(0x50000000u,0x4000000u)); + CHECK(!owned && !releases); + blocked=0; + wrong_address=1; + CHECK(!mcc_memory_reserve(0x50000000u,0x4000000u)); + CHECK(!owned && releases==1); + wrong_address=0; +#ifdef HALO_WINDOWS + mcc_window_initialize(); CHECK(owned && !mcc_window_active); + commit_fail=1; + CHECK(!mcc_memory_reserve(0x50000000u,0x4000000u)); + CHECK(owned && !mcc_window_active); commit_fail=0; +#endif + p=mcc_memory_reserve(0x50000000u,0x4000000u); CHECK(p); + before=maps; +#ifdef HALO_WINDOWS + CHECK(!mcc_memory_reserve(0x60000000u,0x4000000u)); CHECK(maps==before); +#else + (void)before; +#endif + mcc_memory_release(NULL,0); + mcc_memory_release(p,0x4000000u); +#ifdef HALO_WINDOWS + CHECK(owned==p && !mcc_window_active); +#else + CHECK(!owned); +#endif + CHECK(mcc_memory_reserve(0x50000000u,0x4000000u)==p); + mcc_memory_release(p,0x4000000u); + /* A nonstandard base overlapping the default window is still accepted. */ + p=mcc_memory_reserve(0x51000000u,0x4000000u); CHECK(p==(void *)(uintptr_t)0x51000000u); + mcc_memory_release(p,0x4000000u); +#ifdef HALO_WINDOWS + mcc_window_dispose(); +#endif + CHECK(!owned);return 0; +} +''' + source = tmp_path / "memory.c" + source.write_text(code) + binary = compile_tool(tmp_path, [source]) + subprocess.run([str(binary)], check=True, capture_output=True, text=True) + + +@pytest.mark.skipif(sys.platform != "win32", reason="Windows reservation semantics") +def test_windows_pages_are_reserved_decommitted_and_zeroed_on_reload(tmp_path): + posix = (ROOT / "port/windows/src/win32_posix.c").read_text() + code = r''' +#include +#include +#include +#include +#include +#define HALO_WINDOWS 1 +#define platform_log(...) ((void)0) +static int errno_from_windows_error(DWORD e) {(void)e;return ENOMEM;} +''' + '#include "' + (ROOT / "port/windows/include/posix/sys/mman.h").as_posix() + '"\n' + "\n".join(function(posix, name) for name in + ["windows_protection", "address_reserved", "mmap", "munmap"]) + implementation() + r''' +#define CHECK(c) do{if(!(c)){fprintf(stderr,"line %d\n",__LINE__);return 1;}}while(0) +int main(void) { + MEMORY_BASIC_INFORMATION info; + unsigned char *p; + CHECK(mcc_window==(void *)(uintptr_t)0x50000000u); + CHECK(VirtualQuery(mcc_window,&info,sizeof(info)) && info.State==MEM_RESERVE); + CHECK(!VirtualAlloc(mcc_window,65536,MEM_RESERVE,PAGE_NOACCESS)); + p=mcc_memory_reserve(0x50000000u,0x4000000u);CHECK(p); + p[0]=42;p[0x3ffffff]=43; + mcc_memory_release(p,0x4000000u); + CHECK(VirtualQuery(p,&info,sizeof(info)) && info.State==MEM_RESERVE); + CHECK(mcc_memory_reserve(0x50000000u,0x4000000u)==p); + CHECK(p[0]==0 && p[0x3ffffff]==0); + mcc_memory_release(p,0x4000000u); + CHECK(mcc_memory_reserve(0x51000000u,0x4000000u)); + mcc_memory_release((void *)(uintptr_t)0x51000000u,0x4000000u); + CHECK(mcc_memory_reserve(0x50000000u,0x4000000u)==p); + mcc_memory_release(p,0x4000000u); + return 0; +} +''' + source = tmp_path / "memory.c" + source.write_text(code) + binary = compile_tool(tmp_path, [source]) + subprocess.run([str(binary)], check=True, capture_output=True, text=True) diff --git a/tools/test_mcc_menu.py b/tools/test_mcc_menu.py new file mode 100644 index 0000000000..c344f9b92b --- /dev/null +++ b/tools/test_mcc_menu.py @@ -0,0 +1,374 @@ +"""Run the real MCC menu dispatch against narrow widget/catalog stubs. + +The mixed catalog deliberately gives filtered rows different absolute indices. +No game assets or rendering are required to check navigation and launch routes. +""" +import os +from pathlib import Path +import re +import shutil +import subprocess + +import pytest +from harness import function + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.fixture(scope="session") +def menu_tool(tmp_path_factory): + compiler = os.environ.get("CC") or shutil.which("clang") or shutil.which("cc") + if not compiler: + pytest.skip("a C compiler is needed for MCC menu tests") + implementation = (ROOT / "port/linux/game/menu_functions.c").read_text() + kinds = re.search(r"enum\s*\{\s*MAP_KIND_SINGLEPLAYER,.*?\};", implementation, re.S).group() + states = "\n".join(re.search(r"static struct\s*\{[^}]*\}\s*" + name + r";", + implementation, re.S).group() + for name in ["mcc_solo_list", "level_list", "map_list", "mcc_host_list"]) + names = ["map_kind_mcc", "map_kind_singleplayer", "map_kind_shown", "map_kind_first", "mcc_browser_focus", "mcc_solo_folder_choose", + "mcc_solo_choose", "mcc_solo_back", "mcc_host_list_choose", "level_list_update", + "map_list_update", "map_list_back", "mcc_host_back", "level_list_initialize", "map_list_initialize"] + source = r''' +#include +#include +#include +#include +typedef int boolean; +#include "mcc_maps.h" +#define TRUE 1 +#define FALSE 0 +#define NONE (-1) +#define MAP_KIND_ROWS 10 +#define NUMBER_OF_GAME_DIFFICULTY_LEVELS 4 +#define LEVEL_UNAVAILABLE 99 +#define NUMBER_OF_SINGLE_PLAYER_LEVELS 10 +#define SOUND_FORWARD 1 +#define SOUND_BACK 2 +#define SERVER_SETUP_NAME "server_setup" +#define MIN(a,b) ((a)<(b)?(a):(b)) +#define MAX(a,b) ((a)>(b)?(a):(b)) +#define PIN(x,a,b) ((x)<(a)?(a):((x)>(b)?(b):(x))) +#define csmemset memset +enum {MAP_STEP_MAPS, MAP_STEP_DIFFICULTIES}; +struct player_profile {int last_single_player_map_played;}; +struct widget_instance {char const *name;struct {struct {short selected_index;struct widget_instance *extended_description;} list;} parameters;}; +static struct widget_instance spinner, description, list; +static void map_screen_row_text(short entry,wchar_t *text){(void)entry;*text=0;} +/* Presentation belongs to the frontend module; this fixture checks map selection. */ +static void frontend_multiplayer_difficulty(struct widget_instance *widget,short chosen){(void)widget;(void)chosen;} +static struct {short shown_level,saved_level;struct {boolean available;void *finished;} levels[10];} campaign; +static int no_spinner, empty_catalog, failed, launched, deferred, cooperated, multiplayer; +static int opened, backed, last_controller, last_difficulty, last_sound, focus_first, focus_chosen; +static int solo_updated, host_updated, legacy_updated; +static char last_level[40]; +''' + kinds + '\n' + states + r''' +static struct mcc_map_browser mcc_solo_browsers[2],mcc_host_browsers[2]; +static struct widget_instance *named(struct widget_instance *widget,char const *name,short marker) { + (void)widget;(void)marker; + if(!strcmp(name,"solo_level_select_list") || !strcmp(name,"mp_map_select_list_2"))return &list; + return !strcmp(name,"list_item_0_map_kind_spinner") ? (no_spinner ? NULL : &spinner) : &description; +} +/* A sorted mixed catalog: MP, SP, MP, SP, MP. */ +short mcc_maps_type_count(boolean singleplayer) {return empty_catalog ? 0 : singleplayer ? 2 : 3;} +short mcc_maps_type_index(short row,boolean singleplayer) { + if (row<0 || row>=mcc_maps_type_count(singleplayer))return NONE; + return singleplayer ? row*2+1 : row*2; +} +char const *mcc_maps_level_name(short index) { + static char const *names[]={"mcc_maps\\mp0","mcc_maps\\sp0","mcc_maps\\mp1","mcc_maps\\sp1","mcc_maps\\mp2"}; + return index<0 || index>=5 ? NULL : names[index]; +} +boolean mcc_maps_campaign(short index) {return index==1 || index==3;} +void mcc_map_browser_open(struct mcc_map_browser *b,boolean campaign) { + short i;b->campaign=campaign;b->count=mcc_maps_type_count(campaign);if(b->chosen>=b->count)b->chosen=0; + for(i=0;icount;i++){b->entries[i]=mcc_maps_type_index(i,campaign);b->folders[i]=FALSE;} +} +short mcc_map_browser_index(struct mcc_map_browser const *b,short row) { + return row>=0 && rowcount && !b->folders[row] ? b->entries[row] : NONE; +} +void mcc_map_browser_select(struct mcc_map_browser *b,short row) {b->chosen=row;} +boolean mcc_map_browser_enter(struct mcc_map_browser *b,short row) { + if(row<0 || row>=b->count || !b->folders[row])return FALSE; + strcpy(b->package,"package");b->folders[row]=FALSE;b->chosen=0;return TRUE; +} +boolean mcc_map_browser_back(struct mcc_map_browser *b) { + if(!b->package[0])return FALSE;b->package[0]=0;b->chosen=1;return TRUE; +} +static boolean campaign_profile(short controller,struct player_profile *profile) {(void)profile;last_controller=controller;profile->last_single_player_map_played=0;return TRUE;} +static boolean campaign_fail(void) {failed++;return FALSE;} +static void main_set_map_name(char const *name) {strcpy(last_level,name);} +static void main_defer_map_map_change(void) {deferred++;} +static short main_get_difficulty(void) {return 2;} +static void campaign_start(char const *name,short difficulty,short controller) { + launched++;strcpy(last_level,name);last_difficulty=difficulty;last_controller=controller; +} +static boolean ui_widget_port_mcc_cooperative_level_choose(char const *name,short difficulty) { + cooperated++;strcpy(last_level,name);last_difficulty=difficulty;return TRUE; +} +static boolean ui_widget_port_mcc_multiplayer_map_choose(char const *name) { + multiplayer++;strcpy(last_level,name);return TRUE; +} +static boolean ui_widget_port_open(struct widget_instance *widget,char const *name,boolean *deleted) { + (void)widget; if(strcmp(name,SERVER_SETUP_NAME))exit(70);opened++;*deleted=TRUE;return TRUE; +} +static void mcc_maps_rescan_stub(void) {} +#define mcc_maps_rescan mcc_maps_rescan_stub +static void campaign_levels_read(struct player_profile *p) {(void)p;campaign.saved_level=NONE;campaign.levels[0].available=TRUE;} +static short ui_widget_port_multiplayer_maps(char const *const **names,short *last) {*names=NULL;*last=0;return 1;} +static void map_kind_set(struct widget_instance *widget,short kind) {(void)widget;spinner.parameters.list.selected_index=kind;} +static void *global_network_game_server_get(void) {return &list;} +static boolean network_game_is_splitscreen_local(void) {return FALSE;} +static void custom_edition_maps_look_again(void) {} +static short xbox_multiplayer_map_count(short count) {return count;} +static short focused_row(struct widget_instance *widget) {(void)widget;return 0;} +static void focus_row(struct widget_instance *widget,short row) {(void)widget;(void)row;} +static void map_kind_focus(struct widget_instance *widget,short first,short chosen) {(void)widget;focus_first=first;focus_chosen=chosen;} +static void ui_play_audio_feedback_sound(short sound) {last_sound=sound;} +static void ui_widget_port_go_back(struct widget_instance *widget) {(void)widget;backed++;} +static void map_step_open(struct widget_instance *widget,short step,short entry) { + (void)widget;map_list.step=step;map_list.chosen=entry; +} +static void mcc_solo_list_update(struct widget_instance *widget) {(void)widget;solo_updated++;} +static void mcc_host_list_update(struct widget_instance *widget) {(void)widget;host_updated++;} +static short map_kind_count(short kind,short count) {(void)kind;(void)count;return 3;} +static short map_step_count(void) {return 3;} +static void map_difficulty_text(short entry,wchar_t *text) {(void)entry;(void)text;} +static void map_level_text(short entry,wchar_t *text) {(void)entry;(void)text;} +static void level_row_text(short entry,wchar_t *text) {(void)entry;(void)text;} +static void multiplayer_map_text(short entry,wchar_t *text) {(void)entry;(void)text;} +static void custom_campaign_map_text(short entry,wchar_t *text) {(void)entry;(void)text;} +static void custom_multiplayer_map_text(short entry,wchar_t *text) {(void)entry;(void)text;} +static short map_kind_rows_update(struct widget_instance *widget,short *first,short count,void(*text)(short,wchar_t *)) { + (void)widget;(void)first;(void)count;(void)text;legacy_updated++;return NONE; +} +static short map_kind_display_index(short kind,short entry) {(void)kind;return entry;} +static void map_description_show(struct widget_instance *widget,short level,short map) {(void)widget;(void)level;(void)map;} +static void visible_set(struct widget_instance *widget,boolean visible) {(void)widget;(void)visible;} +static void profile_name_show(struct widget_instance *widget) {(void)widget;} +static void level_description(struct widget_instance *widget,char const *prefix,short level,boolean saved,void *finished,short controller) { + (void)widget;(void)prefix;(void)level;(void)saved;(void)finished;(void)controller; +} +''' + '\n'.join(function(implementation, name) for name in names) + r''' +#define CHECK(c,n) do {if(!(c)){fprintf(stderr,"check %d failed\n",n);return n;}} while(0) +int main(int argc,char **argv) { + boolean deleted=FALSE; + if(argc<2)return 99; + list.name="fixture_list"; + list.parameters.list.extended_description=&description; + {int i;for(i=0;i<2;i++){mcc_map_browser_open(&mcc_solo_browsers[i],i);mcc_map_browser_open(&mcc_host_browsers[i],i);}} + if(!strcmp(argv[1],"kinds")) { + int i;printf("%d\n",NUMBER_OF_MAP_KINDS); + for(i=0;iweapon_index", + "backpack_1_argl: this is not a valid object name.", + "timer_minutes: i expected a value of type long"]) +def test_loader_success_cannot_hide_fatal_script_error(fatal): + assert not check_result(LOADED + "\n" + fatal, MARKER, MARKER, "b40", 0)["passed"] + + +@pytest.mark.parametrize("console", ["", '(begin (sleep 150) (print "mcc_smoke_test"))', + "previous_mcc_smoke_test"]) +def test_requires_actual_delayed_output(console): + assert not check_result(LOADED, console, MARKER, "b40", 0)["passed"] + + +def test_completed_simulation_and_normal_exit(): + assert check_result(LOADED, "\r\nmcc_smoke_test\r\n", MARKER, "b40", 0)["passed"] + assert not check_result(LOADED, MARKER, MARKER, "b40", 1)["passed"] + assert not check_result(LOADED, MARKER, MARKER, "a10", 0)["passed"] + + +def arguments(tmp_path, *maps, options=()): + executable = tmp_path / "original" / "halo.exe" + executable.parent.mkdir(exist_ok=True) + executable.write_bytes(b"executable") + (executable.parent / "SDL3.dll").write_bytes(b"library") + data = tmp_path / "data" + (data / "maps").mkdir(parents=True, exist_ok=True) + (data / "maps" / "ui.map").write_bytes(b"menu") + return ["--executable", str(executable), "--data-root", str(data), + "--output", str(tmp_path / "runs"), *options, *maps] + + +def test_workshop_virtual_map_without_local_copy(tmp_path, monkeypatch): + steam = tmp_path / "Steam" + steam.mkdir() + args = smoke.parse_args(arguments(tmp_path, r"mcc_maps\12345\a10", + options=("--workshop", "--steam-root", str(steam), "--campaigns"))) + assert args.maps == ["12345/a10"] + assert not (args.data_root / "mcc_maps").exists() + monkeypatch.setenv("HALO_NETWORK_TEST", "join") + monkeypatch.setenv("HALO_STEAM_ROOT", "wrong installation") + monkeypatch.setenv("HALO_NULL_RENDERER", "1") + environment = smoke.case_environment(args, tmp_path / "case") + assert "HALO_NETWORK_TEST" not in environment + assert "HALO_NULL_RENDERER" not in environment + assert environment["HALO_WORKSHOP_MAPS"] == "1" + assert environment["HALO_MCC_CAMPAIGNS"] == "1" + assert environment["HALO_STEAM_ROOT"] == str(steam.resolve()) + assert environment["HALO_LOG_ROOT"] == str(tmp_path / "case") + + +@pytest.mark.skipif(os.name != "nt", reason="Windows launcher") +def test_main_accepts_workshop_and_runs_cases_in_order(tmp_path, monkeypatch): + argv = arguments(tmp_path, "12345/a10", "67890/b40", options=("--workshop",)) + calls = [] + def run(args, name, binary): + assert binary.read_bytes() == b"executable" + calls.append(name) + return {"map": name, "passed": True, "process_stopped": True} + monkeypatch.setattr(smoke, "run_case", run) + monkeypatch.setattr(sys, "argv", ["mcc_native_smoke.py", *argv]) + assert smoke.main() == 0 + assert calls == ["12345/a10", "67890/b40"] + assert not list((tmp_path / "runs").rglob("*.exe")) + assert not list((tmp_path / "runs").rglob("*.dll")) + assert (tmp_path / "original" / "halo.exe").read_bytes() == b"executable" + + +@pytest.mark.skipif(os.name != "nt", reason="Windows launcher") +def test_launcher_error_stops_following_cases(tmp_path, monkeypatch): + argv = arguments(tmp_path, "12345/a10", "67890/b40", options=("--workshop",)) + calls = [] + def fail(args, name, binary): + calls.append(name) + return {"map": name, "passed": False, "process_stopped": True, + "launcher_error": "cannot restore init"} + monkeypatch.setattr(smoke, "run_case", fail) + monkeypatch.setattr(sys, "argv", ["mcc_native_smoke.py", *argv]) + assert smoke.main() == 1 + assert calls == ["12345/a10"] + assert not list((tmp_path / "runs").rglob("*.exe")) + + +@pytest.mark.parametrize("name", ["b40", "package/b40"]) +def test_existing_local_invocation_keeps_discovery_disabled(tmp_path, name): + argv = arguments(tmp_path, name) + level = tmp_path / "data" / "mcc_maps" / (name + ".map") + level.parent.mkdir(parents=True) + level.write_bytes(b"map") + args = smoke.parse_args(argv) + environment = smoke.case_environment(args, tmp_path / "case") + assert args.maps == [name] + assert environment["HALO_WORKSHOP_MAPS"] == "0" + assert environment["HALO_MCC_CAMPAIGNS"] == "0" + assert environment["HALO_STEAM_ROOT"] == "" + + +@pytest.mark.parametrize("name,options", [ + ("12345/a10", ()), + ("package/a10", ("--workshop",)), + ("../a10", ("--workshop",)), + ("12345/a10;quit", ("--workshop",)), + ("12345/" + "a" * 50, ("--workshop",)), + ("12345/a10", ("--port", "0", "--workshop")), + ("12345/a10", ("--port", "65536", "--workshop")), + ("12345/a10", ("--seconds", "19", "--workshop")), + ("12345/a10", ("--steam-root", ".")), +]) +def test_invalid_requests_fail_before_starting(tmp_path, monkeypatch, name, options): + monkeypatch.setattr(smoke.subprocess, "Popen", lambda *a, **k: pytest.fail("started a game")) + with pytest.raises(SystemExit): + smoke.parse_args(arguments(tmp_path, name, options=options)) + assert not (tmp_path / "runs").exists() + + +def test_cleanup_removes_only_owned_regular_map_caches(tmp_path): + case = tmp_path / "case" + cache = case / "saves" / "z" + cache.mkdir(parents=True) + (cache / "cache000.map").write_bytes(b"abc") + (cache / "cache001.map").write_bytes(b"de") + (cache / "savegame.bin").write_bytes(b"save") + (cache / "other.map").write_bytes(b"retained") + report = smoke.cleanup_map_caches(case) + assert report["removed_files"] == 2 and report["removed_bytes"] == 5 + assert (cache / "savegame.bin").read_bytes() == b"save" + assert (cache / "other.map").read_bytes() == b"retained" + assert not report["errors"] + + +@pytest.mark.parametrize("component", ["saves", "z", "cache000.map"]) +def test_cleanup_refuses_linked_cache_paths(tmp_path, component): + case = tmp_path / "case" + case.mkdir() + original = tmp_path / "original" + (original / "z").mkdir(parents=True) + source = original / "z" / "cache000.map" + source.write_bytes(b"original") + if component == "saves": + link, target = case / "saves", original + elif component == "z": + (case / "saves").mkdir() + link, target = case / "saves" / "z", original / "z" + else: + (case / "saves" / "z").mkdir(parents=True) + link, target = case / "saves" / "z" / component, source + try: + link.symlink_to(target, target_is_directory=target.is_dir()) + except OSError: + if os.name != "nt" or not target.is_dir(): + pytest.skip("symlinks unavailable") + result = smoke.subprocess.run(["cmd", "/c", "mklink", "/J", str(link), str(target)], + capture_output=True, text=True) + assert result.returncode == 0, result.stdout + result.stderr + try: + report = smoke.cleanup_map_caches(case) + assert report["removed_files"] == 0 and report["errors"] + assert source.read_bytes() == b"original" + finally: + if link.is_symlink(): + link.unlink() + elif os.name == "nt": + os.rmdir(link) + + +def test_cleanup_refuses_final_file_reparse_attribute(tmp_path, monkeypatch): + # Exercise Windows' file reparse guard even without symlink privileges. + case = tmp_path / "case" + cache = case / "saves" / "z" + cache.mkdir(parents=True) + target = cache / "cache000.map" + target.write_bytes(b"keep") + lstat = Path.lstat + def status(path): + actual = lstat(path) + if path == target: + return SimpleNamespace(st_mode=actual.st_mode, st_size=actual.st_size, + st_file_attributes=0x400) + return actual + monkeypatch.setattr(Path, "lstat", status) + report = smoke.cleanup_map_caches(case) + assert report["removed_files"] == 0 and report["errors"] + assert target.read_bytes() == b"keep" + + +@pytest.mark.parametrize("original", [None, b"original startup\r\n"]) +def test_launch_failure_restores_init_and_retains_diagnostics(tmp_path, monkeypatch, original): + argv = arguments(tmp_path, "b40") + level = tmp_path / "data" / "mcc_maps" / "b40.map" + level.parent.mkdir() + level.write_bytes(b"map") + args = smoke.parse_args(argv) + init = args.data_root / "init.txt" + if original is not None: + init.write_bytes(original) + def fail(*a, **k): + raise OSError("simulated launch failure") + monkeypatch.setattr(smoke.subprocess, "Popen", fail) + result = smoke.run_case(args, "b40", args.executable) + assert not result["passed"] + assert "simulated launch failure" in result["launcher_error"] + assert init.read_bytes() == original if original is not None else not init.exists() + assert level.read_bytes() == b"map" + assert list(args.output.rglob("result.json")) + + +@pytest.mark.parametrize("operation", ["create_transport_endpoint", "bind_endpoint", "listen_endpoint"]) +def test_console_initialization_failure_cannot_pass(operation): + fatal = f"{operation}() failed on telnet console endpoint" + assert not check_result(LOADED + "\n" + fatal, MARKER, MARKER, "b40", 0)["passed"] + + +def test_occupied_console_port_refuses_before_init_write_or_launch(tmp_path, monkeypatch): + args = smoke.parse_args(arguments(tmp_path, "12345/a10", options=("--workshop",))) + init = args.data_root / "init.txt" + init.write_bytes(b"preserved startup") + original_time = init.stat().st_mtime_ns + monkeypatch.setattr(smoke.subprocess, "Popen", lambda *a, **k: pytest.fail("started a game")) + with smoke.socket.socket(smoke.socket.AF_INET, smoke.socket.SOCK_STREAM) as listener: + listener.bind(("127.0.0.1", 0)) + listener.listen() + args.port = listener.getsockname()[1] + result = smoke.run_case(args, args.maps[0], args.executable) + assert not result["passed"] and result["launcher_error"] + assert init.read_bytes() == b"preserved startup" + assert init.stat().st_mtime_ns == original_time + + +@pytest.mark.parametrize("row,accepted", [ + ("TCP 127.0.0.1:23251 127.0.0.1:50000 ESTABLISHED 1234", True), + ("TCP 127.0.0.1:23251 127.0.0.1:50000 ESTABLISHED 9999", False), + ("TCP 127.0.0.1:23251 127.0.0.1:50001 ESTABLISHED 1234", False), + ("TCP 127.0.0.1:50000 127.0.0.1:23251 ESTABLISHED 1234", False), + ("TCP 0.0.0.0:23251 0.0.0.0:0 LISTENING 1234", False), +]) +def test_console_connection_requires_exact_child_owned_tuple(monkeypatch, row, accepted): + connection = SimpleNamespace(getpeername=lambda: ("127.0.0.1", 23251), + getsockname=lambda: ("127.0.0.1", 50000)) + monkeypatch.setattr(smoke.subprocess, "run", lambda *a, **k: SimpleNamespace(stdout=row)) + if accepted: + smoke.verify_console_owner(connection, 1234) + else: + with pytest.raises(OSError, match="does not belong"): + smoke.verify_console_owner(connection, 1234) + + +def test_console_ownership_inspection_failure_is_terminal(monkeypatch): + def fail(*a, **k): + raise smoke.subprocess.TimeoutExpired("netstat", 5) + monkeypatch.setattr(smoke.subprocess, "run", fail) + with pytest.raises(OSError, match="inspect console ownership"): + smoke.verify_console_owner(None, 1234) + + +@pytest.mark.parametrize("failure", ["connect", "owner", "send", "recv"]) +def test_console_terminal_errors_retain_evidence(tmp_path, monkeypatch, failure): + args = smoke.parse_args(arguments(tmp_path, "12345/a10", options=("--workshop",))) + monkeypatch.setattr(smoke, "check_console_port", lambda port: None) + monkeypatch.setattr(smoke.time, "sleep", lambda seconds: None) + polls, sent = [], [] + process = SimpleNamespace(pid=1234, returncode=None) + def poll(): + polls.append(None) + if len(polls) > 6: + process.returncode = 0 + return process.returncode + process.poll = poll + process.kill = lambda: setattr(process, "returncode", -1) + process.wait = lambda **k: process.returncode + def launch(*a, **k): + (Path(k["env"]["HALO_LOG_ROOT"]) / "debug.txt").write_text( + "mcc: loaded mcc_maps\\12345\\a10 (100 tags)") + return process + def denied(*a, **k): + raise PermissionError("simulated socket permission denied") + connection = SimpleNamespace(settimeout=lambda value: None, close=lambda: None, + sendall=lambda data: sent.append(data), recv=lambda size: b"") + monkeypatch.setattr(smoke.subprocess, "Popen", launch) + monkeypatch.setattr(smoke.socket, "create_connection", denied if failure == "connect" else lambda *a: connection) + monkeypatch.setattr(smoke, "verify_console_owner", denied if failure == "owner" else lambda *a: None) + if failure in ("send", "recv"): + setattr(connection, failure if failure == "recv" else "sendall", denied) + result = smoke.run_case(args, args.maps[0], args.executable) + assert "simulated socket permission denied" in result["launcher_error"] + assert len(polls) <= 3 and not result["passed"] + assert list(args.output.rglob("result.json")) + if failure in ("connect", "owner"): + assert not sent + + +def test_atomic_init_write_failure_preserves_original_and_diagnostics(tmp_path, monkeypatch): + args = smoke.parse_args(arguments(tmp_path, "12345/a10", options=("--workshop",))) + init = args.data_root / "init.txt" + init.write_bytes(b"original startup") + original_time = init.stat().st_mtime_ns + monkeypatch.setattr(smoke, "check_console_port", lambda port: None) + def fail(*a, **k): + raise PermissionError("simulated init replacement failure") + monkeypatch.setattr(smoke.os, "replace", fail) + monkeypatch.setattr(smoke.subprocess, "Popen", lambda *a, **k: pytest.fail("started a game")) + result = smoke.run_case(args, args.maps[0], args.executable) + assert "simulated init replacement failure" in result["launcher_error"] + assert init.read_bytes() == b"original startup" and init.stat().st_mtime_ns == original_time + assert not list(args.data_root.glob(".mcc-smoke-*")) + assert list(args.output.rglob("result.json")) + + +def test_partial_init_write_failure_never_truncates_original(tmp_path, monkeypatch): + init = tmp_path / "init.txt" + init.write_bytes(b"original startup") + fdopen = smoke.os.fdopen + class PartialWrite: + def __init__(self, stream): + self.stream = stream + def __enter__(self): + return self + def __exit__(self, *args): + self.stream.close() + def write(self, content): + self.stream.write(content[:3]) + raise OSError("simulated partial write") + monkeypatch.setattr(smoke.os, "fdopen", lambda *a, **k: PartialWrite(fdopen(*a, **k))) + with pytest.raises(OSError, match="partial write"): + smoke.replace_init(init, b"replacement startup") + assert init.read_bytes() == b"original startup" + assert not list(tmp_path.glob(".mcc-smoke-*")) + + +def test_init_restore_failure_keeps_logs_and_cache_cleanup(tmp_path, monkeypatch): + args = smoke.parse_args(arguments(tmp_path, "12345/a10", options=("--workshop",))) + init = args.data_root / "init.txt" + init.write_bytes(b"original startup") + monkeypatch.setattr(smoke, "check_console_port", lambda port: None) + replace = smoke.os.replace + calls = [] + def replace_once(*a, **k): + calls.append(None) + if len(calls) == 2: + raise PermissionError("simulated restore failure") + return replace(*a, **k) + monkeypatch.setattr(smoke.os, "replace", replace_once) + def fail(*a, **k): + cache = Path(k["env"]["HALO_SAVE_ROOT"]) / "z" + cache.mkdir(parents=True) + (cache / "cache000.map").write_bytes(b"cache") + raise OSError("simulated launch failure") + monkeypatch.setattr(smoke.subprocess, "Popen", fail) + result = smoke.run_case(args, args.maps[0], args.executable) + assert "simulated restore failure" in result["launcher_error"] + assert result["cleanup"]["removed_files"] == 1 + assert list(args.output.rglob("result.json")) and list(args.output.rglob("console.log")) + assert (Path(result["output"]) / "init.original.txt").read_bytes() == b"original startup" + + +@pytest.mark.parametrize("stop_failure", [None, "kill", "wait"]) +def test_cache_cleanup_requires_observed_child_exit(tmp_path, monkeypatch, stop_failure): + args = smoke.parse_args(arguments(tmp_path, "12345/a10", options=("--workshop",))) + init = args.data_root / "init.txt" + init.write_bytes(b"original startup") + monkeypatch.setattr(smoke, "check_console_port", lambda port: None) + process = SimpleNamespace(pid=1234, returncode=None) + process.poll = lambda: process.returncode + def kill(): + if stop_failure == "kill": + raise PermissionError("simulated kill failure") + if stop_failure is None: + process.returncode = -1 + def wait(**kwargs): + if stop_failure == "wait": + raise smoke.subprocess.TimeoutExpired("halo", 10) + return process.returncode + process.kill, process.wait = kill, wait + def launch(*a, **k): + output = Path(k["env"]["HALO_LOG_ROOT"]) + (output / "debug.txt").write_text("EXCEPTION halt") + cache = Path(k["env"]["HALO_SAVE_ROOT"]) / "z" + cache.mkdir(parents=True) + (cache / "cache000.map").write_bytes(b"owned cache") + (cache / "savegame.bin").write_bytes(b"preserved save") + return process + monkeypatch.setattr(smoke.subprocess, "Popen", launch) + result = smoke.run_case(args, args.maps[0], args.executable) + cache = Path(result["output"]) / "saves" / "z" + assert (cache / "cache000.map").exists() == (stop_failure is not None) + assert (cache / "savegame.bin").read_bytes() == b"preserved save" + assert init.read_bytes() == b"original startup" + assert result["process_stopped"] == (stop_failure is None) + assert result["pid"] == process.pid and not result["passed"] + assert bool(result["cleanup"]["errors"]) == (stop_failure is not None) + assert bool(result["launcher_error"]) == (stop_failure is not None) + + +@pytest.mark.parametrize("failure", [None, "stdout", "close"]) +def test_console_completion_checks_all_logs_and_survives_close_error(tmp_path, monkeypatch, failure): + args = smoke.parse_args(arguments(tmp_path, "12345/a10", options=("--workshop",))) + init = args.data_root / "init.txt" + init.write_bytes(b"original startup") + monkeypatch.setattr(smoke, "check_console_port", lambda port: None) + monkeypatch.setattr(smoke, "verify_console_owner", lambda *a: None) + monkeypatch.setattr(smoke.time, "sleep", lambda seconds: None) + process = SimpleNamespace(pid=1234, returncode=None) + process.poll = lambda: process.returncode + killed, commands = [], [] + def kill(): + killed.append(True) + process.returncode = -1 + process.kill = kill + process.wait = lambda **k: process.returncode + output = [] + def launch(*a, **k): + output.append(Path(k["env"]["HALO_LOG_ROOT"])) + (output[0] / "debug.txt").write_text("mcc: loaded mcc_maps\\12345\\a10 (100 tags)") + if failure == "stdout": + k["stdout"].write(b"EXCEPTION halt\n") + return process + def receive(size): + marker = commands[0].decode("ascii").split('"')[1] + if failure == "close": + (output[0] / "debug.txt").write_text("EXCEPTION halt") + else: + process.returncode = 0 + return ("\r\n" + marker + "\r\n").encode("ascii") + def close(): + if failure == "close": + raise OSError("simulated console close failure") + connection = SimpleNamespace(settimeout=lambda value: None, close=close, + sendall=commands.append, recv=receive) + monkeypatch.setattr(smoke.subprocess, "Popen", launch) + monkeypatch.setattr(smoke.socket, "create_connection", lambda *a: connection) + result = smoke.run_case(args, args.maps[0], args.executable) + assert result["passed"] == (failure is None) + assert result["process_stopped"] + assert init.read_bytes() == b"original startup" + assert (Path(result["output"]) / "console.log").is_file() + if failure == "stdout": + assert "exception halt" in result["failures"] + if failure == "close": + assert killed and "simulated console close failure" in result["launcher_error"] + + +@pytest.mark.skipif(os.name != "nt", reason="Windows launcher") +@pytest.mark.parametrize("completion", ["survivor", "unknown", "exception"]) +def test_main_retains_binary_until_child_completion_is_known(tmp_path, monkeypatch, completion): + argv = arguments(tmp_path, "12345/a10", "67890/b40", options=("--workshop",)) + calls = [] + def run(args, name, binary): + calls.append(name) + if completion == "exception": + raise OSError("simulated evidence write failure") + result = {"map": name, "passed": True} + if completion == "survivor": + result["process_stopped"] = False + return result + monkeypatch.setattr(smoke, "run_case", run) + monkeypatch.setattr(sys, "argv", ["mcc_native_smoke.py", *argv]) + if completion == "exception": + with pytest.raises(OSError, match="evidence write failure"): + smoke.main() + else: + assert smoke.main() == 1 + assert calls == ["12345/a10"] + assert [path.read_bytes() for path in (tmp_path / "runs").rglob("*.exe")] == [b"executable"] + assert [path.read_bytes() for path in (tmp_path / "runs").rglob("*.dll")] == [b"library"] diff --git a/tools/test_mcc_network.py b/tools/test_mcc_network.py new file mode 100644 index 0000000000..63c139fe70 --- /dev/null +++ b/tools/test_mcc_network.py @@ -0,0 +1,161 @@ +"""Exercise MCC's independent inventory packets, prediction and throw ledger.""" +import os +import re +from pathlib import Path +import shutil +import subprocess + +import pytest +from harness import enum_with, structure + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.fixture(scope="module") +def mcc_network_tool(tmp_path_factory): + clang = shutil.which("clang") + if not clang: + pytest.skip("clang is required for MCC network checks") + work = tmp_path_factory.mktemp("mcc-network") + # Compile all real new implementation bodies against deterministic + # transport/clock/object adapters; no game data or sockets are needed. + implementation = "\n".join(line for line in (ROOT / "port/linux/game/mcc_network.c").read_text().splitlines() + if not line.startswith("#include")) + damage = (ROOT / "port/linux/game/mcc_network_damage.inc").read_text() + prefix = (ROOT / "tools/harness/tests/mcc_network.c").read_text() + distributed = (ROOT / "port/linux/game/network_distributed.h").read_text() + prefix = prefix.replace("/* DISTRIBUTED_HEADER */", structure(distributed, "distributed_message_header") + + enum_with(distributed, "_distributed_message_player_prediction")) + # The packet harness must use the current production snapshot size. + header = (ROOT / "port/linux/game/mcc_campaign.h").read_text() + size = re.search(r"^#define MCC_CAMPAIGN_SNAPSHOT_BYTES (\d+)u", header, re.M).group(1) + prefix = prefix.replace("/* MCC_CAMPAIGN_SIZE */", "#define MCC_CAMPAIGN_SNAPSHOT_BYTES " + size) + source = work / "network.c" + source.write_text(prefix.replace("/* MCC_INVENTORY_IMPLEMENTATION */", implementation) + .replace("/* MCC_DAMAGE_IMPLEMENTATION */", damage)) + binary = work / ("network.exe" if os.name == "nt" else "network") + target = (["--target=i686-pc-windows-msvc", "-fuse-ld=lld", "-D_CRT_SECURE_NO_WARNINGS"] + if os.name == "nt" else ["-m32"]) + command = [clang, *target, "-std=gnu99", "-O1", "-Wall", "-Wextra", "-Werror", + "-fsanitize=undefined", "-fsanitize-trap=undefined", str(source), "-o", str(binary)] + if os.name != "nt": + command.append("-lm") + build = subprocess.run(command, capture_output=True, text=True) + assert build.returncode == 0, build.stdout + build.stderr + return binary + + +@pytest.mark.parametrize("case", ["host", "receive", "prediction", "rewind_host", "rewind_client", "damage", "legacy", "campaign"]) +def test_mcc_network(mcc_network_tool, case): + run = subprocess.run([str(mcc_network_tool), case], capture_output=True, text=True) + assert run.returncode == 0, run.stdout + run.stderr + + +def test_legacy_inventory_wire_unchanged(): + from harness import structure + source = (ROOT / "port/linux/game/network_objects.c").read_text() + inventory = structure(source, "distributed_inventory") + assert "grenade_counts[NUMBER_OF_UNIT_GRENADE_TYPES]" in inventory + assert "mcc" not in inventory + + +def test_speed_packet_transport_boundary(tmp_path): + """Compile the dispatcher's actual new case, not a second copy of its checks.""" + from harness import structure + clang = shutil.which("clang") + if not clang: + pytest.skip("clang required") + source = (ROOT / "port/linux/game/network_distributed.c").read_text() + header = (ROOT / "port/linux/game/network_distributed.h").read_text() + start = source.index("case _distributed_message_mcc_game_speed:") + case = source[start:source.index("case _distributed_message_mcc_object_names:", start)] + code = r''' +#include +typedef float real; +typedef unsigned char byte; +typedef unsigned short message_header; +''' + structure(header, "distributed_message_header") + r''' +static int unreliable,accepted; +static int network_connection_last_read_was_unreliable(void) {return unreliable;} +enum {NONE=-1,_distributed_message_mcc_game_speed=99}; +static void dispatch(int machine_index,unsigned int size,unsigned int count) { + struct distributed_message_header header={0}; + unsigned int entry_size=0;header.type=_distributed_message_mcc_game_speed;header.count=count; + switch(header.type) { +''' + case + r''' + } + if(entry_size==sizeof(real))accepted++; +} +#define CHECK(x) do {if(!(x))return __LINE__;} while(0) +int main(void) { + unsigned int size,count,valid=sizeof(struct distributed_message_header)+sizeof(real);int sender; + dispatch(NONE,valid,1);CHECK(accepted==1); + for(sender=0;sender<16;sender++)dispatch(sender,valid,1); + CHECK(accepted==1);unreliable=1;dispatch(NONE,valid,1);CHECK(accepted==1);unreliable=0; + for(size=0;size<100;size++)if(size!=valid)dispatch(NONE,size,1); + for(count=0;count<256;count++)if(count!=1)dispatch(NONE,valid,count); + CHECK(accepted==1);return 0; +} +''' + path = tmp_path / "speed_packet.c" + path.write_text(code) + binary = tmp_path / ("speed_packet.exe" if os.name == "nt" else "speed_packet") + target = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld"] if os.name == "nt" else [] + result = subprocess.run([clang, *target, "-std=gnu89", str(path), "-o", str(binary)], capture_output=True, text=True) + assert result.returncode == 0, result.stderr + assert subprocess.run([str(binary)], timeout=10).returncode == 0 + + +def test_map_sharing_keeps_mcc_packets_and_names_separate(tmp_path): + from harness import enum_with, function, structure + clang = shutil.which("clang") + if not clang: + pytest.skip("clang is required") + header = (ROOT / "port/linux/game/network_distributed.h").read_text() + share = (ROOT / "port/linux/game/map_share.c").read_text() + ce = (ROOT / "port/linux/game/custom_edition_cache.c").read_text() + code = r''' +#include +typedef int boolean; +typedef unsigned char byte; +typedef unsigned short word; +typedef word message_header; +#define FALSE 0 +#define csmemcpy memcpy +#define csstrlen strlen +#define CUSTOM_EDITION_LEVEL_NAME_PREFIX "custom_maps\\" +#ifndef _WIN32 +#define _strnicmp strncasecmp +#endif +''' + enum_with(header, "_distributed_message_player_prediction") + structure(header, "distributed_message_header") + code += function(share, "map_share_handles_message") + function(ce, "custom_edition_level_name") + code += r''' +#define CHECK(x) do { if (!(x)) return __LINE__; } while (0) +int main(void) { + struct distributed_message_header h = {0}; + int i; + CHECK(_distributed_message_chat_up == 87); + CHECK(_distributed_message_chat_down == 88); + CHECK(_distributed_message_chat_config == 89); + CHECK(_distributed_message_mcc_grenades == 97); + CHECK(_distributed_message_mcc_campaign == 98); + for (i = 0; i < NUMBER_OF_DISTRIBUTED_MESSAGES; ++i) { + h.type = i; + CHECK(!!map_share_handles_message((word *)&h, sizeof(h)) == (i >= 83 && i <= 86)); + } + h.type = _distributed_message_map_share_request; + for (i = 0; i < sizeof(h); ++i) CHECK(!map_share_handles_message((word *)&h, i)); + CHECK(custom_edition_level_name("custom_maps\\test")); + CHECK(!custom_edition_level_name("mcc_maps\\package\\m0")); + CHECK(!custom_edition_level_name("mcc_maps\\a10")); + CHECK(!custom_edition_level_name("levels\\a10\\a10")); + return 0; +} +''' + path = tmp_path / "routing.c" + path.write_text(code) + exe = tmp_path / ("routing.exe" if os.name == "nt" else "routing") + target = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld"] if os.name == "nt" else ["-m32"] + built = subprocess.run([clang, *target, str(path), "-o", str(exe)], capture_output=True, text=True) + assert built.returncode == 0, built.stderr + assert subprocess.run([str(exe)], timeout=10).returncode == 0 diff --git a/tools/test_mcc_object_names.py b/tools/test_mcc_object_names.py new file mode 100644 index 0000000000..2c288e5940 --- /dev/null +++ b/tools/test_mcc_object_names.py @@ -0,0 +1,56 @@ +"""Exercise the real MCC name table, native dispatch and chunk protocol.""" +from pathlib import Path +import os +import shutil +import subprocess +import pytest +from harness import enum_with, function, structure + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.fixture(scope="module") +def names_tool(tmp_path_factory): + compiler = shutil.which("clang") + if not compiler: + pytest.skip("clang is required") + work = tmp_path_factory.mktemp("mcc-object-names") + game = ROOT / "port/linux/game" + implementations = "\n".join( + line for name in ("mcc_object_names.c", "mcc_object_names_network.c") + for line in (game / name).read_text().splitlines() if not line.startswith("#include")) + native = (ROOT / "source/objects/objects.c").read_text() + hooks = "\n".join(function(native, name) for name in ( + "object_set_object_index_for_name_index", "object_index_from_name_index", + "object_name_list_clear", "object_name_list_new", "object_claim_scenario_name", + "object_name_list_delete", "object_name_list_lookup")) + unload = function((game / "mcc_cache.c").read_text(), "mcc_cache_tags_unload") + source = (ROOT / "tools/harness/tests/mcc_object_names.c").read_text() + distributed = (game / "network_distributed.h").read_text() + source = source.replace("/* DISTRIBUTED_HEADER */", structure(distributed, "distributed_message_header") + + enum_with(distributed, "_distributed_message_player_prediction")) + source = source.replace("/* IMPLEMENTATION */", implementations + "\n" + hooks) + source = source.replace("/* CACHE_UNLOAD */", unload) + (work / "names.c").write_text(source) + output = work / ("names.exe" if os.name == "nt" else "names") + target = (["--target=i686-pc-windows-msvc", "-fuse-ld=lld"] if os.name == "nt" else ["-m32"]) + result = subprocess.run([compiler, *target, "-std=gnu89", "-Wall", "-Wextra", "-Werror", + "-Wno-unused-variable", "-fsanitize=undefined", "-fsanitize-trap=undefined", + "-I" + str(game), str(work / "names.c"), "-o", str(output)], capture_output=True, text=True) + assert result.returncode == 0, result.stdout + result.stderr + return output + + +@pytest.mark.parametrize("case", ["legacy", "boundary", "aliases", "maximum", "network", "invalid", "bsp", + "restart", "unload", "failed_unload"]) +def test_names(names_tool, case): + result = subprocess.run([str(names_tool), case], capture_output=True, text=True) + assert result.returncode == 0, result.stdout + result.stderr + + +@pytest.mark.parametrize("count", [513, 640, 32767]) +@pytest.mark.parametrize("invalid", [False, True], ids=["roundtrip", "invalid"]) +def test_name_snapshots(names_tool, count, invalid): + case = ("invalid_snapshot_" if invalid else "snapshot_") + str(count) + result = subprocess.run([str(names_tool), case], capture_output=True, text=True) + assert result.returncode == 0, result.stdout + result.stderr diff --git a/tools/test_mcc_parameters.py b/tools/test_mcc_parameters.py new file mode 100644 index 0000000000..860fe000bb --- /dev/null +++ b/tools/test_mcc_parameters.py @@ -0,0 +1,21 @@ +"""MCC generated parameter metadata and the real MCC interpreter adapter.""" +import subprocess + +import pytest +from test_mcc_scripts import native_mcc_harness + + +@pytest.fixture(scope="module") +def parameters_tool(native_mcc_harness): + return native_mcc_harness("mcc_script_parameters") + + +@pytest.mark.parametrize("case", ["executing_thread", "kill_self", "kill_other", "kill_self_lists", "kill_other_lists", "kill_console", "kill_stale", "kill_slot", "kill_none", "kill_outside", "kill_deleted", "kill_legacy", "metadata", "count", "type", "pointer", "slot", "orphan", "flags", + "call_arity", "call_type", "global_scope", "legacy", "return", "snapshot", + "nested_scope", "recursive_arguments", "lists", "set", "overflow", "ai_cast", "widen", + "global_capacity", "global_overflow", "maximum", "disabled", "predicate", "script_kind", + "high_node", "negative_count", "sleep_self", "sleep_named", "sleep_missing", "sleep_finished", "sleep_lists", "sleep_disabled", "finished", + "tail_true", "tail_false", "tail_cast", "tail_absent", "tail_complete", "tail_legacy"]) +def test_mcc_parameter_metadata_and_runtime(parameters_tool, case): + result = subprocess.run([str(parameters_tool), case], capture_output=True, text=True, timeout=10) + assert result.returncode == 0, result.stdout + result.stderr diff --git a/tools/test_mcc_particles.py b/tools/test_mcc_particles.py new file mode 100644 index 0000000000..168c0df3a3 --- /dev/null +++ b/tools/test_mcc_particles.py @@ -0,0 +1,29 @@ +"""MCC particle-system marker ownership and per-view visibility, using real code.""" +from pathlib import Path +import subprocess + +import pytest +from harness import function, enum_with +from test_mcc_identity import compile_tool + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.fixture(scope="module") +def particles(tmp_path_factory): + work = tmp_path_factory.mktemp("mcc-particles") + adapter = (ROOT / "port/linux/game/mcc_particles.c").read_text() + definitions = (ROOT / "source/effects/particle_system_definitions.h").read_text() + fixture = (ROOT / "tools/harness/tests/mcc_particles.c").read_text() + implementation = enum_with(definitions, "_particle_system_type_nodraw_first_person_bit") + implementation += "\n" + "\n".join(function(adapter, name) for name in ( + "mcc_particle_system_local_player", "mcc_particle_system_markers", "mcc_particle_system_visible")) + source = work / "particles.c" + source.write_text(fixture.replace("/* IMPLEMENTATION */", implementation)) + return compile_tool(work, [source]) + + +@pytest.mark.parametrize("case", ["markers", "views", "invalid", "lifecycle", "legacy"]) +def test_particle_system_views(particles, case): + result = subprocess.run([str(particles), case], capture_output=True, text=True) + assert result.returncode == 0, result.stdout + result.stderr diff --git a/tools/test_mcc_pause.py b/tools/test_mcc_pause.py new file mode 100644 index 0000000000..6d5d2d3f49 --- /dev/null +++ b/tools/test_mcc_pause.py @@ -0,0 +1,482 @@ +"""Read generated MCC pause tags through the actual native widget ABI. + +The builder runs intact with synthetic font/art handles. These tests require +no proprietary map assets and never enter the Xbox or Custom Edition loaders. +""" +from pathlib import Path +import shutil +import subprocess +import sys + +import pytest + +from harness import function, structure + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.fixture(scope="module") +def pause_tool(tmp_path_factory): + clang = shutil.which("clang") + if not clang: + pytest.skip("clang is needed for the MCC pause builder tests") + work = tmp_path_factory.mktemp("mcc-pause") + native = (ROOT / "source/interface/ui_widget.c").read_text() + wrap_hook_start = native.index("\n\t{\n\t\tif (mcc_pause_text_wrap_needed") + # Extract only the MCC-owned block, not adjacent optional frontend hooks. + wrap_hook_end = native.index("\n\t}\n", wrap_hook_start) + len("\n\t}") + wrap_hook = native[wrap_hook_start:wrap_hook_end] + tag_groups = (ROOT / "source/tag_files/tag_groups.h").read_text() + native_types = "\n".join(structure(tag_groups, name) for name in [ + "tag_block", "tag_reference", "tag_data"]) + native_types += "\n" + "\n".join(structure(native, name) for name in [ + "ui_widget_event_handler_reference", "ui_widget_child_reference", + "ui_widget_conditional_reference", "ui_widget_game_data_input_reference", + "ui_widget_search_and_replace_reference", "ui_widget_definition"]) + (work / "tag_files").mkdir() + (work / "text").mkdir() + (work / "tag_files/tag_groups.h").write_text("/* Native tag structures already included by harness. */\n") + text_groups = (ROOT / "source/text/text_group.h").read_text() + (work / "text/text_group.h").write_text("\n".join(structure(text_groups, name) for name in [ + "string_list", "string_list_entry"])) + (work / "cseries.h").write_text(r''' +#ifndef MCC_PAUSE_TEST_CSERIES +#define MCC_PAUSE_TEST_CSERIES +#include +#include +#include +#include +#include +#include +#include +typedef unsigned char boolean,byte; +typedef unsigned short word; +typedef struct {short y0,x0,y1,x1;} rectangle2d; +typedef struct {float alpha,red,green,blue;} real_argb_color; +#define TRUE 1 +#define FALSE 0 +#define NONE (-1) +#define NUMBEROF(a) (sizeof(a)/sizeof(*(a))) +#define FLAG(bit) (1u<<(bit)) +#define MIN(a,b) ((a)<(b)?(a):(b)) +#define MAX(a,b) ((a)>(b)?(a):(b)) +#define csstrnzcpy(d,s,n) do {strncpy(d,s,n);(d)[(n)-1]=0;} while(0) +#endif +''') + source = r''' +#include "cseries.h" +#include "mcc_pause.h" +#include "mcc_ui.h" +''' + native_types + r''' +typedef char widget_size_must_match_native[sizeof(struct ui_widget_definition)==0x3ec?1:-1]; +typedef char child_size_must_match_native[sizeof(struct ui_widget_child_reference)==0x50?1:-1]; +typedef char event_size_must_match_native[sizeof(struct ui_widget_event_handler_reference)==0x48?1:-1]; +#define CHECK(c) do {if(!(c)){fprintf(stderr,"line %d: %s\n",__LINE__,#c);return 1;}}while(0) +static unsigned allocation_calls,live_allocations,fail_allocation; +static void *test_malloc(size_t bytes) { + void *p; + if(++allocation_calls==fail_allocation)return NULL; + p=malloc(bytes);if(p)live_allocations++;return p; +} +static void *test_calloc(size_t count,size_t bytes) { + void *p=test_malloc(count*bytes);if(p)memset(p,0,count*bytes);return p; +} +static void test_free(void *p) {if(p){assert(live_allocations);live_allocations--;free(p);}} +#define malloc test_malloc +#define calloc test_calloc +#define free test_free +#include "mcc_pause.c" +#undef malloc +#undef calloc +#undef free +static struct {short width,height;enum mcc_pause_art_kind kind;long handle;} art_records[64]; +static unsigned art_count,art_calls,fail_art; +static long art(short width,short height,enum mcc_pause_art_kind kind) { + unsigned i; + if(++art_calls==fail_art)return NONE; + assert(width>0&&height>0&&width<=640&&height<=480); + assert(kind>=MCC_PAUSE_ART_PANEL&&kind<=MCC_PAUSE_ART_OBJECTIVES_RIGHT); + for(i=0;ix0=(short)(bounds->x0+width); +} +''' + function(native, "ui_widget_port_text_wrap") + r''' +static void apply_wrap_hook(long handle,wchar_t *value,rectangle2d bounds,rectangle2d *clipped) { + struct {long definition_tag_index;} instance={handle},*widget=&instance; + wchar_t **text=&value; + rectangle2d clip=*clipped; +''' + wrap_hook + r''' + *clipped=clip; +} +static int wide_equal(wchar_t const *a,wchar_t const *b) { + while(*a&&*a==*b){a++;b++;}return *a==*b; +} +static struct mcc_pause_tag const *find(long handle) { + long i; + for(i=0;ihandle==handle)return mcc_pause_tag_at(i); + return NULL; +} +static struct ui_widget_definition const *widget(long handle) { + struct mcc_pause_tag const *tag=find(handle); + assert(tag&&tag->group=='DeLa'&&tag->data);return tag->data; +} +static unsigned actions(long handle,unsigned depth) { + struct ui_widget_definition const *w=widget(handle); + struct ui_widget_event_handler_reference const *events=w->event_handlers.address; + struct ui_widget_child_reference const *children=w->child_widgets.address; + unsigned result=0;long i; + assert(depth<10); + for(i=0;ievent_handlers.count;i++) { + if((events[i].flags&128)&&events[i].function>=MCC_PAUSE_ACTION_RESUME&& + events[i].function<=MCC_PAUSE_ACTION_FRIENDLY_FIRE) + result|=1u<<(events[i].function-MCC_PAUSE_ACTION_RESUME); + if(events[i].flags&8)result|=actions(events[i].widget_tag.index,depth+1); + } + for(i=0;ichild_widgets.count;i++)result|=actions(children[i].widget_tag.index,depth+1); + return result; +} +static unsigned objectives; +static int walk_bounds(long handle,int x,int y,int width,int height,int layout,unsigned depth) { + struct ui_widget_definition const *w=widget(handle); + struct ui_widget_child_reference const *children=w->child_widgets.address; + struct ui_widget_game_data_input_reference const *inputs=w->game_data_inputs.address; + long i; + CHECK(depth<10); + CHECK(w->bounds.x0+x>=0&&w->bounds.y0+y>=0&&w->bounds.x1+x<=width&&w->bounds.y1+y<=height); + CHECK(w->bounds.x1>w->bounds.x0&&w->bounds.y1>w->bounds.y0); + if(w->type==1)CHECK(w->text_font.index==assets.font[layout]||w->text_font.index==assets.small_font[layout]); + for(i=0;igame_data_inputs.count;i++){CHECK(inputs[i].function==18);objectives++;} + if(w->type==3) { + CHECK((w->flags&0x61)==0x21||(w->flags&0x61)==0x41); + for(i=1;ichild_widgets.count;i++) { + struct ui_widget_definition const *previous=widget(children[i-1].widget_tag.index); + if(w->flags&0x20)CHECK(children[i].vertical_offset>=children[i-1].vertical_offset+previous->bounds.y1); + else CHECK(children[i].horizontal_offset>=children[i-1].horizontal_offset+previous->bounds.x1); + } + } + for(i=0;ichild_widgets.count;i++)CHECK(!walk_bounds(children[i].widget_tag.index, + x+children[i].horizontal_offset,y+children[i].vertical_offset,width,height,layout,depth+1)); + return 0; +} +static int context_check(boolean do_bounds) { + int campaign,network,host,teams,count,first; + for(campaign=0;campaign<2;campaign++)for(network=0;network<2;network++) + for(host=0;host<2;host++)for(teams=0;teams<2;teams++)for(count=1;count<=4;count++)for(first=0;first<2;first++) { + int layout=count==1?0:count==2||(count==3&&first)?1:2; + int width=layout==2?320:640,height=layout==0?480:240; + long root=mcc_pause_select(campaign,network,host,teams,(short)count,first); + struct ui_widget_definition const *w; + unsigned bits; + CHECK(root!=NONE&&mcc_pause_owns(root));w=widget(root); + CHECK(w->bounds.x0==0&&w->bounds.y0==0&&w->bounds.x1==width&&w->bounds.y1==height); + if(do_bounds) { + struct ui_widget_child_reference const *children=w->child_widgets.address; + long child,list=NONE,footer=NONE; + objectives=0;CHECK(!walk_bounds(root,0,0,width,height,layout,0)); + CHECK(objectives==(unsigned)campaign); + for(child=0;childchild_widgets.count;child++) { + struct ui_widget_definition const *definition=widget(children[child].widget_tag.index); + if(definition->type==3)list=child; + if(!strcmp(definition->name,"button_key"))footer=child; + } + CHECK(list!=NONE&&footer!=NONE); + if(!campaign) { + struct ui_widget_definition const *panel=widget(children[0].widget_tag.index); + unsigned record; + for(record=0;recordbackground_bitmap.index)break; + if(panel->child_widgets.count) { + CHECK(panel->child_widgets.count==3); + } else { CHECK(record=children[0].vertical_offset+panel->bounds.y1-28); + } + if(campaign&&layout==0&&assets.settings) { + struct ui_widget_definition const *buttons=widget(children[list].widget_tag.index); + struct ui_widget_child_reference const *rows=buttons->child_widgets.address; + CHECK(widget(children[0].widget_tag.index)->bounds.y1==(network?225:195)); + CHECK(children[footer].vertical_offset==(network?362:332)); + CHECK(rows[1].vertical_offset-rows[0].vertical_offset==30); + } + CHECK(children[footer].vertical_offset>=children[list].vertical_offset+ + widget(children[list].widget_tag.index)->bounds.y1); + CHECK(widget(children[footer].widget_tag.index)->child_widgets.count==4); + CHECK(widget(children[footer].widget_tag.index)->event_handlers.count==0); + if(campaign&&layout!=2) { + /* The stock campaign panels have a five-pixel gap. */ + CHECK(widget(children[0].widget_tag.index)->bounds.x1==218); + CHECK(children[0].horizontal_offset+218+5==children[1].horizontal_offset); + } + } + bits=actions(root,0); + CHECK(bits&1u); /* Resume is always reachable. */ + CHECK(bits&(1u<<(MCC_PAUSE_ACTION_QUIT-MCC_PAUSE_ACTION_RESUME))); + if(network&&!host)CHECK(!(bits&((1u<<3)|(1u<<5)))); /* Co-op shows Xbox actions; callbacks deny clients. */ + if(campaign)CHECK(!(bits&((1u<<5)|(1u<<6)|(1u<<7)))); + /* The native Settings screen requires a full viewport, including + * when the first player owns the half-screen in a three-player game. */ + CHECK(!!(bits&(1u<<8))==(assets.settings&&count==1)); + if(!campaign)CHECK(!(bits&((1u<<1)|(1u<<3)))); + if(!network||campaign||!teams)CHECK(!(bits&((1u<<6)|(1u<<7)))); + CHECK(!(bits&((1u<<6)|(1u<<7)))); /* No extra MCC team menu. */ + if(!campaign&&network&&host)CHECK(bits&(1u<<5)); + } + return 0; +} +int main(int argc,char **argv) { + struct mcc_pause_assets original=assets; + long i,j;unsigned calls,art_total; + CHECK(argc==2); + CHECK(mcc_pause_tag_count()==0&&mcc_pause_tag_at(0)==NULL&&!mcc_pause_owns(0)); + CHECK(mcc_pause_select(TRUE,FALSE,FALSE,FALSE,1,TRUE)==NONE); + CHECK(mcc_pause_build(1024,0x4321,&assets)); + CHECK(!memcmp(&assets,&original,sizeof(assets))); + calls=allocation_calls;art_total=art_calls; + if(!strcmp(argv[1],"identity")) { + CHECK(mcc_pause_tag_count()>24&&mcc_pause_tag_count()<4096); + CHECK(mcc_pause_tag_at(-1)==NULL&&mcc_pause_tag_at(mcc_pause_tag_count())==NULL); + for(i=0;idata&&t->name&&strlen(t->name)>0); + CHECK(!strncmp(t->name,"mcc_pause\\",10)); + CHECK((t->handle&0xffff)==1024+i); + CHECK(t->group=='DeLa'||t->group=='ustr'); + CHECK(mcc_pause_owns(t->handle)==(t->group=='DeLa')); + CHECK(!mcc_pause_owns(t->handle^0x01000000)); + for(j=0;jname,mcc_pause_tag_at(j)->name)!=0&&t->handle!=mcc_pause_tag_at(j)->handle); + } + } else if(!strcmp(argv[1],"parity")) { + long root=mcc_pause_select(TRUE,TRUE,TRUE,FALSE,1,TRUE); + struct ui_widget_definition const *w=widget(root); + struct ui_widget_child_reference const *children=w->child_widgets.address,*rows; + struct ui_widget_definition const *list=widget(children[2].widget_tag.index); + CHECK(list->child_widgets.count==6);rows=list->child_widgets.address; + CHECK(widget(rows[2].widget_tag.index)->string_list_index==LABEL_FRIENDLY_ON); + mcc_pause_friendly_fire(FALSE); + CHECK(widget(rows[2].widget_tag.index)->string_list_index==LABEL_FRIENDLY_OFF); + mcc_pause_friendly_fire(TRUE); + CHECK(widget(rows[2].widget_tag.index)->string_list_index==LABEL_FRIENDLY_ON); + CHECK(widget(rows[5].widget_tag.index)->string_list_index==LABEL_SAVE_QUIT); + root=mcc_pause_select(FALSE,TRUE,TRUE,TRUE,1,TRUE);w=widget(root);children=w->child_widgets.address; + list=widget(children[1].widget_tag.index);rows=list->child_widgets.address; + CHECK(list->child_widgets.count==4); + CHECK(widget(rows[0].widget_tag.index)->string_list_index==LABEL_RESUME); + CHECK(widget(rows[1].widget_tag.index)->string_list_index==LABEL_SETTINGS); + CHECK(widget(rows[2].widget_tag.index)->string_list_index==LABEL_END); + CHECK(widget(rows[3].widget_tag.index)->string_list_index==LABEL_LEAVE); + CHECK(((struct ui_widget_event_handler_reference *)widget(rows[2].widget_tag.index)->event_handlers.address)[0].function==MCC_PAUSE_ACTION_END_GAME); + /* Observed Xbox multiplayer panel, list and footer coordinates. */ + CHECK(children[0].horizontal_offset==206&&children[0].vertical_offset==129); + CHECK(children[1].horizontal_offset==218&&children[1].vertical_offset==172); + CHECK(children[2].horizontal_offset==235&&children[2].vertical_offset==333); + root=mcc_pause_select(FALSE,TRUE,FALSE,TRUE,1,TRUE);w=widget(root);children=w->child_widgets.address; + CHECK(children[0].horizontal_offset==206&&children[0].vertical_offset==147); + CHECK(children[1].horizontal_offset==218&&children[1].vertical_offset==190); + CHECK(children[2].horizontal_offset==235&&children[2].vertical_offset==316); + } else if(!strcmp(argv[1],"contexts")) { + CHECK(!context_check(FALSE)); + } else if(!strcmp(argv[1],"layout")) { + CHECK(!context_check(TRUE)); + } else if(!strcmp(argv[1],"actions")) { + for(i=0;igroup!='DeLa')continue; + w=t->data;e=w->event_handlers.address; + for(j=0;jevent_handlers.count;j++) { + CHECK(!(e[j].flags&1024)&&!e[j].script[0]); + if(e[j].flags&128)CHECK(e[j].function>=MCC_PAUSE_ACTION_RESUME&&e[j].function<=MCC_PAUSE_ACTION_FRIENDLY_FIRE); + if(e[j].flags&8)CHECK(find(e[j].widget_tag.index)&&mcc_pause_owns(e[j].widget_tag.index)); + if(e[j].event_type==0) { + long k; + for(k=0;kevent_handlers.count;k++)if(e[k].event_type==28)break; + CHECK(kevent_handlers.count&&e[k].flags==e[j].flags&&e[k].function==e[j].function&& + e[k].widget_tag.index==e[j].widget_tag.index); + } + } + } + } else if(!strcmp(argv[1],"controller-close")) { + unsigned resume_accept=0,resume_back=0,red=0,blue=0; + for(i=0;igroup!='DeLa')continue; + w=t->data;e=w->event_handlers.address; + for(j=0;jevent_handlers.count;j++) { + if(e[j].function!=MCC_PAUSE_ACTION_RESUME&& + e[j].function!=MCC_PAUSE_ACTION_RED_TEAM&& + e[j].function!=MCC_PAUSE_ACTION_BLUE_TEAM)continue; + /* These callbacks own controller-local tree/history cleanup. + * Generic close-all would dismiss another player's settings. */ + CHECK(e[j].flags==128&&e[j].widget_tag.index==NONE); + if(e[j].function==MCC_PAUSE_ACTION_RESUME) { + if(e[j].event_type==0||e[j].event_type==28)resume_accept++; + else {CHECK(e[j].event_type==1||e[j].event_type==13);resume_back++;} + } else { + CHECK(e[j].event_type==0||e[j].event_type==28); + if(e[j].function==MCC_PAUSE_ACTION_RED_TEAM)red++;else blue++; + } + } + } + CHECK(resume_accept&&resume_back&&!red&&!blue); + } else if(!strcmp(argv[1],"dialogs")) { + unsigned dialogs=0; + for(i=0;igroup!='DeLa')continue; + w=t->data; + if(strcmp(w->name,"confirmation"))continue; + dialogs++;children=w->child_widgets.address; + for(j=0;jchild_widgets.count;j++)if(widget(children[j].widget_tag.index)->type==3)list=children[j].widget_tag.index; + CHECK(list==NONE); /* Xbox prompts are root-level A/B actions, not a selectable list. */ + e=w->event_handlers.address; + if(w->milliseconds_to_auto_close) { + CHECK(w->milliseconds_to_auto_close==3000&&w->event_handlers.count==1); + CHECK(e[0].event_type==25&&e[0].function==MCC_PAUSE_ACTION_QUIT); + } else { + CHECK(w->event_handlers.count==5); + CHECK(e[0].event_type==1&&e[0].flags==512); + CHECK(e[2].event_type==0&&e[3].event_type==12&&e[4].event_type==28); + CHECK(e[2].function==e[3].function&&e[3].function==e[4].function); + } + } + CHECK(dialogs>=15); + } else if(!strcmp(argv[1],"paragraphs")) { + unsigned objective_count=0,confirm_count=0; + for(i=0;idata; + boolean paragraph=t->group=='DeLa'&&(!strcmp(w->name,"objective")||!strcmp(w->name,"confirmation_text")); + CHECK(mcc_pause_text_wrap_needed(t->handle)==paragraph); + CHECK(!mcc_pause_text_wrap_needed(t->handle^0x01000000)); + if(!paragraph)continue; + if(!strcmp(w->name,"objective"))objective_count++;else confirm_count++; + } + CHECK(objective_count&&confirm_count); + CHECK(!mcc_pause_text_wrap_needed(NONE)); + } else if(!strncmp(argv[1],"wrap-",5)) { + long paragraph=NONE,plain=mcc_pause_select(TRUE,FALSE,FALSE,FALSE,1,TRUE); + rectangle2d bounds={20,100,90,130},clip={0,0,480,640},before=clip; + struct {wchar_t text[128];unsigned canary;} value={L"aa aa aa",0x1234abcd}; + for(i=0;ihandle)) { + paragraph=mcc_pause_tag_at(i)->handle;break; + } + CHECK(paragraph!=NONE); + if(!strcmp(argv[1],"wrap-boundaries")) { + wchar_t exact[]=L"WW WW",over[]=L"WW WW",unbroken[]=L"WWWWWW"; + CHECK(ui_widget_port_text_wrap(exact,&bounds,39)&&wide_equal(exact,L"WW WW")); + CHECK(ui_widget_port_text_wrap(over,&bounds,38)&&wide_equal(over,L"WW\rWW")); + CHECK(!ui_widget_port_text_wrap(unbroken,&bounds,30)&&wide_equal(unbroken,L"WWWWWW")); + apply_wrap_hook(paragraph,value.text,bounds,&clip); + CHECK(wide_equal(value.text,L"aa aa\raa")&&value.canary==0x1234abcd); + CHECK(!memcmp(&clip,&bounds,sizeof(clip))); + } else if(!strcmp(argv[1],"wrap-lines")) { + wchar_t lines[]=L"aa aa\r\nbb bb cc",empty[]=L""; + apply_wrap_hook(paragraph,lines,bounds,&clip); + CHECK(wide_equal(lines,L"aa aa\r\nbb bb\rcc")); + apply_wrap_hook(paragraph,lines,bounds,&clip); + CHECK(wide_equal(lines,L"aa aa\r\nbb bb\rcc")); + CHECK(ui_widget_port_text_wrap(empty,&bounds,30)&&!empty[0]); + } else { + CHECK(!strcmp(argv[1],"wrap-isolation")); + apply_wrap_hook(plain,value.text,bounds,&clip); + CHECK(wide_equal(value.text,L"aa aa aa")&&!memcmp(&clip,&before,sizeof(clip))); + apply_wrap_hook(paragraph^0x01000000,value.text,bounds,&clip); + CHECK(wide_equal(value.text,L"aa aa aa")&&!memcmp(&clip,&before,sizeof(clip))); + clip=(rectangle2d){25,105,80,125};before=clip; + apply_wrap_hook(paragraph,value.text,bounds,&clip); + CHECK(wide_equal(value.text,L"aa aa\raa")&&!memcmp(&clip,&before,sizeof(clip))); + } + } else if(!strcmp(argv[1],"strings")) { + unsigned lists=0; + for(i=0;idata; + struct tag_data const *entries=block->address; + if(t->group!='ustr')continue; + lists++;CHECK(block->count==LABEL_COUNT); + for(j=0;jcount;j++) { + unsigned short const *text=entries[j].address;long k; + CHECK(text&&entries[j].size>=2&&entries[j].size<=256&&!(entries[j].size&1)); + CHECK(!text[entries[j].size/2-1]); + for(k=0;k=32&&text[k]<127)||text[k]==13||text[k]==10); + } + } + CHECK(lists==1); + } else if(!strcmp(argv[1],"failure")) { + mcc_pause_dispose();CHECK(!live_allocations); + for(fail_allocation=1;fail_allocation<=calls;fail_allocation++) { + allocation_calls=0;CHECK(!mcc_pause_build(1024,0x4321,&assets)); + CHECK(!live_allocations&&!mcc_pause_tag_count()); + CHECK(mcc_pause_select(TRUE,FALSE,FALSE,FALSE,1,TRUE)==NONE); + } + fail_allocation=0; + CHECK(mcc_pause_build(1024,0x4321,&assets)); + } else if(!strcmp(argv[1],"art-failure")) { + mcc_pause_dispose();CHECK(!live_allocations); + for(fail_art=1;fail_art<=art_total;fail_art++) { + art_calls=0;CHECK(!mcc_pause_build(1024,0x4321,&assets)); + CHECK(!live_allocations&&!mcc_pause_tag_count()); + } + fail_art=0;CHECK(mcc_pause_build(1024,0x4321,&assets)); + } else if(!strcmp(argv[1],"invalid")) { + CHECK(mcc_pause_select(TRUE,FALSE,FALSE,FALSE,0,TRUE)==NONE); + CHECK(mcc_pause_select(TRUE,FALSE,FALSE,FALSE,5,TRUE)==NONE); + CHECK(!mcc_pause_build(-1,1,&assets));CHECK(!live_allocations&&!mcc_pause_tag_count()); + CHECK(!mcc_pause_build(65535,1,&assets));CHECK(!live_allocations&&!mcc_pause_tag_count()); + CHECK(!mcc_pause_build(0,1,NULL));CHECK(!live_allocations&&!mcc_pause_tag_count()); + assets.art=NULL;CHECK(!mcc_pause_build(1024,1,&assets));assets=original; + for(i=0;i<3;i++) { + assets.font[i]=NONE;CHECK(!mcc_pause_build(1024,1,&assets));assets=original; + assets.small_font[i]=NONE;CHECK(!mcc_pause_build(1024,1,&assets));assets=original; + } + CHECK(!live_allocations&&!mcc_pause_tag_count()); + } else if(!strcmp(argv[1],"lifetime")) { + long old=mcc_pause_select(TRUE,FALSE,FALSE,FALSE,1,TRUE); + mcc_pause_dispose();mcc_pause_dispose();CHECK(!live_allocations&&!mcc_pause_owns(old)); + assets.settings=FALSE;CHECK(mcc_pause_build(2048,0x4322,&assets));CHECK(!mcc_pause_owns(old)); + for(i=0;i<2;i++)for(j=0;j<2;j++) { + long root=mcc_pause_select(FALSE,TRUE,(boolean)i,(boolean)j,1,TRUE); + CHECK(!(actions(root,0)&(1u<<8))); + } + } else return 99; + mcc_pause_dispose();CHECK(!live_allocations&&!mcc_pause_tag_count());return 0; +} +''' + path = work / "pause_check.c" + path.write_text(source) + binary = work / ("pause_check.exe" if sys.platform == "win32" else "pause_check") + command = [clang, "-std=gnu99", "-O2", "-Wall", "-Wextra", "-Werror", + "-Wno-unused-function", "-I", str(work), "-I", str(ROOT / "port/linux/game"), + str(path), "-o", str(binary)] + if sys.platform == "win32": + command[1:1] = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld", "-D_CRT_SECURE_NO_WARNINGS"] + else: + command[1:1] = ["-m32", "-fshort-wchar"] + result = subprocess.run(command, capture_output=True, text=True) + assert result.returncode == 0, result.stderr + return binary + + +@pytest.mark.parametrize("case", ["identity", "parity", "contexts", "layout", "actions", "controller-close", "dialogs", "paragraphs", "strings", + "wrap-boundaries", "wrap-lines", "wrap-isolation", "failure", "art-failure", "invalid", "lifetime"]) +def test_mcc_pause_builder(pause_tool, case): + result = subprocess.run([str(pause_tool), case], capture_output=True, text=True, timeout=30) + assert result.returncode == 0, f"{case}: exit {result.returncode}\n{result.stdout}{result.stderr}" diff --git a/tools/test_mcc_pause_runtime.py b/tools/test_mcc_pause_runtime.py new file mode 100644 index 0000000000..47573b35bf --- /dev/null +++ b/tools/test_mcc_pause_runtime.py @@ -0,0 +1,387 @@ +"""Compile the real pause builder and resource importer with a fake renderer. + +Guarded allocations cover generated pixels and the copied live tag table. +Failure injection checks every allocation and texture-creation boundary, so +partial imports cannot publish dangling tags or leak native texture headers. +""" +from pathlib import Path +import re +import shutil +import subprocess +import sys + +import pytest + +from harness import function, structure + +ROOT = Path(__file__).resolve().parents[1] + + +def _compile(source, binary): + clang = shutil.which("clang") + if not clang: + pytest.skip("clang is needed for the MCC pause runtime tests") + command = [clang, "-std=gnu99", "-O2", "-Wall", "-Wextra", "-Werror", "-Wno-unused-function", + "-I", str(ROOT / "port/linux/game"), str(source), "-o", str(binary)] + if sys.platform == "win32": + command[1:1] = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld", "-D_CRT_SECURE_NO_WARNINGS"] + else: + command[1:1] = ["-m32"] + result = subprocess.run(command, capture_output=True, text=True) + assert result.returncode == 0, result.stderr + + +@pytest.fixture(scope="module") +def runtime_tool(tmp_path_factory): + work = tmp_path_factory.mktemp("mcc-pause-runtime") + tags = (ROOT / "source/tag_files/tag_groups.h").read_text() + bitmaps = (ROOT / "source/bitmaps/bitmap_group.h").read_text() + strings = (ROOT / "source/text/text_group.h").read_text() + types = "\n".join(structure(tags, name) for name in ["tag_block", "tag_reference", "tag_data"]) + types += "\n" + "\n".join(structure(bitmaps, name) for name in [ + "bitmap_data", "bitmap_group_sequence", "bitmap_group"]) + types += "\n" + "\n".join(structure(strings, name) for name in ["string_list", "string_list_entry"]) + # Keep both implementations intact; replace only their project headers + # with the native structures and narrow host services declared below. + implementations = "\n".join(re.sub(r'^#include "[^"\n]+"\s*$', "", (ROOT / name).read_text(), flags=re.M) + for name in ["port/linux/game/mcc_pause.c", "port/linux/game/mcc_pause_runtime.c"]) + unbind = function((ROOT / "port/linux/src/d3d8_gl.c").read_text(), "xgpu_mcc_texture_unbind") + source = r''' +#include +#include +#include +#include +#include +#include +typedef unsigned char boolean; +typedef unsigned short word; +typedef unsigned long DWORD; +typedef float real; +union point2d {struct {short x,y;} point;long value;}; +#define TRUE 1 +#define FALSE 0 +#define NONE (-1) +#define NUMBEROF(a) (sizeof(a)/sizeof(*(a))) +#define MAX(a,b) ((a)>(b)?(a):(b)) +#include "mcc_pause.h" +#include "mcc_ui.h" +#include "mcc_pause_runtime.h" +''' + types + r''' +enum {D3DTSS_MAXSTAGES=4}; +static struct {void *textures[D3DTSS_MAXSTAGES];} device; +''' + unbind + r''' +#define CHECK(c) do {if(!(c)){fprintf(stderr,"line %d: %s\n",__LINE__,#c);return 1;}}while(0) +struct allocation {struct allocation *next;size_t bytes;unsigned long pad[2];}; +static struct allocation *allocations; +static unsigned malloc_calls,live_allocations,fail_malloc; +static unsigned gpu_calls,gpu_live,fail_gpu; +static unsigned published,gpu_deleted,gpu_changed,restored,logs; +static boolean active=TRUE,null_renderer; +static int connection; +static int borrowed_failure; +static unsigned long const *placeholders[2]; +static long large_font=0x11110000,small_font=0x11120001,live_count; +static void *live_table,*original_table; +static struct test_scenario {short type;} scenario,*global_scenario; +static struct {struct {boolean teams;} universal_variant;} variant; +enum {_game_connection_local,_game_connection_network_client,_game_connection_network_server}; +static void *test_malloc(size_t bytes) { + struct allocation *a;unsigned char *end; + if(++malloc_calls==fail_malloc)return NULL; + a=malloc(sizeof(*a)+bytes+16);if(!a)return NULL; + a->next=allocations;a->bytes=bytes;a->pad[0]=a->pad[1]=0xcafebabe;allocations=a; + end=(unsigned char *)(a+1)+bytes;memset(end,0xD7,16);live_allocations++;return a+1; +} +static void check_guards(void) { + struct allocation *a;unsigned i; + for(a=allocations;a;a=a->next) { + assert(a->pad[0]==0xcafebabe&&a->pad[1]==0xcafebabe); + for(i=0;i<16;i++)assert(((unsigned char *)(a+1))[a->bytes+i]==0xD7); + } +} +static void test_free(void *p) { + struct allocation **slot=&allocations,*a; + assert(p);check_guards(); + while(*slot&&(*slot)+1!=p)slot=&(*slot)->next; + assert(*slot);a=*slot;*slot=a->next;memset(p,0xEA,a->bytes);free(a);live_allocations--; +} +static boolean mcc_cache_tags_loaded(void){return active;} +void mcc_ui_settings_close(short controller){assert(controller==NONE);} +static short game_connection(void){return (short)connection;} +static void *global_network_game_server_get(void){return connection==_game_connection_network_server?&variant:NULL;} +#define game_engine_get_variant() (&variant) +static long tag_loaded(long group,char const *name) { + if(group=='bitm') {assert(!strncmp(name,"pc\\",3));return borrowed_failure==1?NONE:77;} + assert(group=='font'); + if(!strcmp(name,"ui\\large_ui"))return large_font; + if(!strcmp(name,"ui\\small_ui"))return small_font; + assert(0);return NONE; +} +static struct bitmap_data borrowed_frames[4]; +static struct bitmap_group borrowed_group; +static struct bitmap_data borrowed_copy[4]; +static struct bitmap_group borrowed_group_copy; +static unsigned long borrowed_pixels[4]; +static void *tag_get(long group,long tag) { + assert(group=='bitm'&&tag==77); + return &borrowed_group; +} +boolean pc_menu_tag(long tag){return tag==77&&borrowed_failure!=2;} +long hud_hires_asset_count(void){return 2;} +char const *hud_hires_asset_tag(long a){return a==0?"ui\\shell\\bitmaps\\a_butn_sm":"ui\\shell\\bitmaps\\b_butn_sm";} +void hud_hires_register_placeholder(long a,unsigned long const *p){ + assert(a>=0&&a<2);if(p)assert(!placeholders[a]);placeholders[a]=p; +} +int config_boolean(char const *name){assert(!strcmp(name,"network.coop_own_friendly_fire"));return TRUE;} +char const *config_string(char const *name){assert(!strcmp(name,"display.menus"));return "pc";} +void platform_log(char const *format,...){assert(format);logs++;} +void *cache_files_tag_instances(long *count){*count=live_count;return live_table;} +void cache_files_set_tag_instances(void *instances,long count) { + assert(instances&&count>=2); + if(instances!=original_table){assert(live_table==original_table&&mcc_pause_tag_count()>24);published++;} + if(instances==original_table)restored++; + live_table=instances;live_count=count; +} +static boolean rasterizer_bitmap_new(struct bitmap_data *bitmap) { + assert(bitmap->width>0&&!(bitmap->width&(bitmap->width-1))); + assert(bitmap->height>0&&!(bitmap->height&(bitmap->height-1))); + assert(bitmap->format==11&&bitmap->depth==1&&bitmap->type==0&&bitmap->flags==1); + assert(bitmap->pixels_size==bitmap->width*bitmap->height*4&&bitmap->base_address); + if(++gpu_calls==fail_gpu)return FALSE; + if(null_renderer)return TRUE; + bitmap->hardware_format=test_malloc(16); + if(!bitmap->hardware_format)return FALSE; + device.textures[gpu_calls%3]=bitmap->hardware_format; + gpu_live++;return TRUE; +} +static void rasterizer_bitmap_changed(struct bitmap_data *bitmap) { + assert(bitmap->base_address&&(bitmap->hardware_format||null_renderer));check_guards();gpu_changed++; +} +static void rasterizer_bitmap_delete(struct bitmap_data *bitmap) { + unsigned stage; + assert(bitmap->hardware_format&&gpu_live); + for(stage=0;stagehardware_format) { + fputs("texture header released while still bound\n",stderr);exit(88); + } + test_free(bitmap->hardware_format);bitmap->hardware_format=NULL;gpu_live--;gpu_deleted++; +} +#define malloc test_malloc +#define free test_free +''' + implementations + r''' +#undef malloc +#undef free +static struct mcc_pause_instance original[2]; +static unsigned char original_copy[sizeof(original)]; +static void setup(void) { + int i; + for(i=0;i<4;i++) {borrowed_frames[i].width=16;borrowed_frames[i].height=256; + borrowed_frames[i].base_address=&borrowed_pixels[i];borrowed_frames[i].tag_index=77;} + borrowed_group.bitmaps.count=4;borrowed_group.bitmaps.address=borrowed_frames; + memcpy(borrowed_copy,borrowed_frames,sizeof(borrowed_copy));borrowed_group_copy=borrowed_group; + memset(original,0,sizeof(original)); + original[0].group=original[1].group='font';original[0].handle=0x11110000;original[1].handle=0x11120001; + original[0].name="ui\\large_ui";original[1].name="ui\\small_ui"; + original[0].data=&original[0];original[1].data=&original[1]; + memcpy(original_copy,original,sizeof(original)); + live_table=original;original_table=original;live_count=2; + global_scenario=&scenario;scenario.type=0; + device.textures[3]=&scenario; /* An unrelated texture identity must survive. */ +} +static int clean(void) { + unsigned textures=gpu_live,deletions=gpu_deleted,restores=restored; + boolean table_published=live_table!=original_table; + mcc_pause_runtime_unload(); + CHECK(gpu_deleted==deletions+textures&&restored==restores+table_published); + CHECK(null_renderer ? !gpu_deleted : gpu_changed==gpu_deleted); + CHECK(live_table==original_table&&live_count==2&&!live_allocations&&!gpu_live&&!mcc_pause_tag_count()); + CHECK(!device.textures[0]&&!device.textures[1]&&!device.textures[2]&&device.textures[3]==&scenario); + CHECK(!placeholders[0]&&!placeholders[1]); + CHECK(!memcmp(borrowed_frames,borrowed_copy,sizeof(borrowed_copy))); + CHECK(!memcmp(&borrowed_group,&borrowed_group_copy,sizeof(borrowed_group))); + CHECK(!memcmp(original_copy,original,sizeof(original)));return 0; +} +static int inventory(void) { + long i,j; + struct mcc_pause_instance *table=live_table; + CHECK(live_table!=original_table&&live_count>2&&published==1); + CHECK(!memcmp(original,table,sizeof(original))); + for(i=2;isequences.address; + struct bitmap_data const *frames=group->bitmaps.address; + CHECK(group->sequences.count==1&&sequence->first_bitmap_index==0&& + sequence->bitmap_count==group->bitmaps.count&&group->bitmaps.count>=1&&group->bitmaps.count<=2); + for(j=0;jbitmaps.count;j++) { + CHECK(frames[j].base_address); + if(frames[j].tag_index==77) CHECK(frames[j].base_address>= (void *)borrowed_pixels && + frames[j].base_address < (void *)(borrowed_pixels+4)); + else {CHECK(frames[j].tag_index==table[i].handle);CHECK(frames[j].hardware_format||null_renderer);} + } + } else CHECK(table[i].group=='DeLa'||table[i].group=='ustr'); + } + return 0; +} +static int pixel_check(void) { + long i,j;int x,y; + for(i=0;iborrowed)continue; + for(j=0;jgroup.bitmaps.count;j++) { + struct bitmap_data const *bitmap=&art->frames[j]; + unsigned long const *pixels=bitmap->base_address; + if(art->kind==MCC_PAUSE_ART_OBJECTIVES_PANEL) { + CHECK(pixels[10*bitmap->width+art->width/2]==0xFF000000UL); + CHECK(pixels[28*bitmap->width+art->width/2]==0xFF2896FFUL); + CHECK((pixels[40*bitmap->width+art->width/2]&0xFF) > + (pixels[(art->height-40)*bitmap->width+art->width/2]&0xFF)); + } + if(art->kind==MCC_PAUSE_ART_FOOTER_PANEL) { + CHECK(pixels[(art->height-10)*bitmap->width+art->width/2]==0xBF000000UL); + CHECK(pixels[(art->height-28)*bitmap->width+art->width/2]==0xFF2896FFUL); + CHECK((pixels[40*bitmap->width+art->width/2]&0xFF) > + (pixels[(art->height-40)*bitmap->width+art->width/2]&0xFF)); + } + if(art->kind==MCC_PAUSE_ART_CAMPAIGN_PANEL) { + CHECK(pixels[2*bitmap->width+art->width/2]==0xC00A2649UL); + CHECK(pixels[(art->height-3)*bitmap->width+art->width/2]==0xC0060E1DUL); + } + for(y=0;yheight;y++)for(x=0;xwidth;x++) { + unsigned long color=pixels[y*bitmap->width+x]; + if(art->kind==MCC_PAUSE_ART_DIM)CHECK(color==0x80000000UL); + else if(x>=art->width||y>=art->height)CHECK(!color); + else if(art->kind==MCC_PAUSE_ART_HIGHLIGHT) { + if(!j)CHECK(!color); + else {CHECK((color>>24)<=255);if(x==art->width/2&&y==art->height/2)CHECK(color==0xBB000D20UL);} + } + else if((art->kind==MCC_PAUSE_ART_OBJECTIVES_PANEL||art->kind==MCC_PAUSE_ART_FOOTER_PANEL|| + art->kind==MCC_PAUSE_ART_CAMPAIGN_PANEL) && + (color>>24)==0xC0) { + CHECK((color&255)>=28&&(color&255)<=73); + CHECK(((color>>8)&255)>=13&&((color>>8)&255)<=38); + CHECK(((color>>16)&255)>=5&&((color>>16)&255)<=10); + } + else CHECK(!color||color==0xFF000000UL||color==0xBF000000UL||color==0xFF2896FFUL||color==0xC00A2649UL||color==0x60204A75UL); + } + } + } + check_guards();return 0; +} +int main(int argc,char **argv) { + unsigned calls,textures,k;long old; + CHECK(argc==2);setup(); + if(!strcmp(argv[1],"borrowed-failure")) { + for(borrowed_failure=1;borrowed_failure<=4;borrowed_failure++) { + setup(); + if(borrowed_failure==3)borrowed_group.bitmaps.count=0; + if(borrowed_failure==4)borrowed_group.bitmaps.address=NULL; + borrowed_group_copy=borrowed_group; + CHECK(!mcc_pause_runtime_load()&&!published);CHECK(!clean()); + } + borrowed_failure=0;setup();CHECK(mcc_pause_runtime_load());CHECK(!inventory());CHECK(!clean());return 0; + } + if(!strcmp(argv[1],"inactive")) { + active=FALSE;CHECK(!mcc_pause_runtime_load()); + CHECK(!malloc_calls&&!gpu_calls&&!published&&!logs&&!mcc_pause_runtime_active()); + CHECK(mcc_pause_runtime_screen(1,TRUE)==NONE);CHECK(!clean());return 0; + } + if(!strcmp(argv[1],"fonts")) { + large_font=NONE;CHECK(mcc_pause_runtime_load());CHECK(mcc_pause.assets.font[0]==small_font);CHECK(!clean()); + large_font=original[0].handle;small_font=NONE; + CHECK(mcc_pause_runtime_load());CHECK(mcc_pause.assets.small_font[0]==large_font);CHECK(!clean()); + large_font=small_font=NONE; + CHECK(mcc_pause_runtime_load());CHECK(mcc_pause.assets.font[0]==original[0].handle);CHECK(!clean()); + original[0].group=original[1].group='bitm';memcpy(original_copy,original,sizeof(original)); + published=0;CHECK(!mcc_pause_runtime_load());CHECK(!published&&!live_allocations&&!gpu_live);CHECK(!clean());return 0; + } + if(!strcmp(argv[1],"table-bounds")) { + live_count=-1;CHECK(!mcc_pause_runtime_load()&&!published&&!live_allocations);setup(); + live_count=63001;CHECK(!mcc_pause_runtime_load()&&!published&&!live_allocations);setup(); + live_table=NULL;CHECK(!mcc_pause_runtime_load()&&!published&&!live_allocations);setup(); + CHECK(logs==3); + CHECK(!clean());return 0; + } + if(!strcmp(argv[1],"art-bounds")) { + static short const invalid[][2]={{0,1},{1,0},{-1,1},{1,-1},{1025,1},{1,513}}; + long handle; + for(k=0;k +typedef uint32_t DWORD; +typedef struct {DWORD dwLowDateTime,dwHighDateTime;} FILETIME; +typedef struct { + DWORD dwFileAttributes;FILETIME ftCreationTime,ftLastAccessTime,ftLastWriteTime; + DWORD nFileSizeHigh,nFileSizeLow; +} WIN32_FILE_ATTRIBUTE_DATA; +#define GetFileExInfoStandard 0 +#define ERROR_FILE_NOT_FOUND 2 +#define ERROR_PATH_NOT_FOUND 3 +int GetFileAttributesExA(char const *,int,void *); +DWORD GetLastError(void); +''') + source = tmp_path / "test.c" + source.write_text(r''' +#include "cseries.h" +#include "xtl.h" +#include "mcc_cache.h" +#include +#include +#include +#define CHECK(x) do {if(!(x)){fprintf(stderr,"line %d: %s\n",__LINE__,#x);return 1;}}while(0) +static char paths[9][128]; +static WIN32_FILE_ATTRIBUTE_DATA files[9]; +static int count,probes,valid=1,mutate,denied=-1,present[9]; +static DWORD last_error; +static int hosting,prepared; +struct network_game_server *global_network_game_server_get(void) {return hosting ? (void *)&hosting : NULL;} +int mcc_validation_lookup(char const *name,uint32_t *checksum,unsigned char digest[32]) { + (void)name;(void)checksum;(void)digest;return prepared; +} +char const *mcc_identity_local_name(char const *name) { + return name && !strcmp(name,"mcc_maps/host/a10") ? "mcc_maps/package/a10" : name; +} +DWORD GetLastError(void) {return last_error;} +int GetFileAttributesExA(char const *path,int level,void *out) { + int i;(void)level; + if(strstr(path,"custom_maps") || strstr(path,"d:\\maps\\"))exit(90); + for(i=0;i +#include +#include +#include +#include +#include +#include +#include "mcc_preview_image.h" +typedef int boolean; +typedef unsigned long pixel32; +typedef union rectangle2d {struct {short y0,x0,y1,x1;};short v[4];} rectangle2d; +typedef struct {float alpha,red,green,blue;} real_argb_color; +#define TRUE 1 +#define FALSE 0 +#define NONE (-1) +#define SHORT_MAX 32767 +#define MCC_MAPS_FIRST_DISPLAY_INDEX 0x1000 +#define MCC_MAPS_MAXIMUM 1024 +#define NUMBEROF(a) (sizeof(a)/sizeof((a)[0])) +#define MIN(a,b) ((a)<(b)?(a):(b)) +#define MAX(a,b) ((a)>(b)?(a):(b)) +struct bitmap_data {short width,height;uintptr_t base_address;int hardware_format;}; +struct rasterizer_dynamic_screen_geometry_parameters {int unused;}; +static int live,loads,draws,text_draws,current_font,fail_image,portrait; +static rectangle2d drawn,clipped,drawn_texels; +static wchar_t drawn_text[512]; +static const char *tag_name="ui\\shell\\bitmaps\\mp_map_grafix"; +static const char *tag_get_name(long tag) {(void)tag;return tag_name;} +static long tag_loaded(long kind,const char *name) {(void)kind;(void)name;return 2;} +static rectangle2d *set_rectangle2d(rectangle2d *r,short x,short y,short x1,short y1) {r->x0=x;r->y0=y;r->x1=x1;r->y1=y1;return r;} +static const char *mcc_maps_level_name(short i) {static char level[64];if(i<0||i>=8)return NULL;snprintf(level,sizeof(level),"mcc_maps\\pkg\\level%d",i);return level;} +static boolean mcc_maps_campaign(short i) {return i%2;} +void mcc_preview_image_free(struct mcc_preview_image *im) {free(im->pixels);memset(im,0,sizeof(*im));} +int mcc_preview_image_load(const char *level,int campaign,struct mcc_preview_image *im) { + unsigned i;(void)level;(void)campaign;loads++;if(fail_image)return 0; + im->width=portrait?292:668;im->height=portrait?668:292;im->pixels=malloc(668*292*4);for(i=0;i<668*292;i++)im->pixels[i]=i;return 1; +} +static struct bitmap_data *bitmap_2d_new(short w,short h,short m,short f) { + struct bitmap_data *b=calloc(1,sizeof(*b));assert(f==11&&!m);b->width=w;b->height=h;b->base_address=(uintptr_t)calloc(w*h,4);live++;return b; +} +static void bitmap_rebuild(struct bitmap_data *b) {b->hardware_format=1;} +static void bitmap_delete(struct bitmap_data *b) {free((void *)b->base_address);free(b);live--;} +static void draw_bitmap_in_rect(struct bitmap_data *b,rectangle2d *r,rectangle2d *t,rectangle2d *c,pixel32 color,struct rasterizer_dynamic_screen_geometry_parameters *p,boolean no_plasma) { + (void)b;(void)color;(void)p;(void)no_plasma;draws++;drawn=*r;clipped=*c;drawn_texels=*t; +} +static void draw_string_set_draw_mode(long f,short s,short j,unsigned long flags,const real_argb_color *c) {(void)s;(void)j;(void)flags;(void)c;current_font=(int)f;} +static void draw_unicode_string_compute_bounds(const rectangle2d *b,const wchar_t *s,rectangle2d *ink,rectangle2d *cursor) { + int width=current_font==2?6:10,height=current_font==2?12:22,x=b->x0,y=b->y0,right=x; + for(;*s;s++){if(*s=='\r'){y+=height;x=b->x0;}else x+=width;right=MAX(x,right);} + set_rectangle2d(ink,b->x0,b->y0,(short)right,(short)(y+height));set_rectangle2d(cursor,(short)x,(short)y,(short)x,(short)(y+height)); +} +static void rasterizer_draw_unicode_string(const rectangle2d *b,const rectangle2d *c,void *cursor,short adjust,const wchar_t *text) { + rectangle2d ink,pos;(void)cursor;(void)adjust;text_draws++;drawn=*b;clipped=*c;wcscpy(drawn_text,text); + draw_unicode_string_compute_bounds(b,text,&ink,&pos);assert(ink.x1<=b->x1);assert(ink.y1<=b->y1); +} +''' + code = preamble + for name in ("mcc_menu_preview.c", "mcc_menu_text.c"): + code += re.sub(r'^#include[^\n]*\n', '', (ROOT / "port/linux/game" / name).read_text(), flags=re.M) + # Compile the production pure fit routine, with no decoder dependency. + from harness import function + code += function((ROOT / "port/linux/src/mcc_preview_image.c").read_text(), "mcc_preview_fit") + code += r''' +int main(void) { + rectangle2d box,clip;real_argb_color color={1,1,1,1};int i;wchar_t row_text[64]; + wcscpy(row_text,L"Short title");mcc_menu_text_row(row_text);assert(!wcscmp(row_text,L"Short title")); + wcscpy(row_text,L"A long MCC title which needs to fit inside the map list row"); + mcc_menu_text_row(row_text);assert(width_of(row_text)<=310&&wcsstr(row_text,L"...")); + assert(mcc_menu_preview_index(0,0)==NONE);assert(mcc_menu_preview_index(0,0x4000)==NONE); + assert(mcc_menu_preview_index(0,0x6000)==NONE);assert(mcc_menu_preview_index(0,0x1000)==0); + tag_name="unrelated";assert(mcc_menu_preview_index(0,0x1000)==NONE);tag_name="ui\\shell\\bitmaps\\mp_map_grafix"; + set_rectangle2d(&box,419,87,559,201);set_rectangle2d(&clip,420,90,550,199); + assert(mcc_menu_preview_draw(0,&box,&clip,0,NULL));assert(live==1&&loads==1&&draws==1); + assert(drawn.x0>=box.x0&&drawn.x1<=box.x1&&drawn.y0>=box.y0&&drawn.y1<=box.y1); + assert(drawn.x1-drawn.x0==140&&drawn.y1-drawn.y0==114); + assert(clipped.x0==420&&clipped.x1==550&&clipped.y0==90&&clipped.y1==199); + assert(drawn_texels.x1==512&&drawn_texels.y1==416); + assert(mcc_menu_preview_draw(0,&box,NULL,0,NULL));assert(loads==1); + tag_name="pc\\mcc_xbox\\card_0\\picture"; + assert(mcc_menu_preview_draw(0,&box,&clip,0,NULL)); + assert(!memcmp(&drawn,&box,sizeof(box)));assert(drawn_texels.x0==0&&drawn_texels.x1==512); + assert(drawn_texels.y0==0&&drawn_texels.y1==416); + assert(*(uint32_t *)(uintptr_t)previews[0].bitmap->base_address==155); /* actual center pixels, not a left crop */ + assert(clipped.x0==420&&clipped.x1==550&&clipped.y0==90&&clipped.y1==199); + tag_name="ui\\shell\\bitmaps\\mp_map_grafix"; + for(i=1;i<8;i++) assert(mcc_menu_preview_draw((short)i,&box,NULL,0,NULL)); + assert(live==4&&loads==8);mcc_menu_preview_clear();assert(live==0); + fail_image=1;assert(!mcc_menu_preview_draw(0,&box,NULL,0,NULL));assert(loads==9); + assert(!mcc_menu_preview_draw(0,&box,NULL,0,NULL));assert(loads==9);mcc_menu_preview_clear(); + fail_image=0;assert(mcc_menu_preview_draw(0,&box,NULL,0,NULL));assert(loads==10);mcc_menu_preview_clear();assert(live==0); + portrait=1;assert(mcc_menu_preview_draw(0,&box,NULL,0,NULL)); + assert(!memcmp(&drawn,&box,sizeof(box))&&drawn_texels.x1==512&&drawn_texels.y1==416); + assert(*(uint32_t *)(uintptr_t)previews[0].bitmap->base_address==215*292); /* centered vertical crop */ + mcc_menu_preview_clear();assert(live==0); + tag_name="pc\\main_menu\\mp_map_right_data";set_rectangle2d(&box,417,258,563,394); + assert(!mcc_menu_text_draw(0,1,L"Xbox",1,0,&color,&box,NULL));assert(!text_draws); + assert(!mcc_menu_text_draw(0,0x4000,L"CE",1,0,&color,&box,NULL));assert(!text_draws); + assert(mcc_menu_text_draw(0,0x1000,L"Steam Workshop\r\nHalo CE - A level with a long title and description",1,0,&color,&box,NULL)); + assert(wcschr(drawn_text,'\r')&&text_draws==1); + tag_name="pc\\main_menu\\mp_map_right_name";set_rectangle2d(&box,417,204,563,247); + assert(mcc_menu_text_draw(0,0x1000,L"A VERY LONG MCC LEVEL TITLE WITH LOTS OF WORDS",1,0,&color,&box,NULL)); + assert(current_font==2);assert(wcsstr(drawn_text,L"...")==NULL); + assert(mcc_menu_text_draw(0,0x1000,L"ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ",1,0,&color,&box,NULL)); + assert(wcsstr(drawn_text,L"...")!=NULL); + tag_name="pc\\modern\\campaign\\mcc_folder_name"; + assert(mcc_menu_text_draw(0,NONE,L"Workshop folder with a long package title",1,0,&color,&box,NULL)); + tag_name="pc\\mcc_xbox\\card_0\\mcc_folder_help";set_rectangle2d(&box,83,258,227,394); + assert(mcc_menu_text_draw(0,NONE,L"A long description must not cover the earned completion badges at the bottom of the native Xbox level card even when every difficulty has been completed.",2,0,&color,&box,NULL)); + assert(drawn.y0==258&&drawn.y1==341&&clipped.y1==341&&wcsstr(drawn_text,L"...")); + tag_name="pc\\main_menu\\settings_select\\player_setup\\player_profile_edit\\network_setup\\mcc_download\\description"; + set_rectangle2d(&box,40,60,600,280); + assert(mcc_menu_text_draw(0,NONE,L"The host package is missing or differs. Downloads are disabled. Visit the Workshop page or obtain the exact package from the host.\\nExisting packages remain installed.",2,0,&color,&box,NULL)); + assert(wcschr(drawn_text,'\r')); + puts("MCC preview bounds, cache lifecycle, text wrapping and Xbox/CE isolation passed");return 0; +} +''' + source=tmp_path/"menu.c"; source.write_text(code) + exe=tmp_path/("menu.exe" if sys.platform=="win32" else "menu") + flags=["--target=i686-pc-windows-msvc","-fuse-ld=lld","-D_CRT_SECURE_NO_WARNINGS"] if sys.platform=="win32" else [] + result=subprocess.run([compiler,*flags,"-std=gnu11","-Wall","-Wextra","-Werror","-Wno-multichar","-I",str(ROOT/"port/linux/src"),str(source),"-o",str(exe)],capture_output=True,text=True) + assert result.returncode==0,result.stderr + result=subprocess.run([str(exe)],capture_output=True,text=True,timeout=15) + assert result.returncode==0,result.stderr + + +def test_authored_thumbnail_boxes_and_hooks(): + import xml.etree.ElementTree as ET + widgets=[] + for path in (ROOT/"port/assets/menus").rglob("*.xml"): + for widget in ET.parse(path).getroot().iter("widget"): + if widget.get("name","").split("/")[-1] in ("mp_map_right_pic","lobby_map_pic"): + widgets.append(widget) + assert len(widgets)>=6 + assert all((w.get("width"),w.get("height"))==("140","114") for w in widgets) + ui=(ROOT/"source/interface/ui_widget.c").read_text() + assert 'mcc_menu_preview_draw(mcc_picture_index, &bounds, clip' in ui + assert 'mcc_menu_text_draw(widget->definition_tag_index' in ui + for file in ("mcc_maps.c","menu_tags.c"): + assert 'mcc_menu_preview_clear();' in (ROOT/"port/linux/game"/file).read_text() diff --git a/tools/test_mcc_previews.py b/tools/test_mcc_previews.py new file mode 100644 index 0000000000..1faad99913 --- /dev/null +++ b/tools/test_mcc_previews.py @@ -0,0 +1,294 @@ +"""Actual MCC package reader/PNG decoder, with generated (non-game) assets.""" +import json +import os +from pathlib import Path +import shutil +import struct +import subprocess +import sys +import zlib + +import pytest +from harness import function + +ROOT = Path(__file__).resolve().parents[1] +SRC = ROOT / "port/linux/src" +ZLIB = ROOT / "port/third_party/zlib" + + +def chunk(kind, data): + return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data)) + + +def png(width=3, height=2, channels=4, filter_type=0, *, extra=b"", raw=None): + pixels = bytes((i * 37 + 11) % 256 for i in range(width * height * channels)) + stride = width * channels + def paeth(a, b, c): + p = a + b - c + return min((a, b, c), key=lambda v: abs(p - v)) + rows = bytearray() + for y in range(height): + rows.append(filter_type) + for x in range(stride): + a = pixels[y * stride + x - channels] if x >= channels else 0 + b = pixels[(y - 1) * stride + x] if y else 0 + c = pixels[(y - 1) * stride + x - channels] if y and x >= channels else 0 + predictor = (0, a, b, (a + b) // 2, paeth(a, b, c))[filter_type] if filter_type < 5 else 0 + rows.append((pixels[y * stride + x] - predictor) % 256) + header = struct.pack(">IIBBBBB", width, height, 8, 6 if channels == 4 else 2, 0, 0, 0) + return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header) + extra + chunk(b"IDAT", zlib.compress(rows if raw is None else raw)) + chunk(b"IEND", b""), pixels + + +DRIVER = r''' +#include "mcc_preview_image.h" +#include "mcc_manifest.h" +#include "mcc_menu_metadata.h" +#include "posix.h" +#include "server_json.h" +#include +#include +#include +void platform_translate_path(const char *in,char *out,unsigned long size) { + (void)in; snprintf(out,size,"%s",getenv("TEST_MAP_FILE")); +} +int steam_workshop_package_folder(const char *id,char *out,unsigned long size) { + const char *p=getenv("TEST_STEAM_FOLDER"); (void)id; + if(!p || !*p) return 0; snprintf(out,size,"%s",p); return 1; +} +static void report(int ok,struct mcc_preview_image *image) { + unsigned i; uint32_t hash=2166136261u; + for(i=0;iwidth*image->height;i++) {hash^=image->pixels[i];hash*=16777619u;} + printf("%d %u %u %u\n",ok,image->width,image->height,hash);free(image->pixels); +} +int main(int argc,char **argv) { + struct mcc_preview_image image; unsigned char *data; FILE *file; unsigned length; int ok,w,h; + if(argc<3) return 2; + if(!strcmp(argv[1],"campaign-labels")) { + static struct mcc_menu_metadata metadata; + if(!mcc_menu_metadata_load(argv[2],1,&metadata))return 4; + printf("%d\n",metadata.count);return 0; + } + if(!strcmp(argv[1],"labels")) { + static struct mcc_menu_metadata metadata;const struct steam_workshop_map_text *map; + if(!mcc_menu_metadata_load(argv[2],0,&metadata))return 4; + map=mcc_menu_metadata_find(&metadata,"level");if(!map)return 5; + printf("%s|%s\n",metadata.title,map->title);return 0; + } + if(!strcmp(argv[1],"load")) {ok=mcc_preview_image_load(argv[2],atoi(argv[3]),&image);report(ok,&image);return 0;} + if(!strcmp(argv[1],"read")) {data=malloc(1024);printf("%d\n",posix_mcc_preview_read(argv[2],argv[3],data,1024));free(data);return 0;} + if(!strcmp(argv[1],"fit")) {ok=mcc_preview_fit(atoi(argv[2]),atoi(argv[3]),atoi(argv[4]),atoi(argv[5]),&w,&h);printf("%d %d %d\n",ok,ok?w:0,ok?h:0);return 0;} + data=malloc(MCC_PREVIEW_FILE_LIMIT+1); file=fopen(argv[2],"rb"); if(!file) return 3; + length=(unsigned)fread(data,1,MCC_PREVIEW_FILE_LIMIT+1,file);fclose(file); + ok=mcc_preview_png(data,length,&image);report(ok,&image);free(data);return 0; +} +''' + + +@pytest.fixture(scope="session") +def preview_tool(tmp_path_factory): + compiler = os.environ.get("CC") or shutil.which("clang") or shutil.which("cc") + if not compiler: + pytest.skip("C compiler required") + work = tmp_path_factory.mktemp("mcc-previews") + steam = (SRC / "steam_workshop.c").read_text() + parser = '\n'.join(function(steam, name) for name in ( + "copy_text", "parse", "path_is_plain", "slashes", "neutral_title", "steam_workshop_read_item", "steam_workshop_read_map")) + (work / "driver.c").write_text(DRIVER + '\n' + parser) + windows = sys.platform == "win32" + flags = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld", "-D_CRT_SECURE_NO_WARNINGS"] if windows else ["-D_GNU_SOURCE"] + if os.environ.get("MCC_PREVIEW_SANITIZE"): + flags += ["-fsanitize=address,undefined", "-fno-omit-frame-pointer"] + exe = work / ("preview.exe" if windows else "preview") + files = ROOT / "port/windows/src/win32_files.c" if windows else SRC / "posix_files.c" + sources = [work / "driver.c", SRC / "mcc_preview_image.c", SRC / "mcc_menu_metadata.c", SRC / "posix_mcc_preview.c", + SRC / "mcc_manifest.c", SRC / "server_json.c", files, *sorted(ZLIB.glob("*.c"))] + result = subprocess.run([compiler, *flags, "-std=gnu11", "-DZ_PREFIX", "-I", str(SRC), "-I", str(ZLIB), + *map(str, sources), "-o", str(exe)], capture_output=True, text=True) + assert result.returncode == 0, result.stderr + return exe + + +def run(tool, *args, **env): + result = subprocess.run([str(tool), *map(str, args)], env=dict(os.environ, **env), capture_output=True, text=True, timeout=15) + assert result.returncode == 0, result.stderr + return tuple(map(int, result.stdout.split())) + + +@pytest.mark.parametrize("channels", [3, 4]) +@pytest.mark.parametrize("filter_type", range(5)) +def test_png_pixels(preview_tool, tmp_path, channels, filter_type): + data, pixels = png(channels=channels, filter_type=filter_type) + path = tmp_path / "image.png"; path.write_bytes(data) + expected = 2166136261 + for i in range(0, len(pixels), channels): + r, g, b = pixels[i:i+3]; a = pixels[i+3] if channels == 4 else 255 + expected = ((expected ^ (a << 24 | r << 16 | g << 8 | b)) * 16777619) & 0xffffffff + assert run(preview_tool, "png", path) == (1, 3, 2, expected) + + +def test_invalid_png(preview_tool, tmp_path): + data, _ = png() + header = lambda w,h,d,c,i: chunk(b"IHDR", struct.pack(">IIBBBBB",w,h,d,c,0,0,i)) + cases = [b"", b"", data + b"trailing", data[:-1], data[:40], + data[:16]+b"\xff\xff\xff\xff"+data[20:], png(filter_type=5)[0], + png(raw=b"\0")[0], png(raw=b"\0"*100)[0], + png(extra=chunk(b"EVIL", b""))[0], png(extra=chunk(b"tRNS",b"\0"*6))[0], + png(extra=chunk(b"texT",b"bad reserved bit"))[0], png(extra=chunk(b"1234",b"bad name"))[0], + png(extra=chunk(b"PLTE",b"\0"*3)*2)[0]] + for w,h,d,c,i in [(0,1,8,6,0),(2049,1,8,6,0),(1,2049,8,6,0),(1,1,16,6,0),(1,1,8,3,0),(1,1,8,6,1)]: + cases.append(data[:8]+header(w,h,d,c,i)+data[33:]) + # Valid CRCs around truncated/extra zlib streams and illegal chunk order. + compressed = zlib.compress(b"\0"*26) + cases += [data[:33]+chunk(b"IDAT",compressed[:-1])+chunk(b"IEND",b""), + data[:33]+chunk(b"IDAT",compressed+b"extra")+chunk(b"IEND",b""), + data[:33]+chunk(b"IDAT",compressed[:3])+chunk(b"tEXt",b"x\0y")+chunk(b"IDAT",compressed[3:])+chunk(b"IEND",b""), + data[:33]+data[8:33]+data[33:]] + path=tmp_path/"bad.png" + for case in cases: + path.write_bytes(case) + assert run(preview_tool,"png",path)[:3] == (0,0,0) + path.write_bytes(b"\0" * (8*1024*1024+1)) + assert run(preview_tool,"png",path)[0] == 0 + + +def package(root, *, campaign=False, large="assets/Large.PNG", thumb="thumb.png"): + (root/"meta").mkdir(parents=True) + (root/"assets").mkdir() + content = {"HasCampaign": True} if campaign else {"MultiplayerMaps": ["META/level.json"]} + (root/"ModInfo.json").write_text(json.dumps({"Engine":"Halo1","Title":{"Neutral":"Offline package"},"GameModContents":content})) + (root/"CampaignInfo.json").write_text(json.dumps({"CampaignMaps":["META/level.json"]})) + (root/"meta/level.json").write_text(json.dumps({"ScenarioFile":"levels/test/level", "Title":{"Neutral":"Authored level"}, "Images":{"Large":large,"Thumbnail":thumb}})) + (root/"assets/large.png").write_bytes(png(6,3)[0]) + (root/"thumb.png").write_bytes(png(3,2)[0]) + + +@pytest.mark.parametrize("campaign", [False, True]) +def test_metadata_and_fallback(preview_tool, tmp_path, campaign): + package(tmp_path,campaign=campaign) + def load(): + return run(preview_tool,"load",r"mcc_maps\package\level",int(campaign), TEST_MAP_FILE=str(tmp_path/"level.map")) + assert load()[:3] == (1,6,3) + (tmp_path/"assets/large.png").write_bytes(b"broken") + assert load()[:3] == (1,3,2) + (tmp_path/"thumb.png").unlink() + assert load()[:3] == (0,0,0) + + +def test_package_identity_and_missing_metadata(preview_tool, tmp_path): + local=tmp_path/"local"; steam=tmp_path/"steam" + package(local); package(steam) + (steam/"maps").mkdir() + assert run(preview_tool,"load",r"mcc_maps\12345\level",0, TEST_MAP_FILE=str(steam/"maps/level.map"), TEST_STEAM_FOLDER=str(steam/"maps"))[:3] == (1,6,3) + (local/"ModInfo.json").unlink() + assert run(preview_tool,"load",r"mcc_maps\12345\level",0, TEST_MAP_FILE=str(local/"level.map"), TEST_STEAM_FOLDER=str(steam/"maps"))[0] == 0 + assert run(preview_tool,"load",r"custom_maps\level",0, TEST_MAP_FILE=str(steam/"maps/level.map"))[0] == 0 + + +def test_authored_offline_labels(preview_tool,tmp_path): + package(tmp_path) + assert subprocess.check_output([str(preview_tool),"labels",str(tmp_path)],text=True).strip()=="Offline package|Authored level" + + +@pytest.mark.parametrize("count", [75, 1024]) +def test_large_package_preserves_late_labels_and_preview(preview_tool, tmp_path, count): + package(tmp_path) + names = [] + for index in range(count - 1): + name = f"meta/other{index}.json" + (tmp_path / name).write_text(json.dumps({"ScenarioFile": f"other{index}"})) + names.append(name) + names.append("meta/level.json") + mod = tmp_path / "ModInfo.json" + data = json.loads(mod.read_text()) + data["GameModContents"]["MultiplayerMaps"] = names + mod.write_text(json.dumps(data)) + assert subprocess.check_output([str(preview_tool), "labels", str(tmp_path)], text=True).strip() == "Offline package|Authored level" + assert run(preview_tool, "load", r"mcc_maps\package\level", 0, + TEST_MAP_FILE=str(tmp_path / "level.map"))[:3] == (1, 6, 3) + + +def test_ambiguous_or_wrong_metadata(preview_tool,tmp_path): + package(tmp_path) + mod=tmp_path/"ModInfo.json" + original=json.loads(mod.read_text()) + def load(campaign=0): + return run(preview_tool,"load",r"mcc_maps\package\level",campaign, TEST_MAP_FILE=str(tmp_path/"level.map"))[0] + mod.write_text(json.dumps(dict(original,Engine="Halo2"))) + assert load()==0 + for paths in (["meta/level.json"]*2, ["meta/level.json"]*65, ["unlisted.json"]): + mod.write_text(json.dumps(dict(original,GameModContents={"MultiplayerMaps":paths}))) + assert load()==0 + mod.write_text(json.dumps(dict(original,GameModContents={"HasCampaign":True}))) + mission=tmp_path/"meta/level.json"; metadata=json.loads(mission.read_text()) + for kind in ("Cinematic", None, 1): + mission.write_text(json.dumps(dict(metadata,CampaignMapKind=kind))) + assert load(1)==0 + + +@pytest.mark.parametrize("path", ["../outside.png", "/outside.png", "C:/outside.png", "assets/../thumb.png", + "assets//large.png", "assets/./large.png", "thumb.png:stream", "NUL.png", "assets/", "thumb.png.", "thumb.png "]) +def test_path_refusal(preview_tool,tmp_path,path): + package(tmp_path,large=path,thumb="") + assert run(preview_tool,"load",r"mcc_maps\package\level",0, TEST_MAP_FILE=str(tmp_path/"level.map"))[0] == 0 + + +def test_link_escape(preview_tool,tmp_path): + root=tmp_path/"root"; package(root,large="link/large.png",thumb="") + outside=tmp_path/"outside"; outside.mkdir(); (outside/"large.png").write_bytes(png()[0]) + try: + (root/"link").symlink_to(outside,target_is_directory=True) + except OSError: + if sys.platform != "win32": raise + result = subprocess.run(["cmd","/c","mklink","/J",str(root/"link"),str(outside)],capture_output=True,text=True) + assert result.returncode == 0, result.stdout + result.stderr + try: + assert run(preview_tool,"load",r"mcc_maps\package\level",0, TEST_MAP_FILE=str(root/"level.map"))[0] == 0 + # The same containment applies to a map JSON, not just its image. + (outside/"map.json").write_text(json.dumps({"ScenarioFile":"level","Images":{"Large":"assets/large.png"}})) + (root/"ModInfo.json").write_text(json.dumps({"Engine":"Halo1","GameModContents":{"MultiplayerMaps":["link/map.json"]}})) + assert run(preview_tool,"load",r"mcc_maps\package\level",0, TEST_MAP_FILE=str(root/"level.map"))[0] == 0 + finally: + if sys.platform == "win32" and not (root/"link").is_symlink(): os.rmdir(root/"link") + else: (root/"link").unlink() + + +@pytest.mark.skipif(sys.platform == "win32", reason="POSIX pipes and case-sensitive aliases") +def test_nonregular_and_ambiguous(preview_tool,tmp_path): + os.mkfifo(tmp_path/"pipe") + assert run(preview_tool,"read",tmp_path,"pipe") == (0,) + (tmp_path/"one").write_text("a"); (tmp_path/"ONE").write_text("b") + assert run(preview_tool,"read",tmp_path,"one") == (0,) + (tmp_path/"link").symlink_to(tmp_path/"one") + assert run(preview_tool,"read",tmp_path,"link") == (0,) + + +def test_file_capacity(preview_tool,tmp_path): + path=tmp_path/"bounded" + for size,expected in ((0,0),(1024,1024),(1025,0)): + path.write_bytes(b"x"*size) + assert run(preview_tool,"read",tmp_path,"bounded")== (expected,) + (tmp_path/"directory").mkdir() + assert run(preview_tool,"read",tmp_path,"directory")== (0,) + + +@pytest.mark.parametrize("shape,expected", [((668,292),(140,61)),((316,160),(140,70)),((100,200),(57,114)),((1,2048),(1,114)),((2048,1),(140,1))]) +def test_fit(preview_tool,shape,expected): + assert run(preview_tool,"fit",*shape,140,114) == (1,*expected) + + +def test_bad_fit(preview_tool): + for values in [(0,1,140,114),(1,0,140,114),(2049,1,140,114),(1,1,0,114),(1,1,140,-1),(1,1,40000,114)]: + assert run(preview_tool,"fit",*values)[0] == 0 + + +@pytest.mark.parametrize("kind,expected", [("Default",1),("default",1),("DEFAULT",1),("dEfAuLt",1), + ("Hub",0),("Default ",0),(None,0),(0,0),(True,0),([],0),({},0)]) +def test_campaign_labels_use_supported_kind_case(preview_tool, tmp_path, kind, expected): + package(tmp_path, campaign=True) + path = tmp_path / "meta/level.json" + data = json.loads(path.read_text()); data["CampaignMapKind"] = kind + path.write_text(json.dumps(data)); original = path.read_bytes() + result = subprocess.run([str(preview_tool), "campaign-labels", str(tmp_path)], capture_output=True, text=True) + assert result.returncode == 0, result.stderr + assert result.stdout.strip() == str(expected) + assert path.read_bytes() == original diff --git a/tools/test_mcc_progress.py b/tools/test_mcc_progress.py new file mode 100644 index 0000000000..010c3f9a5a --- /dev/null +++ b/tools/test_mcc_progress.py @@ -0,0 +1,92 @@ +"""Real completion journal: profile/mission isolation and interrupted writes.""" +import json +import re +from pathlib import Path + +from test_hud_button_style import run_c + +ROOT = Path(__file__).resolve().parents[1] + + +def test_completion_journal(tmp_path): + for i in range(3): (tmp_path/str(i)).mkdir() + code = re.sub(r'^#include[^\n]*\n', '', (ROOT/'port/linux/game/mcc_progress.c').read_text(), flags=re.M) + run_c(tmp_path, r''' +#include +#include +#include +#include +#include +typedef int boolean; +#define TRUE 1 +#define FALSE 0 +#define NONE (-1) +#define _error_silent 0 +typedef unsigned long DWORD; +#define INVALID_FILE_ATTRIBUTES ((DWORD)-1) +#define FILE_ATTRIBUTE_DIRECTORY 16 +#define ERROR_FILE_NOT_FOUND 2 +#define ERROR_PATH_NOT_FOUND 3 +static DWORD GetFileAttributesA(const char *path){FILE *f=fopen(path,"rb");if(!f)return INVALID_FILE_ATTRIBUTES;fclose(f);return 0;} +static DWORD GetLastError(void){return ERROR_FILE_NOT_FOUND;} +static int CopyFileA(const char *from,const char *to,int exclusive){ + FILE *in,*out;int c;(void)exclusive;out=fopen(to,"rb");if(out){fclose(out);return 0;} + in=fopen(from,"rb");if(!in)return 0;out=fopen(to,"wb");if(!out){fclose(in);return 0;} + while((c=fgetc(in))!=EOF)fputc(c,out);fclose(in);return fclose(out)==0; +} +static short player_spawn_count=2; +static long profiles[4]={0,1,-1,-1}; +static int warnings; +static long player_ui_get_active_player_profile_index(short player) {return profiles[player];} +static int player_profile_get_enclosing_directory_path(long profile,char *path) { + if(profile<0||profile>1)return 0; + snprintf(path,256,"%s/%ld/",TEST_ROOT,profile);return 1; +} +static int csstrcasecmp(const char *a,const char *b) { + while(*a&&tolower((unsigned char)*a)==tolower((unsigned char)*b)){a++;b++;} + return tolower((unsigned char)*a)-tolower((unsigned char)*b); +} +static void error(int severity,const char *format,...) {(void)severity;(void)format;warnings++;} +'''.replace('TEST_ROOT', json.dumps(tmp_path.as_posix())) + code + r''' +static long size(const char *path) {FILE *f=fopen(path,"rb");long n;assert(f);fseek(f,0,SEEK_END);n=ftell(f);fclose(f);return n;} +int main(void) { + const char *a="mcc_maps\\one\\a10",*b="mcc_maps\\two\\a10"; + char path[300],renamed[300],destination[300],original[300];FILE *f;unsigned char record[76]={0};unsigned checksum;int i; + snprintf(original,sizeof(original),"%s/0/blam.sav",TEST_ROOT); + snprintf(destination,sizeof(destination),"%s/2/",TEST_ROOT); + assert(mcc_progress_copy(original,destination)); /* no companion leaves native rename untouched */ + assert(!mcc_progress_flags(0,a)); + mcc_progress_complete(a,1); + assert(mcc_progress_flags(0,a)==2&&mcc_progress_flags(1,a)==2&&!mcc_progress_flags(0,b)); + assert(mcc_progress_flags(0,"mcc_maps\\ONE\\A10")==2); + assert(mcc_progress_path(0,path)&&size(path)==76); + mcc_progress_complete(a,1);assert(size(path)==76); /* replay is idempotent */ + profiles[1]=-1;mcc_progress_complete(a,3); + assert(mcc_progress_flags(0,a)==10&&mcc_progress_flags(1,a)==2); + mcc_progress_complete(b,2);assert(mcc_progress_flags(0,b)==4&&mcc_progress_flags(0,a)==10); + assert(!mcc_progress_flags(0,"levels\\a10\\a10")); + assert(!mcc_progress_save(0,"custom_maps\\a10",1)); + assert(!mcc_progress_save(0,a,-1)&&!mcc_progress_save(0,a,4)); + assert(!mcc_progress_save(-1,a,1)); + f=fopen(path,"ab");assert(f);fwrite("MCC1bad",1,7,f);fclose(f); + assert(mcc_progress_flags(0,a)==10); /* prior good records survive a torn append */ + assert(!mcc_progress_save(0,a,2)&&size(path)==235); + mcc_progress_complete(a,2);assert(warnings==1&&size(path)==235); + strcpy(original,path);strcpy(strrchr(original,'/')+1,"blam.sav"); + snprintf(renamed,sizeof(renamed),"%s/2/",TEST_ROOT); + assert(mcc_progress_copy(original,renamed)); /* rename preserves even a damaged tail */ + strcat(renamed,"mcc_completed.dat");assert(size(renamed)==235&&size(path)==235); + assert(!mcc_progress_copy(original,destination)); /* exclusive copy refuses an existing companion */ + assert(size(path)==235); /* failure cannot delete the original */ + /* A checksum mismatch and unsupported version cannot manufacture badges. */ + assert(mcc_progress_path(1,path));f=fopen(path,"r+b");assert(f);fputc('X',f);fclose(f); + assert(!mcc_progress_flags(1,a)&&!mcc_progress_save(1,a,1)); + f=fopen(path,"wb");assert(f); + memcpy(record,"MCC1",4);strcpy((char*)record+4,a);record[68]=1; + checksum=mcc_progress_checksum(record);for(i=0;i<4;i++)record[72+i]=(unsigned char)(checksum>>(8*i)); + for(i=0;i<4096;i++)assert(fwrite(record,1,76,f)==76);fclose(f); + assert(mcc_progress_flags(1,a)==1&&!mcc_progress_save(1,a,2)); + assert(size(path)==4096*76); + return 0; +} +'''.replace('TEST_ROOT', json.dumps(tmp_path.as_posix()))) diff --git a/tools/test_mcc_protocol.py b/tools/test_mcc_protocol.py new file mode 100644 index 0000000000..82baaa5e98 --- /dev/null +++ b/tools/test_mcc_protocol.py @@ -0,0 +1,254 @@ +"""Shared OpenCE protocol 43 and host admission regression checks. + +The unchanged AGPL-3.0-or-later fixture comes from OpenCommunityEdition/OpenCE +14ff64cd8, port/linux/network_format.txt. Camera extensions are separately +covered by test_camera_wire.py and test_camera_protocol.py. +""" +from pathlib import Path +import re +import subprocess +from harness import enum_with, function +from test_mcc_identity import compile_tool +import network_format +ROOT = Path(__file__).resolve().parents[1] + + +def test_shared_opence_43_contract(): + lines = (ROOT / "tools/fixtures/opence_network_43.txt").read_text().splitlines() + assert lines[0] == "version 43" + expected = {f"{kind} {name}": value for kind, name, value in + (line.split(" ", 2) for line in lines[1:])} + assert network_format.items() == expected + assert network_format.version() == 43 + + +def test_shared_protocol_preserves_host_admission(tmp_path): + source = (ROOT / "source/networking/network_server_message_handler.c").read_text() + join = function(source, "network_game_server_handle_message_client_join_game_request") + # Execute the real admission handler. Only its external services are fakes; + # Both camera modes must retain tokens, slots, bans and session state. + code = r''' +#include +#include +#include +#pragma clang diagnostic ignored "-Wunused-variable" +#pragma clang diagnostic ignored "-Wunused-parameter" +#pragma clang diagnostic ignored "-Wunused-but-set-variable" +#pragma clang diagnostic ignored "-Wunused-but-set-parameter" +typedef int boolean; +typedef unsigned char byte; +typedef unsigned short word; +#define TRUE 1 +#define FALSE 0 +#define NONE -1 +#define MAXIMUM_MACHINE_NAME_LENGTH 16 +#define JOIN_GAME_TOKEN_LENGTH 16 +#define NETWORK_GAME_MESSAGE_VERSION 1 +#define HALO_PORT_NETWORK_VERSION 43 +#define csmemcmp memcmp +#define csmemcpy memcpy +#define CHECK(x) do {if(!(x)){fprintf(stderr,"line %d: %s\n",__LINE__,#x);return 1;}} while(0) +enum {_network_game_server_state_pregame, _network_game_server_state_ingame}; +enum {_message_client_join_game_request, _network_game_packet_class_client_pregame, + _message_server_machine_accepted, _message_server_machine_rejected, + _network_game_server_rejection_reason_bad_join_token, _rejection_code_game_is_full, + _network_game_server_rejection_reason_game_not_open}; +struct network_game {int machine_count;}; +struct network_game_server {int unused;}; +struct network_game_server_client_machine {int unused;}; +struct network_connection {int unused;}; +struct transport_address {struct {unsigned long long_words[1];} address;}; +#define IPV4_LOOPBACK_ADDRESS 0x7f000001UL +struct network_machine {wchar_t name[16];}; +struct message_client_join_game_request {wchar_t machine_name[16];char hardware_id[32];byte join_game_token[16];byte link_pass[192];byte link_proof[64];word network_version;}; +struct message_server_machine_accepted {short machine_index;long random_seed;}; +struct message_server_machine_rejected {int reason;}; +struct network_message {word header;}; +static struct network_game game; +static struct network_machine machine; +static struct network_message fake_reply; +static int state,late,joined,decode_ok,token_ok,slots,open_game,banned,accepted,name_blocked; +static int camera_locked; +static word join_version; +static int replaceable_bots; +static int bots_population_can_join(struct network_game_server *s) {(void)s;return replaceable_bots;} +static unsigned long peer_address; +static void third_person_session_lock(void) {camera_locked=1;} +static int decode(void *out) { + struct message_client_join_game_request *q=out; + memset(q,0,sizeof(*q));memset(q->join_game_token,token_ok?7:8,16); + q->network_version=join_version;return decode_ok; +} +static int accept(void) {if(banned)return 0;accepted++;return 1;} +#define network_game_server_accepts_late_joins(s) late +#define network_game_server_get_state(s,p) state +#define network_game_server_client_machine_is_joined_to_game(s,m) joined +#define decode_network_game_message(q,...) decode(q) +#define network_game_has_free_player_slot(g) slots +#define network_game_server_get_game(s) (&game) +#define network_game_server_set_machine_hardware_id(m,id) ((void)0) +#define network_game_server_set_machine_link(...) ((void)0) +#define network_game_server_clean_name(...) ((void)0) +#define wide_to_ascii(...) ((void)0) +#define network_connection_get_address(c,a,l) ((a)->address.long_words[0]=peer_address) +#define network_game_server_game_is_open(s) open_game +#define network_game_generate_join_game_token(t) memset(t,7,16) +#define network_game_server_accept_client_machine_into_game(s,m) accept() +#define network_game_server_get_client_machine(s,m,i) (&machine) +#define match_assert(...) ((void)0) +#define network_game_get_random_seed() 0 +#define create_network_game_message(...) (&fake_reply) +#define GET_MESSAGE_SIZE(h) 2 +#define network_game_server_get_client_connection(m) ((struct network_connection *)0) +#define network_game_server_write(...) 1 +#define network_game_server_send_game_settings_to_client_machine(...) 1 +#define network_game_server_send_game_data_pregame(s) 1 +#define network_game_server_last_refusal_code() 0 +#define network_chat_name_blocked(...) name_blocked +#define network_game_server_refuse_with(...) ((void)0) +#define network_event(...) ((void)0) +''' + join + r''' +static void reset(void) { + state=0;late=joined=banned=accepted=name_blocked=0; + camera_locked=replaceable_bots=0;peer_address=2;game.machine_count=1; + decode_ok=token_ok=slots=open_game=1; + join_version=HALO_PORT_NETWORK_VERSION; +} +static int try_join(void) { + word packet[16]={0};struct network_game_server s;struct network_game_server_client_machine m; + return network_game_server_handle_message_client_join_game_request(&s,&m,packet,sizeof(packet)); +} +int main(void) { + int i; + word invalid_versions[]={0,41,42,65,66,67,68,69,70,32712,32713,32714,32716,32717,32718,32720,32721,32722,32724,32725,32726,32728,32729,32730,32732,32733,65535}; + { + for(i=0;i<(int)(sizeof(invalid_versions)/sizeof(invalid_versions[0]));i++) { + reset();join_version=invalid_versions[i]; + CHECK(!try_join() && !accepted && !camera_locked); + } + reset();CHECK(try_join()==1);CHECK(accepted==1);CHECK(camera_locked==accepted); + reset();peer_address=IPV4_LOOPBACK_ADDRESS; + CHECK(try_join()==1);CHECK(!camera_locked); + reset();peer_address=IPV4_LOOPBACK_ADDRESS;game.machine_count=2; + CHECK(try_join()==1);CHECK(camera_locked==accepted); + reset();decode_ok=0;CHECK(!try_join() && !accepted); + reset();token_ok=0;CHECK(!try_join() && !accepted); + reset();slots=0;CHECK(!try_join() && !accepted); + reset();slots=0;replaceable_bots=1; + CHECK(try_join()==1);CHECK(accepted==1); + reset();slots=0;replaceable_bots=1;token_ok=0;CHECK(!try_join() && !accepted); + reset();slots=0;replaceable_bots=1;open_game=0;CHECK(!try_join() && !accepted); + reset();slots=0;replaceable_bots=1;banned=1;CHECK(!try_join() && !accepted); + reset();open_game=0;CHECK(!try_join() && !accepted); + reset();banned=1;CHECK(!try_join() && !accepted); + reset();name_blocked=1;CHECK(!try_join() && !accepted); + reset();state=1;CHECK(!try_join() && !accepted); + reset();state=1;late=1;CHECK(try_join()==1);CHECK(accepted==1); + reset();joined=1;try_join();CHECK(!accepted && !camera_locked); + } + return 0; +} +''' + path = tmp_path / "admission.c" + path.write_text(code) + exe = compile_tool(tmp_path, [path]) + run = subprocess.run([str(exe)], capture_output=True, text=True) + assert run.returncode == 0, run.stdout + run.stderr + + +def test_gameplay_direction_and_mcc_boundary(tmp_path): + source = (ROOT / "port/linux/game/network_distributed.c").read_text() + dispatch = function(source, "network_distributed_handle_message") + family = dispatch[dispatch.index("\tif (header.type >= _distributed_message_mcc_grenades"): + dispatch.index("\t/* a tick's messages in one:")] + direction = dispatch[dispatch.index("\t/* (each kind from the host, or from a client) */"): + dispatch.index("\tif (!distributed_message_epoch_valid")] + kinds = enum_with((ROOT / "port/linux/game/network_distributed.h").read_text(), + "_distributed_message_player_prediction") + code = r''' +#include +#define NONE -1 +enum {_game_connection_local,_game_connection_network_client,_game_connection_network_server}; +static int connection,mcc,applied; +#define HALO_PORT_MAXIMUM_NETWORK_MACHINES 4 +static struct {int heard;} distributed_round_trips[4]; +#define system_milliseconds() 1 +#define game_connection() connection +#define mcc_cache_tags_loaded() mcc +''' + kinds + r''' +static void check(int type,int machine_index) { + struct {int type,game_time;} header; + header.type=type;header.game_time=1; +''' + family + direction + r''' + applied++; +} +int main(void) { + /* Damage, spawns, scores, inventories, world state and MCC state are all + * host-to-client messages. Neither client build may submit them to a host. */ + int types[]={_distributed_message_damage_events,_distributed_message_object_changes, + _distributed_message_player_statistics,_distributed_message_inventories, + _distributed_message_game_state,_distributed_message_mcc_grenades, + _distributed_message_mcc_campaign,_distributed_message_mcc_object_names, + _distributed_message_mcc_game_speed}; + unsigned i; + for(i=0;i=_distributed_message_mcc_grenades) { + mcc=0;check(types[i],NONE);if(applied!=1) return 3; + } + } + applied=0;connection=_game_connection_network_client;check(_distributed_message_player_inputs,NONE); + if(applied) return 4; + connection=_game_connection_network_server;check(_distributed_message_player_inputs,NONE); + if(applied) return 5; + check(_distributed_message_player_inputs,1);if(applied!=1) return 6; + applied=0;mcc=0;connection=_game_connection_network_server; + check(_distributed_message_client_build,1);if(applied!=1)return 7; + connection=_game_connection_network_client; + check(_distributed_message_client_build,NONE);if(applied!=1)return 8; + /* OpenCE fire origins remain client-to-host in both map families. */ + for(mcc=0;mcc<2;mcc++) { + applied=0;connection=_game_connection_network_client; + check(_distributed_message_fire_origins,NONE);if(applied)return 9; + connection=_game_connection_network_server; + check(_distributed_message_fire_origins,NONE);if(applied)return 10; + check(_distributed_message_fire_origins,1);if(applied!=1)return 11; + } + return 0; +} +''' + path = tmp_path / "direction.c" + path.write_text(code) + exe = compile_tool(tmp_path, [path]) + run = subprocess.run([str(exe)], capture_output=True, text=True) + assert run.returncode == 0, run.stdout + run.stderr + + +def test_chat_and_mcc_message_ids_are_disjoint(): + actual = network_format.items() + messages = {key: int(value) for key, value in actual.items() + if key.startswith("enum _distributed_message_")} + assert len(messages.values()) == len(set(messages.values())) + assert messages["enum _distributed_message_aim_assist_policy"] == 90 + assert messages["enum _distributed_message_shield_effects"] == 91 + assert messages["enum _distributed_message_client_build"] == 92 + assert messages["enum _distributed_message_fire_origins"] == 93 + assert messages["enum _distributed_message_map_vote"] == 94 + assert messages["enum _distributed_message_map_vote_choice"] == 95 + header = (ROOT / "port/linux/game/network_distributed.h").read_text() + assert messages["enum _distributed_message_checkpoint"] == 96 + camera = (ROOT / "port/linux/game/third_person_protocol.h").read_text() + camera_join = int(re.search(r"#define THIRD_PERSON_PROTOCOL_JOIN_KIND (\d+)", camera).group(1)) + assert camera_join == 102 and camera_join not in messages.values() + assert header.index("_distributed_message_aim_assist_policy = 90") < header.index("_distributed_message_mcc_grenades = 97") + assert [messages["enum _distributed_message_chat_" + name] + for name in ("up", "down", "config")] == [87, 88, 89] + assert [messages["enum _distributed_message_mcc_" + name] + for name in ("grenades", "campaign", "object_names", "game_speed")] == [97, 98, 99, 100] + # The receive boundary must admit chat in ordinary sessions while rejecting + # MCC data before dispatch; it also applies recursively to batched messages. + receiver = function((ROOT / "port/linux/game/network_distributed.c").read_text(), + "network_distributed_handle_message") + assert "header.type >= _distributed_message_mcc_grenades && !mcc_cache_tags_loaded()" in receiver diff --git a/tools/test_mcc_recordings.py b/tools/test_mcc_recordings.py new file mode 100644 index 0000000000..4a8582d2af --- /dev/null +++ b/tools/test_mcc_recordings.py @@ -0,0 +1,175 @@ +"""Generated recording streams exercise the production MCC-only conversion. + +No map assets are included. Cover both playback codecs, all control versions, +invalid selections after variable-sized events, truncation and tag bounds. +""" +from pathlib import Path +import shutil +import struct +import subprocess +import sys + +import pytest + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.fixture(scope="module") +def recording_tool(tmp_path_factory): + clang = shutil.which("clang") + if not clang: + pytest.skip("clang is needed for MCC recording tests") + work = tmp_path_factory.mktemp("mcc-recordings") + (work / "cseries.h").write_text("#define TRUE 1\n#define FALSE 0\n#define NUMBEROF(a) (sizeof(a)/sizeof((a)[0]))\n") + (work / "errors.h").write_text("#define _error_silent 0\nvoid error(int level, char const *format, ...);\n") + source = work / "runner.c" + source.write_text(r''' +#include +#include +#include +#include "mcc_recordings.h" +#include "mcc_runtime.h" +int mcc_tags_prepare(struct mcc_runtime *r); +void error(int level,char const *format,...) {(void)level;(void)format;} +void *mcc_runtime_pointer(struct mcc_runtime *r,uint32_t address,uint32_t size) { + uint32_t offset=address-r->report.tag_base; + return address>=r->report.tag_base && offset<=r->used && size<=r->used-offset ? r->tags+offset : NULL; +} +static void put(unsigned char *p,uint32_t value) {memcpy(p,&value,4);} +int main(int argc,char **argv) { + unsigned char data[65536];uint32_t size,corrected=0;int ok; + FILE *f;struct mcc_runtime r={0};unsigned char *sc,*rec; + if(argc!=6)return 2; + memset(data,0,sizeof(data));f=fopen(argv[3],"rb");if(!f)return 3; + size=(uint32_t)fread(data+0x700,1,sizeof(data)-0x700,f);fclose(f); + if(!strcmp(argv[5],"weapon-only")) + ok=mcc_recording_weapon_only(data+0x700,size,atoi(argv[1]),atoi(argv[2])); + else if(!strcmp(argv[5],"stream")) + ok=mcc_recording_prepare(data+0x700,size,atoi(argv[1]),atoi(argv[2]),&corrected); + else { + r.tags=r.tag_index=data;r.used=0x700+size;r.report.tag_base=0x50000000;r.report.tag_count=1; + put(data,'scnr');put(data+20,0x50000020);sc=data+0x20;rec=data+0x600; + put(sc+0x36C,1);put(sc+0x370,0x50000600); + rec[0x20]=(unsigned char)atoi(argv[1]);rec[0x22]=(unsigned char)atoi(argv[2]); + put(rec+0x2C,size);put(rec+0x38,0x50000700); + if(!strcmp(argv[5],"bad-block"))put(sc+0x36C,0xFFFFFFFF); + if(!strcmp(argv[5],"bad-pointer"))put(rec+0x38,0xFFFFFFFF); + if(!strcmp(argv[5],"bad-size"))put(rec+0x2C,0xFFFFFFFF); + if(!strcmp(argv[5],"disabled")) {rec[0x20]=0;put(rec+0x2C,0);put(rec+0x38,0);} + ok=mcc_tags_prepare(&r); + } + f=fopen(argv[4],"wb");if(!f)return 4;fwrite(data+0x700,1,size,f);fclose(f); + printf("%d %u\n",ok,(unsigned)corrected);return 0; +} +''') + binary = work / ("recordings.exe" if sys.platform == "win32" else "recordings") + game = ROOT / "port/linux/game" + command = [clang, "-std=gnu89", "-Wall", "-Wextra", "-Werror", "-Wno-multichar", + "-I" + str(work), "-I" + str(game), str(source), str(game / "mcc_recordings.c"), + str(game / "mcc_tags.c"), "-o", str(binary)] + if sys.platform == "win32": + command[1:1] = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld", "-D_CRT_SECURE_NO_WARNINGS"] + result = subprocess.run(command, capture_output=True, text=True) + assert result.returncode == 0, result.stderr + return binary + + +def stream(version=4, control=4, weapon=-256): + data = bytearray(52 + sum(4 if i == 1 else 2 for i in range(1, control)) + (12 if version == 4 else 0)) + struct.pack_into("= 16 else 12 + data += event(version, kind, b"\x7f" * size, time) + data += event(version, 1, time=time) + result, converted = convert(recording_tool, tmp_path, data, version) + assert result == (1, 1) + assert len(converted) == len(data) + assert sum(a != b for a, b in zip(converted, data)) == 2 + assert convert(recording_tool, tmp_path, converted, version) == ((1, 0), converted) + + +@pytest.mark.parametrize("version", [1, 2, 3, 4]) +def test_every_truncation_fails_without_mutation(recording_tool, tmp_path, version): + data = stream(version) + event(version, 5, b"\x00\xff", 3) + event(version, 6, b"\0" * 8) + event(version, 1) + for size in range(len(data)): + assert convert(recording_tool, tmp_path, data[:size], version) == ((0, 0), data[:size]) + + +@pytest.mark.parametrize("version,control,tail", [(0, 4, b"\x04"), (5, 4, b"\x04"), (4, 5, b"\x04"), + (4, 4, b"\xfc"), (1, 4, b"\xff\xff\0\0")]) +def test_unknown_formats_fail_without_mutation(recording_tool, tmp_path, version, control, tail): + data = stream() + tail + assert convert(recording_tool, tmp_path, data, version, control) == ((0, 0), data) + + +@pytest.mark.parametrize("mode", ["tags", "bad-block", "bad-pointer", "bad-size", "disabled"]) +def test_checked_mcc_scenario_integration(recording_tool, tmp_path, mode): + data = stream() + event(4, 1) + result, converted = convert(recording_tool, tmp_path, data, mode=mode) + assert result[0] == (mode in ("tags", "disabled")) + expected = bytearray(data) + if mode == "tags":expected[4:6] = b"\xff\xff" + assert converted == expected diff --git a/tools/test_mcc_resources.py b/tools/test_mcc_resources.py new file mode 100644 index 0000000000..d6a2c4b5fe --- /dev/null +++ b/tools/test_mcc_resources.py @@ -0,0 +1,572 @@ +"""Generated MCC resource files: identity, bounds, missing files and lifetime.""" +from pathlib import Path +import shutil +import struct +import subprocess +import sys +import hashlib +import zlib +import pytest + +ROOT = Path(__file__).resolve().parents[1] +ZLIB = ROOT / "port/third_party/zlib" + + +def identity_fixture(mask, resource_size, seed): + from test_mcc_cache_format import resource_dependency_map, TAG_OFFSET, BASE, fourcc + data = resource_dependency_map("snd!" if mask == 2 else "bitm", int(bool(mask)), 4) + struct.pack_into("\n#define malloc(n) wrong_allocator(n)\n#define free(p) wrong_free(p)\n") + (work / "errors.h").write_text("#define _error_silent 0\nvoid error(short,const char *,...);\n") + source = work / "main.c" + source.write_text(r''' +#include "mcc_runtime.h" +#include "mcc_resources.h" +#include "mcc_identity.h" +#include "mcc_package.h" +#include +#include +#include +void error(short level,const char *format,...) {(void)level;(void)format;} +static int fail_read; +static int read_map(void *context,uint32_t offset,uint32_t size,void *out) { + return !fail_read && !fseek(context,(long)offset,SEEK_SET) && fread(out,1,size,context)==size; +} +int main(int argc,char **argv) { + struct mcc_runtime runtime={0};unsigned char bytes[32]={0};int ok; + if(argc==4 && !strcmp(argv[1],"explain")) { + struct mcc_cache_source source;uint32_t sum=0;char reason[320]; + FILE *f=fopen(argv[2],"rb");if(!f)return 8; + fseek(f,0,SEEK_END);source.size=(uint64_t)ftell(f);source.context=f;source.read=read_map; + strcpy(reason,"stale failure"); + ok=mcc_resources_probe_explain("mcc_maps/package/a10",&source,&sum,reason,sizeof(reason));fclose(f); + printf("%s",reason); + return ok==atoi(argv[3]) ? 0 : 9; + } + if(argc==4 && (!strcmp(argv[1],"incremental") || !strcmp(argv[1],"incremental_crc") || + !strcmp(argv[1],"incremental_failure"))) { + struct mcc_cache_source source;struct mcc_resource_check *check; + uint32_t sum=0x12345678,expected;unsigned i,steps=0;char reason[320]; + FILE *f=fopen(argv[2],"rb");if(!f)return 8; + fseek(f,0,SEEK_END);source.size=(uint64_t)ftell(f);source.context=f;source.read=read_map; + check=mcc_resources_check_begin(argv[3],&source,reason,sizeof(reason)); + if(!check){fprintf(stderr,"%s",reason);return 10;} + /* Cancelling a partial check releases only its own resources. */ + memset(bytes,0xA5,sizeof(bytes)); + ok=mcc_resources_check_step(check,&sum,bytes); + if(!ok) { + if(sum!=0x12345678)return 13; + for(i=0;i8)return 2; + if(!mcc_package_name(argc>=7 ? argv[6] : "mcc_maps/test",runtime.level_name))return 5; + ok=mcc_resources_read(&runtime,(unsigned)atoi(argv[1]),argv[2],(uint32_t)strtoul(argv[3],NULL,0), + (uint32_t)atoi(argv[4]),bytes,argc==8 ? argv[7] : NULL); + if(ok)fwrite(bytes,1,(size_t)atoi(argv[4]),stdout); + mcc_resources_dispose(&runtime);mcc_resources_dispose(&runtime); + if(runtime.resources)return 3; + return ok==atoi(argv[5]) ? 0 : 4; +} +''') + exe = work / "resources.exe" + target = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld"] if sys.platform == "win32" else [] + # Select the production browser reader without substituting browser + # filesystem services into these native, asset-free fixtures. + reader = work / "resources.o" + compile_target = ["--target=i686-pc-windows-msvc"] if sys.platform == "win32" else [] + web = ["-DHALO_WEB"] if request.param == "web-reader" else [] + result = subprocess.run([clang] + compile_target + web + ["-std=gnu89", "-Wall", "-Wextra", "-Werror", + "-D_CRT_SECURE_NO_WARNINGS", "-DZ_PREFIX", "-I"+str(ZLIB), "-I"+str(ROOT / "port/linux/game"), + "-I"+str(work), "-c", str(ROOT / "port/linux/game/mcc_resources.c"), "-o", str(reader)], + capture_output=True, text=True) + assert result.returncode == 0, result.stderr + # Match the game's GNU89 mode, including libc's snprintf declaration on Linux. + result = subprocess.run([clang] + target + [str(ROOT / "tools/mcc_loading_stub.c"), "-std=gnu89", "-Wall", "-Wextra", "-Werror", "-D_CRT_SECURE_NO_WARNINGS", "-DZ_PREFIX", "-I"+str(ZLIB), "-I"+str(ROOT / "port/linux/game"), + "-I"+str(work), str(source), str(ROOT / "port/linux/game/mcc_package.c"), str(reader), str(ROOT / "port/linux/game/mcc_errors.c"), str(ROOT / "port/linux/game/mcc_sha256.c"), str(ROOT / "port/linux/game/mcc_cache_format.c"), str(ZLIB / "crc32.c"), "-o", str(exe)], capture_output=True, text=True) + assert result.returncode == 0, result.stderr + return exe + + +def fixture_blob(kind=2, reverse=False): + names = b"sound\\test__0__0\0second\0" + entries = [(17, 4, 20), (0, 4, 16)] + if reverse: + entries.reverse() + return bytearray(struct.pack("<4I", kind, 24, 24+len(names), 2) + b"abcdefgh" + names + + b"".join(struct.pack("<3I", *entry) for entry in entries)) + +@pytest.mark.parametrize("reverse", [False, True], ids=["descending-offsets", "ascending-offsets"]) +@pytest.mark.parametrize("case", ["valid", "bitmap", "prefix", "wrong_name", "wrong_type", "truncated", + "metadata_overlap", "past_end", "names_outside", "unterminated", "large_count", "inner_offset", + "too_long", "missing", "ce_only", "wrap_offset", "relocated", "relocated_prefix", "ambiguous", + "equal_offsets", "duplicate_equal_offsets"]) +def test_resource_reader(resource_tool, tmp_path, case, reverse): + folder = tmp_path / ("custom_maps" if case == "ce_only" else "mcc_maps") + folder.mkdir() + kind = 1 if case == "bitmap" else 2 + blob = fixture_blob(kind, reverse) + expected = case in {"valid", "bitmap", "prefix", "inner_offset", "relocated", "equal_offsets"} + offset, length, name = 16, 4, r"sound\test__0__0" + index = struct.unpack_from(" +#include +#include +#include +typedef unsigned char boolean; +typedef unsigned short word; +#define TRUE 1 +#define FALSE 0 +#define NONE (-1) +#define NUMBER_OF_GAME_DIFFICULTY_LEVELS 4 +#define MAXIMUM_ROWS 11 +#define MAXIMUM_PROFILES 32 +#define MAXIMUM_PLAYER_PROFILE_NAME_LENGTH 11 +#define PROFILE_VALID_BIT 0x80000000UL +#define PIN(v,a,b) ((v)<(a)?(a):((v)>(b)?(b):(v))) +struct player_profile {wchar_t player_name[12];}; +''' + structure(menu, "campaign_saved_game") + r''' +static struct { + short saved_game_count,shown_saved_game; + struct campaign_saved_game saved_games[MAXIMUM_ROWS]; +} campaign; +static char mcc_saved_game_names[MAXIMUM_ROWS][256]; +static long active=PROFILE_VALID_BIT; +static char saves[3][256]; +static short difficulty=2; +static int storage_valid=1,required=0,available=1,stock_calls=0,starts=0; +static char started[256]; +long player_ui_get_active_player_profile_index(short player) {(void)player;return active;} +boolean game_state_test_persistent_storage(char *name,short *out,boolean *corrupt) { + strcpy(name,saves[active&255]);*out=difficulty;*corrupt=0;return storage_valid; +} +boolean mcc_level_name(char const *name) {return !strncmp(name,"mcc_maps\\",9);} +boolean mcc_cache_require(char const *name,unsigned long checksum) { + (void)checksum;if(!mcc_level_name(name))exit(10);required++;return available; +} +boolean campaign_profile(short controller,struct player_profile *profile) { + (void)controller;wcscpy(profile->player_name,L"player");return active!=NONE; +} +boolean campaign_fail(void) {return FALSE;} +void campaign_start(char const *name,short level,short controller) { + (void)level;(void)controller;strcpy(started,name);starts++; +} +boolean ui_widget_port_saved_game(char const **name,short *level,short *out) { + stock_calls++;*name=saves[active&255];*level=0;*out=difficulty; + return storage_valid && !strncmp(*name,"levels\\",7); +} +void player_profiles_enumerate_available_to_local_player_index(long player,word *count,long *profiles,boolean unused) { + int i;(void)player;(void)unused;*count=3; + for(i=0;i<3;i++)profiles[i]=PROFILE_VALID_BIT+i; +} +boolean player_profile_get(long index,struct player_profile *profile) { + if((index&255)>2)return FALSE;wcscpy(profile->player_name,L"player");return TRUE; +} +void player_ui_set_active_player_profile(short player,long index,struct player_profile const *profile) { + (void)player;(void)profile;active=index; +} +void ustrncpy(wchar_t *out,wchar_t const *in,long count) {wcsncpy(out,in,(size_t)count);} +void campaign_levels_read(struct player_profile const *profile) {(void)profile;} +char const *main_get_solo_level_name(short level) {if(level!=0)exit(11);return "levels\\a10\\a10";} +''' + functions + r''' +int main(int argc,char **argv) { + int result=0; + if(argc<2)return 2; + strcpy(saves[0],"levels\\a10\\a10"); + strcpy(saves[1],"mcc_maps\\a10"); + strcpy(saves[2],"custom_maps\\a10"); + if(!strcmp(argv[1],"continue")) { + if(argc<3)return 2; + strcpy(saves[0],argv[2]); + if(argc>3)available=atoi(argv[3]); + result=campaign_continue(0); + } else if(!strcmp(argv[1],"list")) { + saved_games_read(0); + if(campaign.saved_game_count!=2 || mcc_saved_game_names[0][0] || + strcmp(mcc_saved_game_names[1],"mcc_maps\\a10") || (unsigned long)active!=PROFILE_VALID_BIT)return 12; + if(argc>2) { + campaign.shown_saved_game=(short)atoi(argv[2]); + result=saved_game_continue(0); + } else result=1; + } else if(!strcmp(argv[1],"read")) { + char name[256];short out=0; + if(argc<3)return 2; + strcpy(saves[0],argv[2]); + if(argc>3)difficulty=(short)atoi(argv[3]); + result=mcc_saved_game_read(name,&out); + if(!result && name[0])return 13; + printf("difficulty=%d\n",out); + } else return 2; + printf("result=%d\nstarts=%d\nstarted=%s\nrequired=%d\nstock_calls=%d\ncount=%d\n", + result,starts,started,required,stock_calls,campaign.saved_game_count); + return 0; +} +''' + path = work / "saved_games.c" + path.write_text(source) + output = work / ("saved_games.exe" if sys.platform == "win32" else "saved_games") + command = [compiler, "-std=c99", "-Wall", "-Wextra", "-Werror", str(path), "-o", str(output)] + if sys.platform == "win32": + command[1:1] = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld", "-D_CRT_SECURE_NO_WARNINGS"] + result = subprocess.run(command, capture_output=True, text=True) + assert result.returncode == 0, result.stderr + return output + + +def run(tool, *args): + result = subprocess.run([str(tool), *map(str, args)], capture_output=True, text=True) + assert result.returncode == 0, result.stdout + result.stderr + return dict(line.split("=", 1) for line in result.stdout.splitlines()) + + +@pytest.mark.parametrize("name,starts,required,stock_calls", [ + ("mcc_maps\\a10", 1, 1, 0), + ("levels\\a10\\a10", 1, 0, 1), + ("custom_maps\\a10", 0, 0, 1), +]) +def test_continue_routes_only_mcc_to_new_loader(saved_game_tool, name, starts, required, stock_calls): + fields = run(saved_game_tool, "continue", name) + assert fields["starts"] == str(starts) + assert fields["required"] == str(required) + assert fields["stock_calls"] == str(stock_calls) + if starts: + assert fields["started"] == name + + +def test_missing_mcc_checkpoint_map_does_not_start(saved_game_tool): + fields = run(saved_game_tool, "continue", "mcc_maps\\missing", 0) + assert fields["result"] == fields["starts"] == "0" + + +def test_save_list_keeps_stock_and_mcc_identities_separate(saved_game_tool): + fields = run(saved_game_tool, "list") + assert fields["count"] == "2" + + +@pytest.mark.parametrize("row,expected,required", [(0, "levels\\a10\\a10", 0), (1, "mcc_maps\\a10", 1)]) +def test_saved_game_selection_uses_its_own_namespace(saved_game_tool, row, expected, required): + fields = run(saved_game_tool, "list", row) + assert fields["result"] == "1" + assert fields["started"] == expected + assert fields["required"] == str(required) + + +@pytest.mark.parametrize("difficulty,expected", [(-8, 0), (8, 3)]) +def test_mcc_saved_difficulty_is_bounded(saved_game_tool, difficulty, expected): + fields = run(saved_game_tool, "read", "mcc_maps\\a10", difficulty) + assert fields["result"] == "1" + assert fields["difficulty"] == str(expected) diff --git a/tools/test_mcc_scripts.py b/tools/test_mcc_scripts.py new file mode 100644 index 0000000000..a17a4bc89e --- /dev/null +++ b/tools/test_mcc_scripts.py @@ -0,0 +1,153 @@ +"""Check independent MCC script relocation and native extension behavior.""" +from pathlib import Path +import shutil +import subprocess +import sys + +import pytest + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.fixture(scope="module") +def native_mcc_harness(tmp_path_factory): + compiler = shutil.which("clang") + if not compiler or sys.platform != "win32": + pytest.skip("the script harness currently uses native x86 Windows game headers") + directory = tmp_path_factory.mktemp("mcc-script-behavior") + includes = ["port/windows/include/crt", "port/windows/include", "source", "source/cseries", + "source/math", "source/tag_files", "source/rasterizer", "source/structures", + "source/cache", "source/render", "port/include/xdk", "port/linux/game"] + command = [compiler, "--target=i686-pc-windows-msvc", "-fuse-ld=lld", "-fms-extensions", + "-std=gnu89", "-O1", "-DDEBUG", "-Dxbox", "-D_CRT_SECURE_NO_WARNINGS", + "-Wno-nonportable-include-path", "-Wno-c99-compat", "-Wno-visibility", + "-include", str(ROOT / "port/windows/include/halo_windows_prefix.h"), + "-iquote", str(ROOT / "port/linux/include")] + command += ["-I" + str(ROOT / path) for path in includes] + def build(name): + binary = directory / (name + ".exe") + extra = [str(ROOT / "port/linux/game/mcc_syntax.c")] if name == "mcc_scripts" else [] + if name == "mcc_campaign": + extra.append(str(ROOT / "port/linux/game/mcc_script_effects.c")) + if name == "mcc_recording_control": + extra.append(str(ROOT / "port/linux/game/mcc_recordings.c")) + result = subprocess.run(command + [str(ROOT / "tools/harness/tests" / (name + ".c")), + str(ROOT / "port/linux/game" / (name + ".c"))] + extra + ["-o", str(binary)], + capture_output=True, text=True) + assert result.returncode == 0, result.stderr + return binary + return build + + +@pytest.fixture(scope="module") +def scripts_tool(native_mcc_harness): + return native_mcc_harness("mcc_scripts") + + +@pytest.mark.parametrize("case", ["issue89_link_abs_integer", "issue89_link_get_executing_running_thread", "issue89_link_kill_thread", "issue89_registry", "link", "alias", "extension", "equipment", "segment", "core_segment", "global", "unknown", "speed", "score", "score_write", "score_capacity", "score_allocation", + "bad_child", "child_salt", "short_data", "capacity", "full_capacity", + "negative_count", "unterminated", "skull_read", "skull_wrong_type", "skull_write", "developer_read", "developer_cast", "developer_write", "skull_disable", "skull_enable", "skull_computed", "developer_capacity", "developer_allocation"]) +def test_mcc_script_linking(scripts_tool, case): + result = subprocess.run([str(scripts_tool), case], capture_output=True, text=True, timeout=10) + assert result.returncode == 0, result.stdout + result.stderr + + +@pytest.mark.parametrize("name,index", [ + ("objects_distance_to_object", 0x7000), ("mcc_mission_segment", 0x7001), + ("core_save_name", 0x7002), ("player_add_equipment", 0x7003), + ("abs_integer", 0x7004), ("get_executing_running_thread", 0x7005), + ("kill_thread", 0x7006), ("ai_deselect", 0x7007), ("player_effect_set_max_vibrate", 322), + ("physics_set_gravity", 0x7010), ("sleep", -1), ("unknown_script_name", -1), +]) +@pytest.mark.parametrize("spelling", [str.lower, str.upper, str.title], ids=["lower", "upper", "mixed"]) +def test_mcc_preparation_and_runtime_resolution(scripts_tool, name, index, spelling): + result = subprocess.run([str(scripts_tool), "resolver", spelling(name), str(index)], + capture_output=True, text=True, timeout=10) + assert result.returncode == 0, result.stdout + result.stderr + + +@pytest.mark.parametrize("name", ["player_effect_set_max_vibrate", "PLAYER_EFFECT_SET_MAX_VIBRATE", + "Player_Effect_Set_Max_Vibrate"]) +def test_mcc_missing_alias_target_does_not_use_native_alias(scripts_tool, name): + result = subprocess.run([str(scripts_tool), "resolver_missing_alias", name, "-1"], + capture_output=True, text=True, timeout=10) + assert result.returncode == 0, result.stdout + result.stderr + + +def test_mcc_ai_deselect_admission_and_completion(scripts_tool): + result = subprocess.run([str(scripts_tool), "ai_deselect"], capture_output=True, text=True, timeout=10) + assert result.returncode == 0, result.stdout + result.stderr + + +def test_mcc_authoritative_game_speed(native_mcc_harness): + result = subprocess.run([str(native_mcc_harness("mcc_game_speed"))], capture_output=True, text=True, timeout=10) + assert result.returncode == 0, result.stdout + result.stderr + + +def test_mcc_weapon_only_recording_directions(native_mcc_harness): + result = subprocess.run([str(native_mcc_harness("mcc_recording_control"))], + capture_output=True, text=True, timeout=10) + assert result.returncode == 0, result.stdout + result.stderr + + +def test_mcc_environment_shader_draw_isolation(native_mcc_harness): + result = subprocess.run([str(native_mcc_harness("mcc_environment_shader"))], capture_output=True, text=True, timeout=10) + assert result.returncode == 0, result.stdout + result.stderr + + +@pytest.mark.parametrize("skull", ["sputnik", "catch", "boom"]) +@pytest.mark.parametrize("case", ["skull_read", "skull_wrong_type", "skull_disable", "skull_enable", "skull_computed"]) +def test_additional_disabled_skulls(scripts_tool, skull, case): + result = subprocess.run([str(scripts_tool), case, "debug_ice_cream_flavor_status_"+skull], + capture_output=True, text=True, timeout=10) + assert result.returncode == 0, result.stdout + result.stderr + + +@pytest.mark.parametrize("case", ["prediction_enable", "prediction_disable", "prediction_computed"]) +def test_prediction_policy(scripts_tool, case): + result = subprocess.run([str(scripts_tool), case], capture_output=True, text=True, timeout=10) + assert result.returncode == 0, result.stdout + result.stderr + + +@pytest.mark.parametrize("kind", ["real", "long", "boolean"]) +def test_disabled_skull_result_matches_native_constant_type(scripts_tool, kind): + result = subprocess.run([str(scripts_tool), "skull_disable", "debug_ice_cream_flavor_status_sputnik", kind], + capture_output=True, text=True, timeout=10) + assert result.returncode == 0, result.stdout + result.stderr + + +def test_mcc_vehicle_masks_and_legacy_isolation(native_mcc_harness): + result = subprocess.run([str(native_mcc_harness("mcc_objects"))], capture_output=True, + text=True, timeout=10) + assert result.returncode == 0, result.stdout + result.stderr + + +def test_mcc_player_input_and_profile_slots(native_mcc_harness): + result = subprocess.run([str(native_mcc_harness("mcc_player"))], capture_output=True, + text=True, timeout=10) + assert result.returncode == 0, result.stdout + result.stderr + + +def test_mcc_weapon_movement(native_mcc_harness): + result = subprocess.run([str(native_mcc_harness("mcc_movement"))], capture_output=True, + text=True, timeout=10) + assert result.returncode == 0, result.stdout + result.stderr + + +@pytest.mark.parametrize("counter", "012345") +def test_mcc_scratch_globals_are_map_local(scripts_tool, counter): + result = subprocess.run([str(scripts_tool), "scratch", counter], capture_output=True, text=True, timeout=10) + assert result.returncode == 0, result.stdout + result.stderr + + +@pytest.mark.parametrize("case", ["prediction_enable", "prediction_disable", "prediction_computed"]) +def test_breadcrumb_availability_override(scripts_tool, case): + result = subprocess.run([str(scripts_tool), case, "breadcrumbs_navpoints_enabled_override"], + capture_output=True, text=True, timeout=10) + assert result.returncode == 0, result.stdout + result.stderr + + +def test_mcc_sound_streams_and_cleanup(native_mcc_harness): + result = subprocess.run([str(native_mcc_harness("mcc_audio"))], + capture_output=True, text=True, timeout=10) + assert result.returncode == 0, result.stdout + result.stderr diff --git a/tools/test_mcc_seats.py b/tools/test_mcc_seats.py new file mode 100644 index 0000000000..7af6eab095 --- /dev/null +++ b/tools/test_mcc_seats.py @@ -0,0 +1,159 @@ +"""Execute the real MCC interaction and shared seat receiver against fake objects.""" +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest +from harness import function + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.fixture(scope="module") +def seats(tmp_path_factory): + clang = shutil.which("clang") + if not clang: + pytest.skip("clang required") + folder = tmp_path_factory.mktemp("mcc-seats") + adapter = (ROOT / "port/linux/game/mcc_seats.c").read_text() + network = (ROOT / "port/linux/game/network_objects.c").read_text() + source = r''' +#include +#include +#include +typedef int boolean; +#define TRUE 1 +#define FALSE 0 +#define NONE -1 +#define NULL ((void *)0) +#define TEST_FLAG(v,b) (((v)&(1UL<<(b)))!=0) +enum {_object_dead_bit=0,_unit_control_action_bit=1,_object_mask_biped=1,_object_mask_vehicle=2, + _object_mask_unit=3,_game_connection_network_client=2,_unit_nearby_seat_available=2}; +struct object_data {long parent_object_index;unsigned long damage_flags;int type;}; +struct object_datum {long definition_index;struct object_data object;}; +struct unit_datum {long definition_index;struct object_data object;struct {short parent_seat_index;long player_index;unsigned long control_flags;} unit;}; +struct unit_camera {int unused;}; +struct unit_seat {struct unit_camera camera;}; +static struct unit_seat seats[16]; +#define TAG_BLOCK_GET_ELEMENT(b,i,t) (&seats[i]) +struct player_control_unit_camera_info {long unit_index;short seat_index;struct unit_camera *camera;}; +struct unit_definition {struct {struct {int count;} seats;} unit;}; +struct player_datum {long unit_index;}; +struct object_header_datum {struct object_datum *datum;}; +static struct unit_datum units[20]; +static struct unit_definition definitions[20]; +static struct object_header_datum headers[20]; +static struct player_datum player={0}; +static int active=1,reads,connection,overcharged,nearby=2,boarded,exited,animation=1; +static long occupant=NONE; +static int exists[20],known[20]; +static void *object_header_data; +static boolean mcc_cache_tags_loaded(void){return active;} +static struct object_datum *object_try_and_get(long i){++reads;return i>=0&&i<20&&exists[i]?(struct object_datum *)&units[i]:NULL;} +static struct object_datum *object_try_and_get_and_verify_type(long i,int mask){ + struct object_datum *o=object_try_and_get(i);return o&&(o->object.type&mask)?o:NULL; +} +static struct unit_definition *unit_definition_get(long i){return &definitions[i];} +static struct player_datum *player_try_and_get(long i){return i==0?&player:NULL;} +static struct player_datum *player_get(long i){return player_try_and_get(i);} +static int unit_overcharged(long i){(void)i;return overcharged;} +static short unit_find_nearby_seat(long u,long p,short *s){(void)u;(void)p;*s=0;return nearby;} +static int game_connection(void){return connection;} +static int unit_enter_seat(long u,long p,short s){++boarded;units[u].object.parent_object_index=p;units[u].unit.parent_seat_index=s;return 1;} +static void unit_exit_seat_end(long u){++exited;units[u].object.parent_object_index=NONE;units[u].unit.parent_seat_index=NONE;} +static int unit_try_and_exit_seat(long u){unit_exit_seat_end(u);return 1;} +static int distributed_object_index_valid(long i){return i>=0&&i<20&&exists[i];} +static int network_objects_client_has(long i){return i>=0&&i<20&&known[i];} +static int unit_has_animation_to_enter_seat(long u,long p,short s){(void)u;return animation&&s>=0&&s=0&&i<20&&exists[i]?&headers[i]:NULL;} +static int unit_can_enter_seat(long u,long p,short s,long *out){(void)u;(void)p;(void)s;*out=occupant;return occupant==NONE;} +''' + '\n'.join(function(adapter, n) for n in ("mcc_seat_parent", "mcc_seat_controller", "mcc_seat_nearby", "mcc_seat_action", "mcc_seat_update", "mcc_seat_camera")) + '\n' + function(network, "network_objects_set_seat") + r''' +#define CHECK(v) do{if(!(v)){fprintf(stderr,"line %d\n",__LINE__);return 1;}}while(0) +int main(int argc,char **argv){ + int i;short s; + if(argc!=2)return 2; + for(i=0;i<20;++i){exists[i]=known[i]=1;units[i].definition_index=i; + units[i].object.type=1;units[i].object.parent_object_index=NONE; + units[i].unit.parent_seat_index=NONE;units[i].unit.player_index=NONE;headers[i].datum=(struct object_datum *)&units[i];} + definitions[1].unit.seats.count=1; + if(!strcmp(argv[1],"controller")){ + CHECK(mcc_seat_controller(1)==NONE); + units[1].unit.player_index=0;CHECK(mcc_seat_controller(1)==1); + active=0;reads=0;CHECK(mcc_seat_controller(1)==NONE&&reads==0); + active=1;units[1].object.type=2;CHECK(mcc_seat_controller(1)==NONE); + }else if(!strcmp(argv[1],"isolation")){ + active=0;CHECK(!mcc_seat_nearby(0,1,&s));CHECK(reads==0); + CHECK(!mcc_seat_action(0,1,0));network_objects_set_seat(0,1,0);CHECK(!boarded); + units[1].object.type=2;network_objects_set_seat(0,1,0);CHECK(boarded==1); + }else if(!strcmp(argv[1],"interaction")){ + CHECK(mcc_seat_nearby(0,1,&s)&&s==0);CHECK(mcc_seat_action(0,1,0));CHECK(boarded==1); + CHECK(!mcc_seat_nearby(0,1,&s));unit_exit_seat_end(0);CHECK(mcc_seat_nearby(0,1,&s)); + }else if(!strcmp(argv[1],"authority")){ + connection=2;CHECK(mcc_seat_nearby(0,1,&s));CHECK(mcc_seat_action(0,1,0));CHECK(!boarded); + connection=1;nearby=0;CHECK(mcc_seat_action(0,1,0));CHECK(!boarded); + nearby=2;CHECK(mcc_seat_action(0,1,1));CHECK(!boarded); + CHECK(mcc_seat_action(0,1,0));CHECK(boarded==1); + }else if(!strcmp(argv[1],"dead")){ + units[0].object.damage_flags=1;CHECK(!mcc_seat_nearby(0,1,&s)); + units[0].object.damage_flags=0;units[1].object.damage_flags=1;CHECK(!mcc_seat_nearby(0,1,&s)); + network_objects_set_seat(0,1,0);CHECK(!boarded); + units[1].object.damage_flags=0;overcharged=1;CHECK(!mcc_seat_nearby(0,1,&s)); + }else if(!strcmp(argv[1],"invalid")){ + CHECK(!mcc_seat_nearby(0,NONE,&s));CHECK(!mcc_seat_nearby(1,1,&s)); + CHECK(!mcc_seat_nearby(0,0,&s));definitions[1].unit.seats.count=17; + CHECK(!mcc_seat_nearby(0,1,&s));definitions[1].unit.seats.count=0;CHECK(!mcc_seat_nearby(0,1,&s)); + }else if(!strcmp(argv[1],"cycles")){ + units[1].object.parent_object_index=0;CHECK(!mcc_seat_nearby(0,1,&s)); + network_objects_set_seat(0,1,0);CHECK(!boarded); + units[1].object.parent_object_index=1;CHECK(!mcc_seat_nearby(0,1,&s)); + network_objects_set_seat(0,1,0);CHECK(!boarded); + units[1].object.parent_object_index=19;exists[19]=0;CHECK(!mcc_seat_nearby(0,1,&s)); + network_objects_set_seat(0,1,0);CHECK(!boarded); + }else if(!strcmp(argv[1],"replication")){ + connection=2;network_objects_set_seat(0,1,0);CHECK(boarded==1); + CHECK(units[0].object.parent_object_index==1);network_objects_set_seat(0,NONE,NONE); + CHECK(exited==1&&units[0].object.parent_object_index==NONE); + occupant=2;network_objects_set_seat(0,1,0);CHECK(boarded==2&&exited==2); + }else if(!strcmp(argv[1],"seat_update")){ + units[0].object.parent_object_index=1; + CHECK(!mcc_seat_update(0)); /* Ordinary infection attachment has no seat. */ + units[0].unit.parent_seat_index=0;active=0;CHECK(!mcc_seat_update(0)); + active=1;CHECK(mcc_seat_update(0)&&!exited); + units[0].unit.control_flags=2;connection=2;CHECK(mcc_seat_update(0)&&!exited); + connection=1;CHECK(mcc_seat_update(0)&&exited==1); + units[0].object.parent_object_index=1;units[0].unit.parent_seat_index=0; + units[1].object.damage_flags=1;CHECK(mcc_seat_update(0)&&exited==2); + }else if(!strcmp(argv[1],"camera")){ + struct player_control_unit_camera_info info={0,NONE,NULL}; + mcc_seat_camera(&info);CHECK(info.unit_index==0&&info.camera==NULL); + units[0].object.parent_object_index=1;units[0].unit.parent_seat_index=0; + active=0;mcc_seat_camera(&info);CHECK(info.camera==NULL); + active=1;mcc_seat_camera(&info);CHECK(info.unit_index==1&&info.seat_index==0&&info.camera==&seats[0].camera); + info.unit_index=0;info.seat_index=NONE;info.camera=NULL;units[0].unit.parent_seat_index=1; + mcc_seat_camera(&info);CHECK(info.camera==NULL); + }else if(!strcmp(argv[1],"network_bounds")){ + for(i=-2;i<20;++i)if(i!=0){network_objects_set_seat(0,1,(short)i);CHECK(!boarded);} + known[1]=0;network_objects_set_seat(0,1,0);CHECK(!boarded); + known[1]=1;animation=0;network_objects_set_seat(0,1,0);CHECK(!boarded); + animation=1;exists[1]=0;network_objects_set_seat(0,1,0);CHECK(!boarded); + network_objects_set_seat(0,0,0);CHECK(!boarded); + }else return 3; + return 0; +} +''' + path = folder / "seats.c" + path.write_text(source) + exe = folder / ("seats.exe" if sys.platform == "win32" else "seats") + args = [clang, "-std=gnu89", str(path), "-o", str(exe)] + if sys.platform == "win32": + args[1:1] = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld"] + result = subprocess.run(args, capture_output=True, text=True) + assert result.returncode == 0, result.stderr + return exe + + +@pytest.mark.parametrize("case", ["controller", "isolation", "interaction", "authority", "dead", "invalid", "cycles", "replication", "seat_update", "camera", "network_bounds"]) +def test_mcc_seats(seats, case): + result = subprocess.run([str(seats), case], capture_output=True, text=True) + assert result.returncode == 0, result.stderr diff --git a/tools/test_mcc_shader_channels.py b/tools/test_mcc_shader_channels.py new file mode 100644 index 0000000000..405228b551 --- /dev/null +++ b/tools/test_mcc_shader_channels.py @@ -0,0 +1,158 @@ +"""MCC model and meter flags select channels per consumer of shared bitmaps.""" +from pathlib import Path +import shutil +import subprocess +import sys + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from harness import function, structure + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.fixture(scope="module") +def model_masks(tmp_path_factory): + clang = shutil.which("clang") + if not clang: + pytest.skip("clang is needed for MCC shader channel tests") + bitmap = (ROOT / "port/linux/game/mcc_bitmaps.c").read_text() + header = (ROOT / "source/bitmaps/bitmap_group.h").read_text() + declarations = "\n".join(structure(header, name) for name in [ + "bitmap_data", "bitmap_group_sprite", "bitmap_group_sequence", "bitmap_group"]) + declarations += "\n" + "\n".join(structure(bitmap, name) for name in [ + "mcc_texture", "mcc_bitmap_clone", "mcc_textures"]) + routines = "\n".join(function(bitmap, name) for name in [ + "mcc_bitmap_tag", "mcc_bitmap_block", "mcc_bitmap_mark_one", "mcc_bitmap_clone_block", + "mcc_bitmap_specialize", "mcc_bitmap_mark", "mcc_meter_usage", "mcc_bitmap_model_usage", + "mcc_bitmap_bytes", "mcc_pixel", "mcc_channels", "mcc_bitmap_decode"]) + source = r''' +#include +#include +#include +#include +typedef float real; +union point2d {struct {short x,y;};uint32_t n;}; +typedef struct {float x0,x1,y0,y1;} real_rectangle2d; +typedef struct {float x,y;} real_point2d; +struct tag_block {long count;void *address,*definition;}; +struct tag_data {long size,flags,file_offset;void *address,*definition;}; +struct meter_hud_element_definition {struct {uint32_t index;} meter_bitmap;short sequence_index;unsigned char meter_flags;float opacity,fade;}; +#define BITMAP_GROUP_TAG 'bitm' +#define NONE -1 +static uint32_t global_vector_palette[256]; +struct mcc_runtime {unsigned char *tags,*tag_index;uint32_t used;struct {uint32_t tag_count;} report;}; +static void *mcc_runtime_pointer(struct mcc_runtime *r,uint32_t p,uint32_t size) { + uintptr_t start=(uintptr_t)r->tags; + return p>=start && p-start<=r->used && size<=r->used-(p-start) ? (void *)(uintptr_t)p : NULL; +} +static void *mcc_runtime_allocate(struct mcc_runtime *r,uint32_t size) { + uint32_t at=(r->used+15)&~15u; + if(size>65536-at)return NULL; + r->used=at+size;return r->tags+at; +} +#define BCDEC_STATIC +#define BCDEC_IMPLEMENTATION +#include "bcdec.h" +''' + declarations + "\n" + routines + r''' +static void shader_init(unsigned char *shader,uint16_t flags,uint32_t handle) { + static unsigned const offsets[]={0xB0,0xC8,0xE8,0x170};unsigned i; + memset(shader,0,0x174);memcpy(shader+0x28,&flags,sizeof(flags)); + for(i=0;i<4;i++)memcpy(shader+offsets[i],&handle,sizeof(handle)); +} +int main(int argc,char **argv) { + struct mcc_runtime runtime={0};struct mcc_textures textures={0}; + struct bitmap_group *original;struct bitmap_data *descriptor,original_descriptor; + unsigned char xbox[0x174],gearbox[0x174],repeated[0x174],missing[0x174]; + uint32_t *entry,source=0xE1740000,cloned,decoded[16];unsigned i; + /* A red-only opaque BC1 block: specular reflection, with no color + * change. Misreading alpha as change color instead tints all texels. */ + unsigned char dxt1[8]={0,0xF8,0,0,0,0,0,0}; + unsigned char rgba[4]={10,20,30,40}; + struct meter_hud_element_definition xbox_meter={{source},NONE,0x3F,1.0f,0.75f},gearbox_meter={{source},NONE,0x1F,1.0f,0.5f}; + int reverse; + if(argc!=2)return 1;reverse=atoi(argv[1]); + runtime.tags=calloc(1,65536);runtime.tag_index=runtime.tags;runtime.used=512; + runtime.report.tag_count=1; + original=mcc_runtime_allocate(&runtime,sizeof(*original)); + descriptor=mcc_runtime_allocate(&runtime,sizeof(*descriptor)); + original->bitmaps.count=1;original->bitmaps.address=descriptor; + descriptor->width=descriptor->height=4;descriptor->depth=1; + descriptor->format=14;descriptor->pixels_offset=2048;descriptor->pixels_size=8; + original_descriptor=*descriptor; + entry=(uint32_t *)runtime.tag_index;entry[0]='bitm';entry[3]=source;entry[5]=(uint32_t)original; + textures.capacity=8;textures.tag_capacity=8;textures.count=1; + textures.items=calloc(8,sizeof(*textures.items));textures.clones=calloc(8,sizeof(*textures.clones)); + textures.items[0].bitmap=descriptor;textures.items[0].handle=source; + shader_init(xbox,0x7F,source);shader_init(gearbox,0x3F,source);shader_init(repeated,0,source); + if(!mcc_bitmap_model_usage(&runtime,&textures,reverse ? gearbox : xbox) || + !mcc_bitmap_model_usage(&runtime,&textures,reverse ? xbox : gearbox))return 2; + cloned=*(uint32_t *)(gearbox+0xC8); + if(cloned==source || runtime.report.tag_count!=2 || textures.count!=2)return 3; + if(*(uint32_t *)(xbox+0xC8)!=source || textures.items[0].channels!=1 || textures.items[1].channels!=2)return 4; + if(memcmp(&original_descriptor,descriptor,sizeof(*descriptor)) || + textures.items[1].bitmap==descriptor || memcmp(textures.items[1].bitmap,descriptor,sizeof(*descriptor)))return 5; + if(*(uint16_t *)(xbox+0x28)!=0x7F || *(uint16_t *)(gearbox+0x28)!=0x3F)return 6; + if(!mcc_bitmap_model_usage(&runtime,&textures,repeated) || *(uint32_t *)(repeated+0xC8)!=cloned || + runtime.report.tag_count!=2 || textures.count!=2)return 7; + /* Base, detail and cube textures remain ordinary in both shaders. */ + if(*(uint32_t *)(gearbox+0xB0)!=source || *(uint32_t *)(gearbox+0xE8)!=source || + *(uint32_t *)(gearbox+0x170)!=source)return 8; + mcc_bitmap_decode(dxt1,decoded,4,4,14,textures.items[0].channels); + for(i=0;i<16;i++)if(decoded[i]!=0xFFFF0000u)return 9; + mcc_bitmap_decode(rgba,decoded,1,1,11,textures.items[1].channels); + if(decoded[0]!=0x1E0A1428u)return 10; + shader_init(missing,0x40,0xFFFFFFFFu); + if(!mcc_bitmap_model_usage(&runtime,&textures,missing) || runtime.report.tag_count!=2)return 11; + shader_init(missing,0,0xFFFFFFFFu); + if(!mcc_bitmap_model_usage(&runtime,&textures,missing) || runtime.report.tag_count!=2)return 12; + /* Neither channel path can silently accept a stale/non-bitmap handle. */ + shader_init(missing,0x40,source+3); + if(mcc_bitmap_model_usage(&runtime,&textures,missing))return 13; + shader_init(missing,0,source^0x10000u); + if(mcc_bitmap_model_usage(&runtime,&textures,missing))return 14; + /* A bitmap can simultaneously serve two meter conventions and a + * material mask without any of these consumers overwriting another. */ + if(!mcc_meter_usage(&runtime,&textures,reverse ? &gearbox_meter : &xbox_meter) || + !mcc_meter_usage(&runtime,&textures,reverse ? &xbox_meter : &gearbox_meter))return 15; + if(xbox_meter.meter_bitmap.index!=source || gearbox_meter.meter_bitmap.index==source || + gearbox_meter.meter_bitmap.index==cloned || textures.count!=3 || runtime.report.tag_count!=3 || + textures.items[0].channels!=1 || textures.items[1].channels!=2 || textures.items[2].channels!=4)return 16; + if(xbox_meter.meter_flags!=0x3F || gearbox_meter.meter_flags!=0x1F || + memcmp(&original_descriptor,descriptor,sizeof(*descriptor)))return 17; + if(xbox_meter.opacity!=1.0f || gearbox_meter.opacity!=0.0f || + xbox_meter.fade!=0.75f || gearbox_meter.fade!=0.5f)return 21; + /* Transparent outside-shape pixel has nonzero fill order. Preserve + * alpha zero in Xbox order, while an unflagged meter must swap it. */ + rgba[0]=rgba[1]=rgba[2]=128;rgba[3]=0; + mcc_bitmap_decode(rgba,decoded,1,1,11,textures.items[0].channels); + if(decoded[0]!=0x00808080u)return 18; + mcc_bitmap_decode(rgba,decoded,1,1,11,textures.items[2].channels); + if(decoded[0]!=0x80008000u)return 19; + xbox_meter.meter_bitmap.index=gearbox_meter.meter_bitmap.index=0xFFFFFFFFu; + if(!mcc_meter_usage(&runtime,&textures,&xbox_meter) || !mcc_meter_usage(&runtime,&textures,&gearbox_meter) || + runtime.report.tag_count!=3)return 20; + free(textures.clones);free(textures.items);free(runtime.tags);return 0; +} +''' + work = tmp_path_factory.mktemp("mcc-model-masks") + path = work / "masks.c" + path.write_text(source) + output = work / ("masks.exe" if sys.platform == "win32" else "masks") + command = [clang, "-include", str(ROOT / "port/linux/game/mcc_loading.h"), str(ROOT / "tools/mcc_loading_stub.c"), "-std=gnu99", "-O2", "-Wall", "-Wextra", "-Werror", + "-Wno-multichar", "-Wno-unused-function", "-I", str(ROOT / "port/third_party/bcdec"), + str(path), "-o", str(output)] + if sys.platform == "win32": + command[1:1] = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld", "-D_CRT_SECURE_NO_WARNINGS"] + else: + command[1:1] = ["-m32", "-fsanitize=undefined", "-fsanitize-trap=undefined"] + result = subprocess.run(command, capture_output=True, text=True) + assert result.returncode == 0, result.stderr + return output + + +@pytest.mark.parametrize("reversed_consumers", [0, 1]) +def test_mcc_model_channel_order_is_per_shader(model_masks, reversed_consumers): + result = subprocess.run([str(model_masks), str(reversed_consumers)], capture_output=True, text=True, timeout=10) + assert result.returncode == 0, result.stdout + result.stderr diff --git a/tools/test_mcc_share_game.py b/tools/test_mcc_share_game.py new file mode 100644 index 0000000000..b36262508e --- /dev/null +++ b/tools/test_mcc_share_game.py @@ -0,0 +1,263 @@ +"""Real MCC game adapter, package planner, session and stage in two isolated fixture folders. + +Engine/UI/identity and metadata schema/decoder calls are deterministic stubs. The wire, host +admission, consent, file hashes, native safe publication and lifecycle implementation are real. +Linux instruments every translation unit with ASan/UBSan; Windows runs the same cases natively. +""" +from pathlib import Path +import shutil +import subprocess +import sys + +import pytest +from harness import function + +ROOT = Path(__file__).resolve().parents[1] +GAME = ROOT / "port/linux/game" +DRIVER = ROOT / "tools/tests/mcc_share_game.c" +CASES = ["transfer", "only_listed_files", "off", "unlisted", "listed_without_maker", "another_package_listed", + "workshop_sidecar", "unreadable_sidecar", "not_the_games_package", "gate", "identity_mismatch", + "handlers", "leave", "map_changes", "disk_space", "consent", "existing_version", "metadata_mismatch", + "host_toggle", "peer_left", "client_toggle", "map_only", "cancel", "workshop_off", "workshop_client_off", "prompt_map_change", "prompt_disconnect", "prompt_content_change", + "prompt_metadata_change", "stale_accept", "unused_resources", "bitmap_only", + "workshop_resource_fallback", "shared_resource", "invalid_resource", "host_revision", "prompt_overlay", + "admission_grace", "admission_player", "admission_peer_left", "admission_map", "admission_revision", + "admission_off", "admission_disconnect", "admission_wrap", "local_validation_hold", "validation_pending_cancel", + "validation_handoff", "validation_stale_handoff", + "manual_host_off", "manual_client_off", "manual_local", "manual_closed", + "manual_new_join", "manual_map_load", "manual_wait_menu", "manual_stale_accept", + "manual_cancel", "manual_disconnect", "manual_stale_workshop"] +RENAMED = ["mcc_share_game_update", "mcc_share_game_render", "mcc_share_game_downloading", + "mcc_share_game_holds_players", "mcc_share_game_machine_active", "mcc_share_game_machine_needs_map", "mcc_share_game_handles_message", + "mcc_share_game_handle_message", "mcc_identity_set_missing", "mcc_identity_host_package", + "mcc_identity_accept_installed", "display_error_text_when_main_menu_loaded", "network_game_abort", + "global_network_game_server_get", "global_network_game_client_get", + "network_distributed_server_send_to_machine_reliably", "network_distributed_client_send_reliably", + "network_game_client_get_game", "network_game_get_game", "mcc_share_package_build", "mcc_identity_host_revision", + "mcc_share_game_can_download", "mcc_share_game_has_workshop", "mcc_share_game_prompt_text", + "mcc_share_game_prompt_closed", "mcc_share_game_prompt_action", "mcc_share_game_disconnect", + "mcc_share_game_peer_left"] +HEADERS = { + "cseries.h": """#ifndef STUB_CSERIES_H +#define STUB_CSERIES_H +#include +#include +#include +#include +#include +typedef int boolean; +typedef unsigned char byte; +typedef unsigned short word; +#define TRUE 1 +#define FALSE 0 +#define NONE (-1) +#define NUMBEROF(a) ((short)(sizeof(a)/sizeof((a)[0]))) +#define PIN(x,lo,hi) ((x)<(lo)?(lo):(x)>(hi)?(hi):(x)) +#define csmemset memset +#define csmemcpy memcpy +#define csmemcmp memcmp +/* Production cseries.h remaps malloc/free, but leaves calloc as libc. */ +void *fixture_engine_malloc(size_t bytes); +void fixture_engine_free(void *pointer); +#define malloc(bytes) fixture_engine_malloc(bytes) +#define free(pointer) fixture_engine_free(pointer) +int csstrcasecmp(char const *a, char const *b); +typedef struct {float alpha,red,green,blue;} real_argb_color; +typedef struct {short x0,y0,x1,y1;} rectangle2d; +void offset_rectangle2d(void *rectangle, short x, short y); +#endif +""", + "cseries/errors.h": "#define _error_silent 0\nvoid error(short level, char const *format, ...);\n", + "bungie_net/common/message_header.h": """void build_message_header(word *header, word size, int type, int flags); +#define GET_MESSAGE_FLAGS(h) ((h)&3) +#define GET_MESSAGE_TYPE(h) (((h)>>2)&3) +#define GET_MESSAGE_SIZE(h) ((h)>>4) +""", + "game/game.h": "int game_in_progress(void);\nlong game_time_get(void);\n", + "main/main.h": "void main_goto_main_menu(void);\n", + "interface/interface.h": "long interface_get_tag_index(int tag);\nenum { _interface_font_terminal };\n", + "interface/ui_widget.h": """struct widget_instance; +boolean main_menu_is_active(void); +void display_error_text_when_main_menu_loaded(wchar_t const *text); +struct widget_instance *ui_widget_load_by_name_or_tag(char const *,long,void *,int,int,int,int); +void ui_widgets_pop_stack(int); +void ui_widget_delete(struct widget_instance *); +""", + "tag_files/tag_groups.h": "long tag_loaded(unsigned long, char const *);\n", + "networking/network_game_globals.h": """struct network_game_server; +struct network_game_client; +struct network_game_server *global_network_game_server_get(void); +struct network_game_client *global_network_game_client_get(void); +""", + "networking/network_game_manager.h": "void network_game_abort(void);\nstruct network_game *network_game_get_game(void);\nstruct network_player;\nint network_player_is_valid(struct network_player *);\n", + "networking/network_client_manager.h": """struct network_game_client; +#ifndef STUB_NETWORK_GAME +#define STUB_NETWORK_GAME +struct network_player { int valid; long machine_index; }; +struct network_game { struct { char name[128]; } map; unsigned char mcc_content_sha256[32], mcc_metadata_sha256[32]; struct network_player players[8]; }; +#endif +struct network_game *network_game_client_get_game(struct network_game_client *client); +""", + "render/render.h": "extern struct { struct { rectangle2d window_bounds, viewport_bounds; } camera; } render;\n", + "text/draw_string.h": "void draw_string_set_draw_mode(long a, long b, short c, short d, real_argb_color const *e);\n", + "text/font_group.h": "", + "rasterizer/rasterizer.h": "void rasterizer_draw_string(rectangle2d *bounds, void *a, void *b, short c, char const *text);\n", + "network_distributed.h": """struct distributed_message_header { word header; byte type; byte count; int game_time; unsigned epoch; }; +enum { _distributed_message_mcc_share_request = 103, _distributed_message_mcc_share_response = 104 }; +""", + "xtl.h": """#define FILE_ATTRIBUTE_DIRECTORY 0x10 +typedef union { struct { unsigned int LowPart, HighPart; }; unsigned long long QuadPart; } ULARGE_INTEGER; +int GetDiskFreeSpaceExA(char const *path, ULARGE_INTEGER *available, ULARGE_INTEGER *total, ULARGE_INTEGER *free_total); +unsigned long GetFileAttributesA(char const *path); +int CreateDirectoryA(char const *path, void *security); +int RemoveDirectoryA(char const *path); +int MoveFileA(char const *from, char const *to); +int DeleteFileA(char const *path); +""", + "mcc_cache.h": "int mcc_level_name(char const *name);\n", + "mcc_identity.h": """void mcc_identity_set_missing(int (*handler)(char const name[128], unsigned char const digest[32], unsigned char const metadata[32])); +int mcc_identity_host_package(char const *level, unsigned char digest[32]); +int mcc_identity_accept_installed(char const name[128], unsigned char const digest[32], unsigned char const metadata[32],char const *installed); +unsigned long mcc_identity_host_revision(void); +void mcc_identity_update(void); +int mcc_identity_pending(char const *); +""", + "mcc_maps.h": """#define MCC_MAPS_DIRECTORY "d:\\\\mcc_maps\\\\" +void mcc_maps_rescan(void); +short mcc_maps_count(boolean multiplayer_only); +char const *mcc_maps_level_name(short index); +int mcc_maps_workshop_title(char const *item, char *title, size_t size); +""", +} + + +def build(work, share_source=None, package_source=None): + clang = shutil.which("clang") + if not clang: + pytest.skip("clang required") + stubs = work / "stubs" + for name, text in HEADERS.items(): + path = stubs / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + windows = sys.platform == "win32" + flags = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld", "-D_CRT_SECURE_NO_WARNINGS"] if windows else ["-D_GNU_SOURCE"] + compile_flags = [x for x in flags if x != "-fuse-ld=lld"] + sanitize = [] if windows else ["-fsanitize=address,undefined", "-fno-sanitize-recover=all"] + includes = ["-I", str(stubs), "-I", str(GAME), "-I", str(ROOT / "port/linux/src")] + objects = [] + for filename in ("mcc_share.c", "mcc_share_package.c"): + source = stubs / filename + original = (share_source if filename == "mcc_share.c" else package_source) or GAME / filename + # Relocate includes only; the implementation is compiled unchanged. + source.write_text(original.read_text().replace('"../src/', '"')) + for prefix in ("h_", "j_"): + renames = [f"-D{name}={prefix}{name}" for name in RENAMED] + obj = work / f"{prefix}{filename}.o" + result = subprocess.run([clang, *compile_flags, *sanitize, "-std=gnu89", "-g", "-Wall", "-Wextra", "-Werror", + "-Wno-unused-parameter", *includes, *renames, "-c", str(source), "-o", str(obj)], + capture_output=True, text=True) + assert result.returncode == 0, result.stderr + objects.append(obj) + workshop = stubs / "mcc_workshop.c" + workshop.write_text("#define fopen fixture_fopen\n" + (GAME / "mcc_workshop.c").read_text()) + exe = work / ("game_test.exe" if windows else "game_test") + hooks = work / "map_share_hooks.c" + legacy = (GAME / "map_share.c").read_text() + hooks.write_text('''#include +typedef int boolean; +#define TRUE 1 +struct host_machine {int downloading,downloaded;}; +static struct {struct host_machine machines[128];} map_share_globals; +static int host_machine_valid(long i){return i>=0&&i<128;} +static int host_machine_downloading(struct host_machine const *m){return m->downloading;} +int h_mcc_share_game_machine_active(long); +int h_mcc_share_game_machine_needs_map(long); +#define mcc_share_game_machine_active h_mcc_share_game_machine_active +#define mcc_share_game_machine_needs_map h_mcc_share_game_machine_needs_map +void fixture_ce_download(int downloading,int downloaded){ + map_share_globals.machines[6].downloading=downloading; + map_share_globals.machines[6].downloaded=downloaded; +} +''' + function(legacy, "map_share_machine_downloading") + '\n' + + function(legacy, "map_share_machine_needs_map")) + result = subprocess.run([clang, *flags, *sanitize, "-std=gnu89", "-g", "-Wall", "-Wextra", "-Werror", + "-Wno-unused-parameter", *includes, str(DRIVER), str(hooks), *map(str, objects), + *[str(GAME / n) for n in ("mcc_share_session.c", "mcc_share_stage.c", "mcc_share_list.c", + "mcc_share_rules.c", "mcc_package.c", "mcc_sha256.c")], + str(workshop), str(ROOT / "port/linux/src/posix_mcc_share.c"), "-o", str(exe)], + capture_output=True, text=True) + assert result.returncode == 0, result.stderr + return exe + + +@pytest.fixture(scope="module") +def game_tool(tmp_path_factory): + return build(tmp_path_factory.mktemp("mcc-share-game")) + + +def run_case(exe, case, work): + work.mkdir() + return subprocess.run([str(exe), case, str(work)], capture_output=True, text=True, timeout=120) + + +@pytest.mark.parametrize("case", CASES) +def test_game_side(game_tool, tmp_path, case): + result = run_case(game_tool, case, tmp_path / "work") + assert result.returncode == 0, result.stderr + stage = tmp_path / "work/join/mcc_staging" + assert not stage.exists() or not any(p.is_file() for p in stage.rglob("*")) + + +def test_allocator_domain_negative_control(tmp_path): + source = (GAME / "mcc_share.c").read_text() + allocation = "entries=malloc(MCC_SHARE_METADATA_FILES*sizeof(*entries));" + assert source.count(allocation) == 1 + changed = tmp_path / "libc_allocation.c" + changed.write_text(source.replace(allocation, "entries=calloc(MCC_SHARE_METADATA_FILES,sizeof(*entries));")) + exe = build(tmp_path, changed) + result = run_case(exe, "transfer", tmp_path / "work") + assert result.returncode != 0 and "engine free received a non-engine allocation" in result.stderr + + +def test_completed_download_needs_time_for_player_admission(tmp_path): + source = (GAME / "mcc_share.c").read_text() + statement = "mcc_share_admission_pending[machine]=1;" + assert source.count(statement) == 1 + changed = tmp_path / "without_admission.c" + changed.write_text(source.replace(statement, "mcc_share_admission_pending[machine]=0;")) + exe = build(tmp_path, changed) + result = run_case(exe, "admission_grace", tmp_path / "work") + assert result.returncode == 1 and "map_share_machine_downloading(MACHINE)" in result.stderr + + +@pytest.mark.parametrize("before,after,case", [ + (" || !from_stream ||", " ||", "handlers"), + ('if (!config_boolean("network.map_download")) {', "if (0) {", "gate"), + ("memcmp(actual,mcc_share_metadata,32)", "0", "metadata_mismatch"), + ("!memcmp(mcc_share_proof.digest,mcc_share_digest,32)", "1", "identity_mismatch"), + ("mcc_share_prompt_pending || mcc_share_prompt_visible)\n\t\treturn;", "0)\n\t\treturn;", "prompt_overlay"), +]) +def test_negative_controls(tmp_path, before, after, case): + source = (GAME / "mcc_share.c").read_text() + assert source.count(before) == 1, before + changed = tmp_path / "changed_mcc_share.c" + changed.write_text(source.replace(before, after)) + exe = build(tmp_path, changed) + result = run_case(exe, case, tmp_path / "work") + assert result.returncode != 0, result.stderr + + +@pytest.mark.parametrize("before,after,case", [ + ("csstrcasecmp(expected,resources[i-1])", "0", "shared_resource"), + ("if (!resources[i-1][0]) continue;", + "if (!resources[i-1][0]) mcc_package_resource_path(canonical,i,resources[i-1]);", "unused_resources"), +]) +def test_resource_planner_negative_controls(tmp_path, before, after, case): + source = (GAME / "mcc_share_package.c").read_text() + assert source.count(before) == 1 + changed = tmp_path / "changed_package.c" + changed.write_text(source.replace(before, after)) + exe = build(tmp_path, package_source=changed) + result = run_case(exe, case, tmp_path / "work") + assert result.returncode != 0, result.stderr diff --git a/tools/test_mcc_share_menu.py b/tools/test_mcc_share_menu.py new file mode 100644 index 0000000000..b8da8cb35c --- /dev/null +++ b/tools/test_mcc_share_menu.py @@ -0,0 +1,240 @@ +"""Run the real download-management menu with observable storage/session boundaries.""" +from pathlib import Path +import subprocess +import xml.etree.ElementTree as ET + +import pytest + +from test_mcc_identity import compile_tool + +ROOT = Path(__file__).resolve().parents[1] +GAME = ROOT / "port/linux/game" + + +@pytest.mark.parametrize("platform", ["desktop", "android", "web"]) +@pytest.mark.parametrize("in_game", [False, True]) +def test_stock_network_menu_reaches_sharing(platform, in_game): + """Traverse the shipped Stock widgets without loading optional frontend tags.""" + base = "main_menu/settings_select/player_setup/player_profile_edit/network_setup/" + widgets = {w.get("name"): w for file in (ROOT / "port/assets/menus/ce").glob("*.xml") + for w in ET.parse(file).getroot().findall("widget")} + pending = [base + ("in_game/in_game_network_settings_screen" if in_game else "network_settings_screen")] + reached = set() + visible = lambda node: platform in node.get("platform", "desktop android web").split() + while pending: + name = pending.pop() + if name in reached or name not in widgets or not visible(widgets[name]): + continue + reached.add(name) + for node in widgets[name]: + if visible(node): + target = node.get("widget") if node.tag == "child" else node.get("open") + if target: + pending.append(target) + settings = {widgets[name].get("setting") for name in reached} + assert {"network.mcc_map_share", "network.map_download", "network.map_seed", + "game.mcc_campaigns", "game.mcc_collections"} <= settings + assert ("game.workshop_maps" in settings) == (platform == "desktop") + assert base + "mcc_downloads/screen" in reached + assert base + "mcc_downloads/remove" in reached + + +def test_generated_remove_button_has_one_text_owner(): + import port_settings + + base = port_settings.PE + "/network_setup/mcc_downloads" + name = base.replace("/", ".") + ".xml" + generated = "\n".join(port_settings.settings_files()[name]) + assert (ROOT / "port/assets/menus/ce" / name).read_text(encoding="utf-8") == generated + document = ET.fromstring(generated) + remove = document.find(f"widget[@name='{base}/remove']") + assert remove is not None + # widget_instance_render_text_box replaces and resizes dynamic text when a + # definition has a string-list binding. The screen's live update owns this + # button's text buffer instead, for both removal and confirmation labels. + assert not {"text", "strings", "string_list"}.intersection(remove.attrib) + screen = document.find(f"widget[@name='{base}/screen']") + assert screen.find("data[@input='port mcc downloads update']") is not None + for event in ("a", "start"): + assert remove.find(f"on[@event='{event}'][@run='port mcc downloads remove']") is not None + for button, caption in (("previous", "PREVIOUS"), ("next", "NEXT"), ("back", "BACK")): + assert document.find(f"widget[@name='{base}/{button}']").get("text") == caption + +HEADERS = { + "cseries.h": "#include \n#include \ntypedef int boolean;\n#define NUMBEROF(a) (sizeof(a)/sizeof((a)[0]))\n", + "game/game.h": "int game_in_progress(void);\nint game_time_menu_scene(void);\nint game_time_get_paused(void);\n", + "networking/network_game_globals.h": """struct network_game_client; +struct network_game_server; +struct network_game_client *global_network_game_client_get(void); +struct network_game_server *global_network_game_server_get(void); +""", +} + +DRIVER = r''' +#include +#include +#include +#include +#include "mcc_share_menu.h" +#include "mcc_share_storage.h" +#define CHECK(c) do { if(!(c)){fprintf(stderr,"line %d: %s\n",__LINE__,#c);exit(1);} } while(0) +static char const *native_maps="native-root/mcc_maps"; +static struct mcc_share_storage_item records[2]; +static int record_count=2,exists=1,list_error,list_truncated; +static int initialized,stat_calls,list_calls,remove_calls,delete_calls,rescans; +static int playing,menu_scene,paused,client,server; +static enum mcc_share_storage_result removal=MCC_SHARE_STORAGE_REMOVED; +static char removed[64]; + +int game_in_progress(void){return playing;} +int game_time_menu_scene(void){return menu_scene;} +int game_time_get_paused(void){return paused;} +struct network_game_client *global_network_game_client_get(void){return client ? (void*)&client : NULL;} +struct network_game_server *global_network_game_server_get(void){return server ? (void*)&server : NULL;} +void mcc_maps_rescan(void){rescans++;} +void platform_translate_path(char const *path,char *out,unsigned long size){ + CHECK(!strcmp(path,"d:\\mcc_maps"));CHECK(strlen(native_maps)directory_exists=native_exists;io->delete_file=native_delete; +} +int mcc_share_storage_list(char const *maps,struct mcc_share_io const *io, + struct mcc_share_storage_item *items,int capacity,int *truncated){ + CHECK(!strcmp(maps,native_maps));CHECK(io->directory_exists==native_exists); + CHECK(io->delete_file==native_delete);CHECK(capacity>=record_count);list_calls++; + *truncated=list_truncated; + if(list_error)return -1; + memcpy(items,records,(size_t)record_count*sizeof(*items));return record_count; +} +enum mcc_share_storage_result mcc_share_storage_remove(char const *maps, + struct mcc_share_io const *io,char const *folder){ + char path[160];int i; + CHECK(!strcmp(maps,native_maps));CHECK(io->directory_exists==native_exists); + CHECK(io->delete_file==native_delete);remove_calls++;strcpy(removed,folder); + if(removal==MCC_SHARE_STORAGE_ERROR)return removal; + snprintf(path,sizeof(path),"%s/%s/managed.map",maps,folder);CHECK(io->delete_file(path)); + for(i=0;i|name");strcpy(records[0].workshop.id,"12345"); + records[0].bytes=3u*1024u*1024u/2u;records[0].files=7; + strcpy(records[1].folder,"dl_second");strcpy(records[1].source,"mcc_maps\\host\\second"); + strcpy(records[1].maker,"Second maker");records[1].bytes=2u*1024u*1024u;records[1].files=3; + if(!strcmp(mode,"missing"))exists=0; + if(!strcmp(mode,"list_error"))list_error=1; + if(!strcmp(mode,"empty"))record_count=0; + if(!strcmp(mode,"text"))list_truncated=1; + if(!strncmp(mode,"ui_",3)){playing=1;menu_scene=1;} + mcc_share_menu_open();CHECK(initialized==1 && stat_calls==1); + if(!strcmp(mode,"missing")||!strcmp(mode,"empty")||!strcmp(mode,"list_error")){ + CHECK(!mcc_share_menu_can_remove());mcc_share_menu_remove();mcc_share_menu_remove();mcc_share_menu_step(1); + CHECK(!mcc_share_menu_confirming() && !remove_calls && !delete_calls && !rescans);text(shown); + CHECK(strstr(shown,list_error?"could not be read":"No managed MCC downloads")); + CHECK(list_calls==(exists?1:0));return 0; + } + CHECK(list_calls==1 && mcc_share_menu_can_remove()); + if(!strcmp(mode,"text")){ + text(shown);CHECK(strstr(shown,"1 of 2 (more packages exist)")); + CHECK(strstr(shown,"mcc_maps\\host\\first"));CHECK(strstr(shown,"Maker: Maker %s /name")); + CHECK(strstr(shown,"1.5 MiB, 7 files"));CHECK(strstr(shown,"Workshop: 12345"));CHECK(!strchr(shown,'|')); + mcc_share_menu_step(-1);text(shown);CHECK(strstr(shown,"2 of 2"));CHECK(strstr(shown,"2.0 MiB, 3 files")); + CHECK(!strstr(shown,"Workshop:"));CHECK(!remove_calls);return 0; + } + mcc_share_menu_remove();CHECK(mcc_share_menu_confirming()); + CHECK(!remove_calls && !delete_calls && !rescans);text(shown);CHECK(strstr(shown,"CONFIRM REMOVAL")); + if(!strcmp(mode,"selection")){ + mcc_share_menu_step(1);CHECK(!mcc_share_menu_confirming()); + mcc_share_menu_remove();CHECK(mcc_share_menu_confirming() && !remove_calls); + mcc_share_menu_remove();CHECK(remove_calls==1 && delete_calls==1 && !strcmp(removed,"dl_second")); + CHECK(rescans==1 && !mcc_share_menu_confirming());text(shown);CHECK(strstr(shown,"host\\first")); + mcc_share_menu_remove();CHECK(remove_calls==1 && mcc_share_menu_confirming()); + mcc_share_menu_open();CHECK(initialized==2 && !mcc_share_menu_confirming());return 0; + } + if(!strcmp(mode,"playing"))active=&playing; + if(!strcmp(mode,"paused")){active=&playing;paused=1;CHECK(game_time_get_paused());} + if(!strcmp(mode,"client"))active=&client; + if(!strcmp(mode,"server"))active=&server; + if(!strcmp(mode,"ui_client"))active=&client; + if(!strcmp(mode,"ui_server"))active=&server; + if(!strcmp(mode,"ui_to_game")){ + menu_scene=0;CHECK(playing && !mcc_share_menu_can_remove()); + mcc_share_menu_remove();CHECK(!mcc_share_menu_confirming() && !remove_calls && !delete_calls && !rescans); + menu_scene=1;mcc_share_menu_remove();CHECK(mcc_share_menu_confirming() && !remove_calls); + mcc_share_menu_remove();CHECK(remove_calls==1 && !strcmp(removed,"dl_first"));return 0; + } + if(active){ + *active=1;CHECK(!mcc_share_menu_can_remove());text(shown);CHECK(strstr(shown,"Leave the game/session")); + mcc_share_menu_remove();CHECK(!mcc_share_menu_confirming() && !remove_calls && !delete_calls && !rescans); + *active=0;mcc_share_menu_remove();CHECK(mcc_share_menu_confirming() && !remove_calls); + mcc_share_menu_remove();CHECK(remove_calls==1 && !strcmp(removed,"dl_first"));return 0; + } + if(!strcmp(mode,"leftovers"))removal=MCC_SHARE_STORAGE_LEFTOVERS; + if(!strcmp(mode,"remove_error"))removal=MCC_SHARE_STORAGE_ERROR; + mcc_share_menu_remove();CHECK(remove_calls==1 && !strcmp(removed,"dl_first")); + CHECK(rescans==1 && list_calls==2 && !mcc_share_menu_confirming());text(shown); + CHECK(strstr(shown,removal==MCC_SHARE_STORAGE_REMOVED?"Downloaded snapshot removed.": + removal==MCC_SHARE_STORAGE_LEFTOVERS?"Files you added were kept.":"Removal stopped: content changed")); + CHECK(delete_calls==(removal!=MCC_SHARE_STORAGE_ERROR)); + CHECK(strstr(shown,removal==MCC_SHARE_STORAGE_ERROR?"host\\first":"host\\second"));return 0; +} +''' + + +def build(work, implementation=None): + for name, text in HEADERS.items(): + path = work / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + source = work / "driver.c" + source.write_text(DRIVER) + return compile_tool(work, [source, implementation or GAME / "mcc_share_menu.c"]) + + +@pytest.fixture(scope="module") +def menu_tool(tmp_path_factory): + return build(tmp_path_factory.mktemp("mcc-share-menu")) + + +@pytest.mark.parametrize("case", ["selection", "playing", "paused", "client", "server", + "ui_removed", "ui_client", "ui_server", "ui_to_game", "text", "missing", + "empty", "list_error", "removed", "leftovers", "remove_error"]) +def test_download_management(menu_tool, case): + result = subprocess.run([str(menu_tool), case], capture_output=True, text=True, timeout=10) + assert result.returncode == 0, result.stderr + + +@pytest.mark.parametrize("before,after,case", [ + ("if (!confirming) { confirming=1; return; }", "", "selection"), + ("if (!mcc_share_menu_can_remove()) { confirming=0; return; }", "", "playing"), + ("(!game_in_progress() || game_time_menu_scene())", "!game_in_progress()", "ui_removed"), + ("(!game_in_progress() || game_time_menu_scene())", "(!game_in_progress() || game_time_get_paused() || game_time_menu_scene())", "paused"), +]) +def test_confirmation_and_session_guards_detect_removal_regressions(tmp_path, before, after, case): + original = (GAME / "mcc_share_menu.c").read_text() + assert original.count(before) == 1 + # Relocate the relative platform include only; compile the real menu body. + changed = tmp_path / "mcc_share_menu.c" + changed.write_text(original.replace(before, after).replace('"../src/posix.h"', + f'"{(ROOT / "port/linux/src/posix.h").as_posix()}"')) + executable = build(tmp_path, changed) + result = subprocess.run([str(executable), case], capture_output=True, text=True, timeout=10) + assert result.returncode == 1, result.stderr diff --git a/tools/test_mcc_share_rules.py b/tools/test_mcc_share_rules.py index 6efe5d0f0c..53e20cc8cc 100644 --- a/tools/test_mcc_share_rules.py +++ b/tools/test_mcc_share_rules.py @@ -122,3 +122,11 @@ def test_fuzzed_rules(tmp_path): cwd=tmp_path, capture_output=True, text=True, timeout=90) print(result.stderr) assert result.returncode == 0, result.stderr + + +def test_ci_runs_share_rules(): + """The dedicated Windows and Linux jobs must run this suite, not just trigger.""" + workflow = (ROOT / ".github/workflows/mcc.yml").read_text() + for job in ("reader-and-validator", "windows-adapters"): + body = workflow.split(f" {job}:", 1)[1].split("\n windows-adapters:", 1)[0] + assert "tools/test_mcc_share_rules.py" in body diff --git a/tools/test_mcc_sprites.py b/tools/test_mcc_sprites.py new file mode 100644 index 0000000000..1cf380217c --- /dev/null +++ b/tools/test_mcc_sprites.py @@ -0,0 +1,34 @@ +"""Render real MCC sprite batches across the native eight-bitmap boundary.""" +from pathlib import Path +import os +import shutil +import subprocess +import pytest +from harness import function + +ROOT = Path(__file__).resolve().parents[1] + + +def test_mcc_sprite_batches(tmp_path): + compiler = shutil.which('clang') + if not compiler: + pytest.skip('clang is required') + native = (ROOT / 'source/render/render_sprite.c').read_text() + header = (ROOT / 'source/render/render_sprite.h').read_text() + header = '\n'.join(line for line in header.splitlines() if not line.startswith(('#include', '#pragma'))) + helper = (ROOT / 'port/linux/game/mcc_sprites.c').read_text() + helper = '\n'.join(line for line in helper.splitlines() if not line.startswith(('#include', '#pragma'))) + fixture = (ROOT / 'tools/harness/tests/mcc_sprites.c').read_text() + source = fixture.replace('/* HEADER */', header).replace('/* IMPLEMENTATION */', + helper + '\n' + '\n'.join(function(native, name) for name in + ('build_sprites_begin', 'build_sprites_end', 'build_sprite_get_group'))) + path = tmp_path / 'sprites.c' + path.write_text(source) + binary = tmp_path / ('sprites.exe' if os.name == 'nt' else 'sprites') + target = ['--target=i686-pc-windows-msvc', '-fuse-ld=lld'] if os.name == 'nt' else ['-m32'] + result = subprocess.run([compiler, *target, '-std=gnu89', '-Wall', '-Wextra', '-Werror', + '-fsanitize=undefined', '-fsanitize-trap=undefined', str(path), '-o', str(binary)], + capture_output=True, text=True) + assert result.returncode == 0, result.stdout + result.stderr + result = subprocess.run([str(binary)], capture_output=True, text=True, timeout=10) + assert result.returncode == 0, result.stdout + result.stderr diff --git a/tools/test_mcc_syntax.py b/tools/test_mcc_syntax.py new file mode 100644 index 0000000000..af92aa575f --- /dev/null +++ b/tools/test_mcc_syntax.py @@ -0,0 +1,23 @@ +"""Exercise MCC capacity, graph validation and isolated script safety traversal.""" +import subprocess + +import pytest + +from test_mcc_scripts import native_mcc_harness + + +@pytest.fixture(scope="module") +def syntax_tool(native_mcc_harness): + return native_mcc_harness("mcc_syntax") + + +@pytest.mark.parametrize("case", [ + "empty", "high_slot", "sparse", "deep", "wide", "deep_cycle", "salt", "zero_salt", + "out_of_range", "unused", "sibling_cycle", "call_cycle", "short_blob", "long_blob", + "negative_count", "negative_capacity", "count_over_capacity", "actual_count", + "negative_actual", "free_hint", "signature", "node_size", "invalid_array", "callbacks", + "root_type", "damaged_root", "shared_child", +]) +def test_mcc_syntax_behavior(syntax_tool, case): + result = subprocess.run([str(syntax_tool), case], capture_output=True, text=True, timeout=10) + assert result.returncode == 0, result.stdout + result.stderr diff --git a/tools/test_mcc_texture_bridge.py b/tools/test_mcc_texture_bridge.py new file mode 100644 index 0000000000..2beaeb5fa8 --- /dev/null +++ b/tools/test_mcc_texture_bridge.py @@ -0,0 +1,350 @@ +"""MCC texture lifetime/pressure tests with real descriptors and a fake GPU. + +Compile the actual private bridge and native descriptor/size routines. GPU +stubs record ownership and failures; no legacy staging allocator is linked. +""" +from pathlib import Path +import re +import shutil +import subprocess +import sys + +import pytest + +from harness import function, structure + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.fixture(scope="module") +def bridge_tool(tmp_path_factory): + clang = shutil.which("clang") + if not clang: + pytest.skip("clang is needed for the MCC texture bridge tests") + work = tmp_path_factory.mktemp("mcc-texture-bridge") + native = (ROOT / "port/linux/src/xbox_textures.c").read_text() + xgpu = (ROOT / "port/linux/src/xgpu.h").read_text() + xdk = (ROOT / "port/include/xdk/xdk_d3d8.h").read_text() + pdb = (ROOT / "port/include/xdk/xdk_pdb.h").read_text() + macros = "\n".join(line for line in xdk.splitlines() if re.match( + r"#define (D3DFORMAT_|D3DSIZE_|D3DCOMMON_TYPE_TEXTURE|D3DTEXTURE_(?:PITCH|CUBEFACE)_ALIGNMENT)", line)) + formats = "\n".join("#define " + name + " " + value for name, value in re.findall( + r"\b(D3DFMT_\w+)\s*=\s*(0x[0-9a-fA-F]+|[0-9]+)\b", pdb)) + header = r''' +#ifndef TEST_XGPU_H +#define TEST_XGPU_H +#include +#include +#include +typedef unsigned long DWORD,D3DCOLOR; +typedef unsigned GLuint,GLenum; +typedef int BOOL,boolean; +#define TRUE 1 +#define FALSE 0 +#define GL_TEXTURE_2D 0x0DE1 +#define GL_TEXTURE_3D 0x806F +#define GL_TEXTURE_CUBE_MAP 0x8513 +''' + macros + '\n' + formats + '\n' + structure(xgpu, "xgpu_texture_description") + r''' +void xgpu_texture_describe(DWORD,DWORD,struct xgpu_texture_description *); +unsigned long xgpu_texture_face_size(struct xgpu_texture_description const *); +void glGenTextures(int,GLuint *); +void glDeleteTextures(int,GLuint const *); +void xgpu_gl_state_invalidate(void); +void xgpu_mcc_texture_unbind(DWORD const *); +BOOL xgpu_mcc_texture_upload(GLuint,GLenum,struct xgpu_texture_description const *,void const *,unsigned long,D3DCOLOR const *); +#endif +''' + (work / "xgpu.h").write_text(header) + (work / "zlib.h").write_text( + '#ifndef TEST_ZLIB_H\n#define TEST_ZLIB_H\n' + 'typedef unsigned int uInt;\nunsigned long crc32(unsigned long,const void *,uInt);\n' + '#endif\n') + (work / "zlib_prefixed.h").write_text('#include "zlib.h"\n') + helpers = re.search(r"enum texel_kind\s*\{.*?\};", native, re.S).group() + helpers += '\n' + structure(native, "format_information") + helpers += '\n' + '\n'.join(function(native, name) for name in ["format_information", + "kind_compressed", "floor_log2", "level_dimension", "xgpu_texture_describe", "level_bytes", + "xgpu_texture_level_offset", "xgpu_texture_face_size"]) + bridge = (ROOT / "port/linux/src/mcc_texture_bridge.c").read_text() + game = (ROOT / "port/linux/game/mcc_texture_cache.c").read_text() + source = r''' +#include "xgpu.h" +#include +#include "hud_hires.h" +#include "zlib.h" +const struct hud_hires_embedded hud_hires_embedded[] = { + {.tag="mcc\\hud\\rocket_reticle"}, {.tag="mcc\\hud\\sniper_scope"}}; +const unsigned int hud_hires_embedded_count=2; +static unsigned long mock_crc; +static int hud_enabled,fail_replacement; +unsigned long crc32(unsigned long c,const void *p,uInt bytes) {(void)c;(void)p;(void)bytes;return mock_crc;} +int config_boolean(char const *name) {(void)name;return hud_enabled;} +unsigned int hud_hires_override_texture(long asset,unsigned long *levels) { + *levels=10;return fail_replacement?0:900+(unsigned)asset; +} +static unsigned allocations,live_allocations,largest_allocation,fail_allocate; +static unsigned generated,deleted,uploads,unbound,invalidated,fail_upload,fail_generate; +static void const *last_pixels; +static unsigned long last_bytes; +static void *tracked_calloc(size_t count,size_t bytes) { + void *p; + if(fail_allocate)return NULL; + if(count*bytes>largest_allocation)largest_allocation=(unsigned)(count*bytes); + p=calloc(count,bytes);if(p){allocations++;live_allocations++;}return p; +} +static void tracked_free(void *p) {if(p)live_allocations--;free(p);} +void glGenTextures(int count,GLuint *p) {(void)count;*p=fail_generate?0:++generated;} +GLuint xgpu_texture_name_new(void) {GLuint texture;glGenTextures(1,&texture);return texture;} +void glDeleteTextures(int count,GLuint const *p) {(void)count;if(!*p)exit(80);deleted++;} +void xgpu_gl_state_invalidate(void) {invalidated++;} +void xgpu_mcc_texture_unbind(DWORD const *p) {if(!p)exit(81);unbound++;} +BOOL xgpu_mcc_texture_upload(GLuint texture,GLenum target,struct xgpu_texture_description const *d, + void const *pixels,unsigned long bytes,D3DCOLOR const *palette) { + (void)texture;(void)target;(void)d;(void)palette; + uploads++;last_pixels=pixels;last_bytes=bytes;return !fail_upload; +} +''' + helpers + r''' +#define calloc tracked_calloc +#define free tracked_free +''' + bridge + r''' +#undef calloc +#undef free +struct bitmap_data {short width,height,depth,type,format,mipmap_count;unsigned short flags;void *base_address;}; +static int active=1; +static int owned_coverage; +static void const *owned; +static unsigned long owned_bytes; +static int mcc_cache_tags_loaded(void) {return active;} +static void const *mcc_cache_bitmap_pixels(struct bitmap_data const *b,unsigned long *bytes,int *coverage) { + (void)b;if(coverage)*coverage=owned_coverage;*bytes=owned_bytes;return owned; +} +static unsigned rasterizer_xbox_bitmap_get_max_mipmap_count(struct bitmap_data *b) {return b->mipmap_count;} +static unsigned bitmap_mipmap_get_row_pitch(struct bitmap_data *b,int level) {(void)level;return b->width*4;} +''' + function(game, "mcc_texture_cache_get") + r''' +static DWORD format(unsigned logw,unsigned logh,unsigned logd,unsigned levels,unsigned type) { + return (D3DFMT_A8R8G8B8<=900 || uploads!=1)return 40; + hud_enabled=1; + if(!xgpu_mcc_texture_get(header,NULL,&texture,&target,&d) || texture!=900 || !d.hires || + d.width!=256 || d.height!=256 || d.levels!=10 || uploads!=1)return 41; + hud_enabled=0; + if(!get(header,&texture,&target) || texture>=900 || uploads!=1)return 42; + hud_enabled=1;fail_replacement=1; + if(!xgpu_mcc_texture_get(header,NULL,&texture,&target,&d) || texture>=900 || d.hires || d.levels!=1)return 43; + fail_replacement=0;mock_crc++; + original=mcc_texture_bridge_register(&other,format(8,8,0,1,0),0,data,262144); + if(!original || !get(original,&texture,&target) || texture>=900)return 44; + if(mcc_hud_texture_asset(&d,NULL,262144)!=-1)return 45; + mock_crc=1422780498UL; + if(mcc_hud_texture_asset(&d,data,262143)!=-1 || mcc_hud_texture_asset(&d,data,262144)!=1)return 46; + d.cube_map=1;if(mcc_hud_texture_asset(&d,data,262144)!=-1)return 47; + d.cube_map=0;d.width=128;if(mcc_hud_texture_asset(&d,data,262144)!=-1)return 48; + mcc_texture_bridge_dispose();free(data); + if(deleted!=2 || live_allocations)return 49; + } else if(!strcmp(argv[1],"identity")) { + DWORD copy[5]; + struct xgpu_texture_description description; + header=mcc_texture_bridge_register(&owner,format(2,2,0,1,0),0,pixels,sizeof(pixels)); + if(!header||header!=mcc_texture_bridge_find(&owner)||mcc_texture_bridge_find(&other))return 1; + if(header!=mcc_texture_bridge_register(&owner,0,0,NULL,0)||allocations!=1)return 2; + memcpy(copy,header,sizeof(copy)); + if(!xgpu_mcc_texture_describe(header,&description) || description.width!=4 || uploads || generated || + xgpu_mcc_texture_describe(copy,&description) || xgpu_mcc_texture_describe(NULL,&description) || + xgpu_mcc_texture_describe((DWORD const *)(uintptr_t)1,&description))return 50; + if(get(copy,&texture,&target)||get((DWORD const *)(uintptr_t)1,&texture,&target)||get(NULL,&texture,&target))return 3; + if(!get(header,&texture,&target)||!texture||target!=GL_TEXTURE_2D||uploads!=1||last_pixels!=pixels)return 4; + if(!get(header,&texture,&target)||uploads!=1)return 5; + } else if(!strcmp(argv[1],"bounds")) { + if(mcc_texture_bridge_register(NULL,format(2,2,0,1,0),0,pixels,sizeof(pixels))|| + mcc_texture_bridge_register(&owner,format(2,2,0,1,0),0,NULL,sizeof(pixels))|| + mcc_texture_bridge_register(&owner,format(2,2,0,1,0),0,pixels,63)|| + mcc_texture_bridge_register(&owner,format(2,2,0,1,2),0,pixels,767)|| + mcc_texture_bridge_register(&owner,format(14,2,0,1,0),0,pixels,0xffffffffUL)|| + mcc_texture_bridge_register(&owner,format(10,2,2,1,1),0,pixels,0xffffffffUL)|| + mcc_texture_bridge_register(&owner,format(2,2,0,15,0),0,pixels,0xffffffffUL))return 6; + fail_allocate=1; + if(mcc_texture_bridge_register(&owner,format(2,2,0,1,0),0,pixels,sizeof(pixels)))return 7; + if(allocations||generated||uploads)return 8; + } else if(!strcmp(argv[1],"failure")) { + header=mcc_texture_bridge_register(&owner,format(2,2,0,1,0),0,pixels,sizeof(pixels)); + fail_generate=1; + if(!get(header,&texture,&target)||texture||uploads||deleted)return 9; + fail_generate=0;fail_upload=1; + if(!get(header,&texture,&target)||texture||uploads!=1||deleted!=1||invalidated!=1)return 10; + fail_upload=0; + if(!get(header,&texture,&target)||!texture||uploads!=2||deleted!=1||last_bytes!=sizeof(pixels))return 11; + } else if(!strcmp(argv[1],"dispose")) { + struct xgpu_texture_description d; + header=mcc_texture_bridge_register(&owner,format(2,2,0,1,0),0,pixels,sizeof(pixels)); + mcc_texture_bridge_meter(&owner); + if(!xgpu_mcc_texture_get(header,NULL,&texture,&target,&d) || + !d.hires || !d.hires_coverage || !d.hires_point_threshold)return 12; + mcc_texture_bridge_dispose(); + if(live_allocations||deleted!=1||unbound!=1||invalidated!=1||mcc_texture_bridge_find(&owner)||get(header,&texture,&target))return 13; + header=mcc_texture_bridge_register(&owner,format(2,2,0,1,0),0,pixels,sizeof(pixels)); + if(!xgpu_mcc_texture_get(header,NULL,&texture,&target,&d)||uploads!=2||generated!=2 || + d.hires || d.hires_coverage || d.hires_point_threshold)return 14; + } else if(!strcmp(argv[1],"palette")) { + D3DCOLOR palette[256]={0};struct xgpu_texture_description d; + DWORD f=(format(2,2,0,1,0)&~D3DFORMAT_FORMAT_MASK)|(D3DFMT_P8<2048 || allocations!=count || live_allocations!=count)return 20; + for(frame=0;frame<3;frame++)for(i=0;i +#include +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#define csstrcasecmp _stricmp +#else +#include +#define csstrcasecmp strcasecmp +#endif +typedef unsigned char boolean; +typedef unsigned short word; +#define TRUE 1 +#define FALSE 0 +#define NONE (-1) +#define NUMBEROF(a) (sizeof(a)/sizeof(*(a))) +#define csmemcpy memcpy +#define MAXIMUM_NUMBER_OF_LOCAL_PLAYERS 4 +#define PC_MENU_FUNCTION_BASE 256 +#define pc_menu_profile_edit_begin(...) TRUE +#define TEST_FLAG(value,bit) ((value)&(1u<<(bit))) +#define _error_silent 0 +#define match_assert(file,line,condition) assert(condition) +#define match_vassert(file,line,condition,...) assert(condition) +enum {_game_connection_local,_game_connection_network_client,_game_connection_network_server}; +enum {_event_handler_close_current_widget_bit,_event_handler_close_other_widget_bit, +_event_handler_close_all_widgets_bit,_event_handler_open_widget_bit,_event_handler_reload_self_bit, +_event_handler_reload_widget_bit,_event_handler_give_focus_to_widget_bit,_event_handler_run_function_bit, +_event_handler_replace_with_other_widget_bit,_event_handler_go_back_to_previous_widget_bit, +_event_handler_run_scenario_script_bit,_event_handler_look_for_conditional_widget_on_failure_bit}; +enum {_conditional_widget_load_if_event_handler_function_fails_bit}; +enum {_ui_audio_feedback_none,_ui_audio_feedback_cursor,_ui_audio_feedback_forward,_ui_audio_feedback_back}; +struct widget_instance {long definition_tag_index;char const *name;short local_player_index;boolean visible,disabled; +short horizontal_offset,vertical_offset;struct widget_instance *parent,*next,*previous,*child,*focused_child;}; +struct event_record {short type,controller_index;}; +struct tag_reference {long index;}; +struct tag_block {long count;void *address;}; +struct ui_widget_definition {struct tag_block conditional_widgets;}; +struct ui_widget_event_handler_reference {uint32_t flags;short event_type,function; +struct tag_reference widget_tag,sound_effect;char script[32];}; +struct ui_widget_conditional_reference {struct tag_reference widget_tag;long flags;}; +struct widget_stack_data {int unused;}; +static int friendly=1,friendly_label=1,config_writes,config_success=1; +static int config_boolean(char const *name){assert(!strcmp(name,"network.coop_own_friendly_fire"));return friendly;} +static int config_write(char const *name,char const *value){ + assert(!strcmp(name,"network.coop_own_friendly_fire"));config_writes++; + assert(!strcmp(value,friendly?"false":"true")); + if(config_success)friendly=!friendly;return config_success; +} +static void mcc_pause_friendly_fire(boolean enabled){friendly_label=enabled;} +static struct {struct widget_instance *active_widgets[4];void *widget_stack[4];} widget_globals; +struct network_player {int valid;short machine_index,controller_index;char team_index;}; +struct network_game {struct {struct {boolean teams;} universal_variant;} variant;struct network_player players[4];}; +struct scenario {short type;}; +static struct scenario scenario; +static struct scenario *global_scenario = &scenario; +static struct network_game game; +static struct network_player sent_player; +static int mcc=1,connection,coop,saved=1,profile=1,have_settings=1,profile_begin,settings_open; +static int campaign=1,pc_menus=1,pause_owned=1; +static int settings_load=1,settings_controller=-1,last_profile=1004,available_profile=1005,assigned_controller=-1; +static long settings_history_tag; +static short mcc_settings_controller=NONE; +struct player_profile {int value;}; +struct game_variant {int value;}; +static struct { + long edit_profile_index; + struct {long active_profile_index;} local_players[4]; + struct {union {struct player_profile player;struct game_variant variant;} original,current;} edit_profile; +} player_ui_globals; +static struct {int original,current;} player_ui_edit_options; +enum {_saved_game_file_type_player_profile=1,_saved_game_file_type_game_variant=2}; +static struct widget_instance settings_widgets[4]; +static int revert_count,reset_count,restart_count,save_count,persist_count,menu_count,quit_count,end_count,settings_collision; +static int posted_button=-1,posted_controller=-1,deleted_count,opened_count,legacy_count,port_count; +static int message_count,script_count,team_sent,denied_count,top_dispatch,quit_controller=-1,balance_allowed=1; +static int local_players=1,left_count,left_controller=-1,stack_disposed; +static boolean quit_closes_widgets; +static boolean free_widget_on_delete,round_active=TRUE; +static struct widget_instance *released_widget; +static long opened_tag; +static wchar_t const *message; +static char const *widget_tag_name="ui\\shell\\multiplayer_game\\pause_game\\blue_team_button"; +static char owned[0x60],unowned[0x60]; +static boolean mcc_cache_tags_loaded(void){return mcc;} +static short mcc_cache_scenario_type(void){return mcc?scenario.type:NONE;} +static boolean mcc_level_name(char const *name){return name&&!strncmp(name,"mcc_maps\\",9);} +static boolean mcc_pause_owns(long tag){return pause_owned&&tag==300;} +static void *tag_get(long group,long index){(void)group;return index==100?owned:unowned;} +static char *tag_get_name(long index){(void)index;return (char *)widget_tag_name;} +static boolean mcc_cache_contains(void const *p,long size){return p==owned && size<=sizeof(owned);} +static char const *config_string(char const *name){(void)name;return pc_menus==2?"PC":pc_menus?"pc":"xbox";} +static short game_connection(void){return connection;} +static void display_error_text_deferred(wchar_t const *text,short controller){assert(controller>=0&&controller<4);message_count++;message=text;} +static void *global_network_game_server_get(void){return connection==_game_connection_network_server?&game:NULL;} +static void *global_network_game_client_get(void){return connection?&game:NULL;} +static boolean mcc_ui_restart_network_game(void){restart_count++;return TRUE;} +static void main_reset_map(void){reset_count++;} +static void main_revert_map(void){revert_count++;} +static void main_goto_main_menu(void){menu_count++;} +static boolean game_engine_running(void){return TRUE;} +static boolean game_engine_can_score(void){return round_active;} +static void ui_widget_delete(struct widget_instance *widget); +static void ui_widgets_close_all(void); +static void game_engine_end_game(void){end_count++;ui_widgets_close_all();} +static boolean network_coop_active(void){return coop;} +static boolean mcc_maps_level_campaign(char const *name){(void)name;return campaign;} +static char *main_get_map_name(void){return "mcc_maps\\a10";} +static boolean game_state_port_saved_game_valid(void){return saved;} +static void game_state_save_to_persistent_storage(void){persist_count++;} +static void game_state_save(void){save_count++;saved=TRUE;} +static void ui_widgets_close_all_for_local_player(short controller); +static void network_game_client_local_player_quit(short controller){quit_count++;quit_controller=controller;if(quit_closes_widgets){ui_widgets_close_all_for_local_player(controller);local_players--;}} +static short local_player_count(void){return (short)local_players;} +static void player_ui_local_player_left_multiplayer_game(short controller){left_count++;left_controller=controller;} +static struct network_game *network_game_get_game(void){return connection?&game:NULL;} +static short network_game_client_get_local_machine_index(void){return 2;} +static boolean network_player_is_valid(struct network_player const *player){return player->valid;} +static boolean network_game_client_update_local_player_data(void *client,struct network_player *player){assert(client);sent_player=*player;team_sent++;return TRUE;} +static boolean mcc_ui_team_balance_allows(short machine,short controller,short team){(void)machine;(void)controller;(void)team;return balance_allowed;} +static void event_manager_post_button(short controller,short button){posted_button=button;posted_controller=controller;} +static long tag_loaded(long group,char const *name){(void)group;(void)name;return have_settings?(settings_collision?100:200):NONE;} +static int saved_game_file_get_type(long index){return index>=1000&&index<=1005?1:index==2000?2:0;} +static boolean player_profile_get(long index,struct player_profile *out){profile_begin++;if(!profile)return FALSE;out->value=(int)index;return TRUE;} +static boolean playlist_profile_get(long index,struct game_variant *out){out->value=(int)index;return TRUE;} +static void playlist_profile_get_options(long index,int *out){*out=(int)index;} +static long player_ui_get_player1_last_used_profile_index(void){return last_profile;} +static void player_profiles_enumerate_available_to_local_player_index(short controller,word *count,long *index,boolean defaults){assert(controller==0&&!defaults&&*count==1);*count=available_profile==NONE?0:1;*index=available_profile;} +static void player_ui_set_active_player_profile(short controller,long index,struct player_profile *p){assert(p->value==index);assigned_controller=controller;player_ui_globals.local_players[controller].active_profile_index=index;} +void mcc_ui_settings_profile_released(void); +void mcc_ui_settings_close(short controller); +static void player_ui_end_editing_profile(void); +static struct widget_instance *widget_instance_get_topmost_parent(struct widget_instance *widget){assert(widget!=released_widget);while(widget->parent)widget=widget->parent;return widget;} +static boolean ui_widget_port_dispatch_event(struct widget_instance *widget,short type,short controller,boolean *deleted){(void)widget;(void)deleted;assert(type==32&&controller==2);top_dispatch++;return TRUE;} +static void error(int priority,char const *text,...){(void)priority;(void)text;} +static void console_warning(char const *text,...){(void)text;} +static boolean pc_menu_tag(long index){return index==200;} +static boolean main_menu_is_active(void){return FALSE;} +static boolean pc_menu_event_function_invoke(struct widget_instance *widget,struct event_record *event,long function,boolean *deleted){(void)widget;(void)event;(void)function;(void)deleted;port_count++;return TRUE;} +static boolean legacy_function(struct widget_instance *widget,struct event_record *event,boolean *deleted){(void)widget;(void)event;(void)deleted;legacy_count++;return TRUE;} +static struct {boolean (*functions[102])(struct widget_instance *,struct event_record *,boolean *);char const *names[102];} event_handler_function_list; +static boolean hs_evaluate_by_name(char const *name){assert(!strcmp(name,"my_action"));script_count++;return TRUE;} +static void widget_instance_give_focus_by_tag(struct widget_instance *widget,long tag,short controller){(void)widget;(void)tag;(void)controller;} +static void widget_instance_reload_recursive(struct widget_instance *widget){(void)widget;} +static void ui_widget_reload_by_tag(long tag){(void)tag;} +static struct widget_instance *widget_instance_find_by_tag_index(long tag){(void)tag;return NULL;} +static void ui_widget_delete(struct widget_instance *widget){int i;assert(widget!=released_widget);deleted_count++;for(i=0;i<4;i++)if(widget_globals.active_widgets[i]==widget)widget_globals.active_widgets[i]=NULL;if(free_widget_on_delete){released_widget=widget;memset(widget,0xDD,sizeof(*widget));free(widget);}} +static boolean ui_widget_launch_widget(struct widget_instance *widget,long tag){assert(widget!=released_widget);opened_count++;opened_tag=tag;return TRUE;} +static struct widget_instance *ui_widget_load_by_name_or_tag(char const *name,long tag,struct widget_instance *widget,short controller,long a,long b,long c){ + (void)tag;(void)widget;(void)b;(void)c; + if(!name||!strstr(name,"pc\\main_menu\\settings_select"))return NULL; + assert(controller>=0&&controller<4); + if(!settings_load)return NULL; + if(widget_globals.active_widgets[controller])ui_widget_delete(widget_globals.active_widgets[controller]); + settings_widgets[controller]=(struct widget_instance){200,"native settings",controller}; + widget_globals.active_widgets[controller]=&settings_widgets[controller]; + settings_controller=controller;settings_history_tag=a;settings_open++;return &settings_widgets[controller]; +} +static void widget_instance_go_back_to_previous(struct widget_instance *widget){assert(widget!=released_widget);} +static void unspatialized_impulse_sound_new(long tag,float volume){(void)tag;(void)volume;} +static void pop_widget(void **stack,struct widget_stack_data *data){(void)data;*stack=NULL;} +static void dispose_widget_stack(void **stack){assert(*stack);stack_disposed++;*stack=NULL;} +static boolean virtual_keyboard_active(void){return FALSE;} +static void virtual_keyboard_close(void){} +static void ui_play_audio_feedback_sound(long sound){(void)sound;} +''' + actions + '\n' + pc_stubs + '\n' + '\n'.join(function(profiles, name) for name in [ + "player_ui_get_edit_profile_index", "player_ui_get_active_player_profile_index", "player_ui_get_edit_player_profile", "player_ui_get_edit_playlist_profile", + "player_ui_begin_editing_profile", "clear_profile_edit_data", "player_ui_end_editing_profile" + ]) + '\n' + function(native, "ui_widgets_close_all_for_local_player") + '\n' + \ + function(native, "ui_widgets_close_all") + '\n' + \ + structure(ui, "mcc_ui_widget_prefix") + '\n' + '\n'.join(function(ui, name) for name in names) + '\n' + \ + '\n'.join(function(events, name) for name in ["network_game_remove_local_player", "ui_widget_function_denied", + "ui_widget_event_handler_function_invoke"]) + '\n' + \ + function(native, "event_handler_dispatch") + r''' +struct mcc_runtime {unsigned char *tag_index;uint32_t used;struct {uint32_t tag_count;}report;}; +static unsigned char metadata[0x400]; +static void *mcc_runtime_pointer(struct mcc_runtime *r,uint32_t address,uint32_t bytes){(void)r;return address<=sizeof(metadata)&&bytes<=sizeof(metadata)-address?metadata+address:NULL;} +static int mcc_hud(struct mcc_runtime *r,uint32_t group,unsigned char *p){(void)r;(void)group;(void)p;return TRUE;} +static int mcc_scenario_recordings(struct mcc_runtime *r,unsigned char *p){(void)r;(void)p;abort();return FALSE;} +static int mcc_scenario_cameras(struct mcc_runtime *r,unsigned char *p){(void)r;(void)p;abort();return FALSE;} +''' + '\n'.join(function(tags, name) for name in ["mcc_word", "mcc_block", "mcc_tags_prepare"]) + r''' +#define CHECK(c,n) do{if(!(c)){fprintf(stderr,"check %d failed\n",n);return n;}}while(0) +static boolean fire(struct widget_instance *widget,short button,struct ui_widget_event_handler_reference *handler){ + boolean deleted=FALSE;struct event_record event={1,widget->local_player_index};struct ui_widget_definition definition={0}; + if(button==handler->event_type)event_handler_dispatch(widget,&definition,&event,handler,&deleted); + return deleted; +} +int main(int argc,char **argv){ + struct widget_instance widget={100,"button",2};int i; + struct ui_widget_event_handler_reference mouse={128,28,108,{NONE},{NONE},{0}}; + struct ui_widget_event_handler_reference open={8,0,0,{101},{NONE},{0}}; + struct ui_widget_event_handler_reference action={132,0,11,{NONE},{NONE},{0}}; + for(i=0;i<102;i++)event_handler_function_list.functions[i]=legacy_function; + for(i=0;i<4;i++)player_ui_globals.local_players[i].active_profile_index=1000+i; + player_ui_globals.edit_profile_index=NONE; + event_handler_function_list.functions[72]=network_game_remove_local_player; + widget_globals.active_widgets[2]=&widget; + if(argc!=2)return 99; + if(!strcmp(argv[1],"metadata")){ + unsigned char entries[32]={0},before[0x400];struct mcc_runtime r={entries,sizeof(metadata),{1}}; + uint32_t group='DeLa',address=0,count=2,events=0x100; + memcpy(entries,&group,4);memcpy(entries+20,&address,4); + memcpy(metadata+0x54,&count,4);memcpy(metadata+0x58,&events,4); + memset(metadata+0x100,0xA5,0x90);memcpy(before,metadata,sizeof(before)); + CHECK(mcc_tags_prepare(&r),1);CHECK(!memcmp(before,metadata,sizeof(before)),2); + events=0x3FF;memcpy(metadata+0x58,&events,4);CHECK(!mcc_tags_prepare(&r),3);return 0; + } + if(!strcmp(argv[1],"confirmation")){ + CHECK(!fire(&widget,28,&mouse)&&posted_button==0&&posted_controller==2,4); + CHECK(!revert_count&&!opened_count&&!deleted_count,5); + CHECK(fire(&widget,posted_button,&open)&&opened_count==1&&opened_tag==101,6); + CHECK(!revert_count,7); + CHECK(fire(&widget,0,&action)&&revert_count==1&&deleted_count==1,8);return 0; + } + if(!strcmp(argv[1],"client-denial")||!strcmp(argv[1],"no-checkpoint")){ + if(!strcmp(argv[1],"client-denial")){connection=1;coop=TRUE;}else saved=FALSE; + CHECK(!fire(&widget,0,&action)&&message_count==1,9); + CHECK(!revert_count&&!deleted_count&&!opened_count,10); + action.function=12;connection=1; + CHECK(!fire(&widget,0,&action)&&message_count==2&&!reset_count&&!restart_count,11);return 0; + } + if(!strcmp(argv[1],"restart")){ + action.function=12;CHECK(fire(&widget,0,&action)&&reset_count==1,12); + connection=2;coop=TRUE;widget_globals.active_widgets[2]=&widget; + CHECK(fire(&widget,0,&action)&&restart_count==1&&reset_count==1,13); + action.function=163;coop=FALSE;widget_globals.active_widgets[2]=&widget; + CHECK(fire(&widget,0,&action)&&restart_count==2,14);return 0; + } + if(!strcmp(argv[1],"quit")){ + action.function=13;action.flags=128;CHECK(!fire(&widget,0,&action)&&menu_count==1&&persist_count==1,15); + coop=TRUE;connection=1;fire(&widget,0,&action);CHECK(quit_count==4&&persist_count==1,16); + coop=FALSE;action.function=72;fire(&widget,0,&action);CHECK(quit_count==5&&quit_controller==2,17);return 0; + } + if(!strcmp(argv[1],"team")){ + connection=1;game.variant.universal_variant.teams=TRUE;game.players[0]=(struct network_player){1,1,2,0}; + game.players[1]=(struct network_player){1,2,2,1};action.function=157; + CHECK(fire(&widget,0,&action)&&team_sent==1&&sent_player.team_index==1&&sent_player.machine_index==2,18); + widget_tag_name="ui\\shell\\multiplayer_game\\pause_game\\red_team_button"; + fire(&widget,0,&action);CHECK(team_sent==2&&sent_player.team_index==0,19); + game.variant.universal_variant.teams=FALSE;CHECK(!fire(&widget,0,&action)&&message_count==1,20);return 0; + } + if(!strcmp(argv[1],"settings")||!strcmp(argv[1],"settings-uppercase")){ + if(!strcmp(argv[1],"settings-uppercase"))pc_menus=2; + campaign=FALSE;scenario.type=1; + action.function=137;action.flags=136;action.widget_tag.index=300; + CHECK(fire(&widget,0,&action)&&settings_open==1&&profile_begin==1,21); + CHECK(!opened_count,22);have_settings=FALSE; + CHECK(!fire(&widget,0,&action)&&message_count==1&&settings_open==1,23); + have_settings=TRUE;settings_collision=TRUE; + CHECK(!fire(&widget,0,&action)&&profile_begin==1&&settings_open==1&&message_count==2,36); + CHECK(mcc_ui_settings_needed("mcc_maps\\dangercanyon"),24);mcc=FALSE;CHECK(!mcc_ui_settings_needed("mcc_maps\\dangercanyon"),25);return 0; + } + if(!strcmp(argv[1],"save")){ + action.function=179;fire(&widget,0,&action);CHECK(save_count==1&&persist_count==1,26); + coop=TRUE;connection=2;fire(&widget,0,&action);CHECK(save_count==2&&persist_count==1,27); + connection=1;CHECK(!fire(&widget,0,&action)&&save_count==2&&message_count==1,28);return 0; + } + if(!strcmp(argv[1],"team-balance")){ + connection=1;game.variant.universal_variant.teams=TRUE;balance_allowed=FALSE;action.function=157; + CHECK(!fire(&widget,0,&action)&&message_count==1&&!team_sent&&!deleted_count,41);return 0; + } + if(!strcmp(argv[1],"new-game")){ + struct widget_instance *heap_widget=malloc(sizeof(*heap_widget)); + CHECK(heap_widget!=NULL,42);*heap_widget=widget; + widget_tag_name="ui\\shell\\multiplayer_game\\pause_game\\new_game_button"; + fire(&widget,28,&mouse);CHECK(posted_button==0,37); + /* The actual engine synchronously frees the whole tree. Pending + * close/go-back flags must not touch it again after MCC handles it. */ + open.flags|=(1u<<_event_handler_close_current_widget_bit)|(1u<<_event_handler_go_back_to_previous_widget_bit); + connection=2;widget_globals.active_widgets[2]=heap_widget;free_widget_on_delete=TRUE; + CHECK(fire(heap_widget,posted_button,&open)&&end_count==1&&!opened_count&&deleted_count==1,38); + CHECK(!widget_globals.active_widgets[2]&&released_widget==heap_widget,43); + free_widget_on_delete=FALSE;widget_globals.active_widgets[2]=&widget; + connection=1;CHECK(!fire(&widget,0,&open)&&end_count==1&&message_count==1&&!opened_count&&deleted_count==1,39); + connection=2;round_active=FALSE; + CHECK(!fire(&widget,0,&open)&&end_count==1&&message_count==2&&deleted_count==1,44); + open.flags=8; + mcc=FALSE;fire(&widget,0,&open);CHECK(opened_count==1&&end_count==1,40);return 0; + } + if(!strcmp(argv[1],"trusted-pause")){ + widget.definition_tag_index=300; + CHECK(tag_get('DeLa',300)==unowned&&mcc_ui_trusted_action(&widget,MCC_PAUSE_ACTION_RESUME),45); + action.function=MCC_PAUSE_ACTION_RESUME; + CHECK(fire(&widget,0,&action)&&deleted_count==1&&!legacy_count,46); + widget_globals.active_widgets[2]=&widget;action.function=MCC_PAUSE_ACTION_REVERT; + CHECK(fire(&widget,0,&action)&&revert_count==1,47); + widget_globals.active_widgets[2]=&widget;action.function=MCC_PAUSE_ACTION_RESTART; + CHECK(fire(&widget,0,&action)&&reset_count==1,48); + action.flags=128;action.function=MCC_PAUSE_ACTION_SAVE; + CHECK(!fire(&widget,0,&action)&&save_count==1&&persist_count==1,49); + action.function=MCC_PAUSE_ACTION_QUIT; + CHECK(!fire(&widget,0,&action)&&menu_count==1&&persist_count==2,50); + connection=1;coop=TRUE; + CHECK(!fire(&widget,0,&action)&&quit_count==4&&persist_count==2,51); + campaign=FALSE;scenario.type=1;coop=FALSE; + CHECK(fire(&widget,0,&action)&&quit_count==5&&quit_controller==2,52);return 0; + } + if(!strcmp(argv[1],"trusted-teams")){ + widget.definition_tag_index=300;widget_tag_name="generated\\arbitrary_button_name"; + connection=1;campaign=FALSE;scenario.type=1;game.variant.universal_variant.teams=TRUE; + game.players[1]=(struct network_player){1,2,2,1}; + action.function=MCC_PAUSE_ACTION_RED_TEAM; + CHECK(fire(&widget,0,&action)&&team_sent==1&&sent_player.team_index==0,53); + widget_globals.active_widgets[2]=&widget;action.function=MCC_PAUSE_ACTION_BLUE_TEAM; + CHECK(fire(&widget,0,&action)&&team_sent==2&&sent_player.team_index==1,54); + balance_allowed=FALSE;CHECK(!fire(&widget,0,&action)&&team_sent==2&&message_count==1,55);return 0; + } + if(!strcmp(argv[1],"split-resume")||!strcmp(argv[1],"split-team")|| + !strcmp(argv[1],"split-team-denied")||!strcmp(argv[1],"split-quit")|| + !strcmp(argv[1],"split-quit-sync")||!strcmp(argv[1],"local-quit")){ + struct widget_instance *heap_widget=malloc(sizeof(*heap_widget)); + struct widget_instance other={300,"other player's pause",1}; + struct widget_stack_data history={0},other_history={0}; + boolean team=!strncmp(argv[1],"split-team",10),resume=!strcmp(argv[1],"split-resume"); + boolean denied=!strcmp(argv[1],"split-team-denied"),local=!strcmp(argv[1],"local-quit"); + CHECK(heap_widget!=NULL,73);*heap_widget=widget;heap_widget->definition_tag_index=300; + campaign=FALSE;scenario.type=1;connection=local?0:1;local_players=local?1:2; + widget_globals.active_widgets[1]=&other;widget_globals.widget_stack[1]=&other_history; + widget_globals.active_widgets[2]=heap_widget;widget_globals.widget_stack[2]=&history; + free_widget_on_delete=TRUE;quit_closes_widgets=!strcmp(argv[1],"split-quit-sync"); + action.flags=128;action.function=resume?MCC_PAUSE_ACTION_RESUME: + team?MCC_PAUSE_ACTION_RED_TEAM:MCC_PAUSE_ACTION_QUIT; + if(team){game.variant.universal_variant.teams=TRUE;game.players[1]=(struct network_player){1,2,2,1};} + if(denied){ + balance_allowed=FALSE; + CHECK(!fire(heap_widget,0,&action)&&!deleted_count&&!stack_disposed&&!team_sent&&message_count==1,74); + CHECK(widget_globals.active_widgets[2]==heap_widget&&widget_globals.widget_stack[2]==&history,75); + free(heap_widget); + }else{ + /* The real close-for-controller helper frees the caller and its + * history. Native quit may do so first; dispatch must not reuse it. */ + CHECK(fire(heap_widget,0,&action)&&deleted_count==1&&stack_disposed==1,76); + CHECK(released_widget==heap_widget&&!widget_globals.active_widgets[2]&&!widget_globals.widget_stack[2],77); + CHECK(!opened_count&&!legacy_count&&!persist_count,78); + if(team)CHECK(team_sent==1&&sent_player.team_index==0&&!quit_count,79); + else if(resume)CHECK(!team_sent&&!quit_count&&!menu_count,80); + else if(local)CHECK(menu_count==1&&!quit_count&&!left_count,81); + else CHECK(quit_count==1&&quit_controller==2&&left_count==1&&left_controller==2&&!menu_count,82); + } + CHECK(widget_globals.active_widgets[1]==&other&&widget_globals.widget_stack[1]==&other_history,83); + return 0; + } + if(!strcmp(argv[1],"trusted-end")){ + struct widget_instance *heap_widget=malloc(sizeof(*heap_widget)); + CHECK(heap_widget!=NULL,56);*heap_widget=widget;heap_widget->definition_tag_index=300; + widget_globals.active_widgets[2]=heap_widget;free_widget_on_delete=TRUE; + connection=2;campaign=FALSE;scenario.type=1;action.function=MCC_PAUSE_ACTION_END_GAME; + /* Builder confirmations use run-function only for END_GAME. */ + action.flags=128; + CHECK(fire(heap_widget,0,&action)&&end_count==1&&deleted_count==1&&!opened_count,57); + CHECK(released_widget==heap_widget&&!widget_globals.active_widgets[2],58); + widget.definition_tag_index=300;connection=1;free_widget_on_delete=FALSE; + CHECK(!fire(&widget,0,&action)&&end_count==1&&message_count==1,59);return 0; + } + if(!strcmp(argv[1],"friendly-fire")){ + widget.definition_tag_index=300;action.function=MCC_PAUSE_ACTION_FRIENDLY_FIRE;action.flags=128; + CHECK(!fire(&widget,0,&action)&&!config_writes,147); + coop=TRUE;connection=1; + CHECK(!fire(&widget,0,&action)&&config_writes==1&&!friendly&&!friendly_label,148); + CHECK(!fire(&widget,0,&action)&&config_writes==2&&friendly&&friendly_label,149); + config_success=0; + CHECK(!fire(&widget,0,&action)&&config_writes==3&&friendly&&friendly_label,150); + widget.definition_tag_index=100; + CHECK(!fire(&widget,0,&action)&&config_writes==3,151); + CHECK(!revert_count&&!restart_count&&!end_count&&!deleted_count&&!quit_count,152);return 0; + } + if(!strcmp(argv[1],"trusted-settings")){ + widget.definition_tag_index=300;action.function=MCC_PAUSE_ACTION_SETTINGS;action.flags=128; + CHECK(fire(&widget,0,&action)&&profile_begin==1&&settings_open==1,60); + mcc_ui_settings_close(NONE); + campaign=FALSE;scenario.type=1;pc_menus=FALSE; + CHECK(fire(&widget,0,&action)&&profile_begin==2&&settings_open==2,61); + mcc_ui_settings_close(NONE); + pc_menus=TRUE; + CHECK(fire(&widget,0,&action)&&profile_begin==3&&settings_open==3,62); + settings_collision=TRUE; + CHECK(!fire(&widget,0,&action)&&profile_begin==3&&settings_open==3&&message_count==1,63);return 0; + } + if(!strcmp(argv[1],"settings-namespace")){ + CHECK(mcc_ui_settings_needed("mcc_maps\\a10"),69); + CHECK(mcc_ui_settings_pause_game(),140); + global_scenario=NULL;CHECK(mcc_ui_settings_pause_game(),146);global_scenario=&scenario; + connection=1;CHECK(!mcc_ui_settings_pause_game(),141); + connection=2;CHECK(!mcc_ui_settings_pause_game(),142); + connection=0;local_players=0;CHECK(mcc_ui_settings_pause_game(),143); + local_players=1;scenario.type=1;CHECK(!mcc_ui_settings_pause_game(),144); + scenario.type=0;mcc=FALSE;CHECK(!mcc_ui_settings_pause_game(),145);mcc=TRUE; + CHECK(!mcc_ui_settings_needed("mercury_falling")&&!mcc_ui_settings_needed("a10"),70); + campaign=FALSE;CHECK(mcc_ui_settings_needed("mcc_maps\\dangercanyon"),71); + CHECK(!mcc_ui_settings_needed("ui")&&!mcc_ui_settings_needed("custom_maps\\dangercanyon")&& + !mcc_ui_settings_needed("dangercanyon")&&!mcc_ui_settings_needed(NULL),72);return 0; + } + if(!strcmp(argv[1],"network-stale-solo")){ + /* Network startup changes its own map, leaving main_get_map_name() + * and the solo catalog classification at the previous campaign. */ + int role;widget.definition_tag_index=300;scenario.type=1;campaign=TRUE;action.flags=128; + CHECK(!strcmp(main_get_map_name(),"mcc_maps\\a10"),84); + for(role=1;role<=2;role++){ + connection=role;action.function=MCC_PAUSE_ACTION_SETTINGS; + CHECK(fire(&widget,0,&action)&&settings_open==role&&profile_begin==role,85); + widget_globals.active_widgets[2]=&widget;action.function=MCC_PAUSE_ACTION_QUIT; + CHECK(fire(&widget,0,&action)&&quit_count==role&&quit_controller==2,86); + CHECK(!persist_count&&!menu_count,87); + } + return 0; + } + if(!strcmp(argv[1],"campaign-stale-catalog")){ + /* Saving/reloading a live scenario must not depend on later catalog + * changes or the last multiplayer selection. */ + widget.definition_tag_index=300;scenario.type=0;campaign=FALSE;action.flags=128; + action.function=MCC_PAUSE_ACTION_SETTINGS; + CHECK(fire(&widget,0,&action)&&profile_begin==1&&settings_open==1,88); + mcc_ui_settings_close(NONE); + action.function=MCC_PAUSE_ACTION_SAVE; + CHECK(!fire(&widget,0,&action)&&save_count==1&&persist_count==1,89); + action.function=MCC_PAUSE_ACTION_QUIT; + CHECK(!fire(&widget,0,&action)&&persist_count==2&&menu_count==1&&!quit_count,90); + coop=TRUE;connection=1; + CHECK(!fire(&widget,0,&action)&&persist_count==2&&quit_count==4,91);return 0; + } + if(!strcmp(argv[1],"settings-no-scenario")){ + widget.definition_tag_index=300;global_scenario=NULL;campaign=FALSE;action.flags=128; + action.function=MCC_PAUSE_ACTION_SETTINGS; + CHECK(!fire(&widget,0,&action)&&!profile_begin&&!settings_open&&message_count==1,92); + global_scenario=&scenario;scenario.type=2; + CHECK(!fire(&widget,0,&action)&&!profile_begin&&!settings_open&&message_count==2,93);return 0; + } + if(!strcmp(argv[1],"settings-controller")){ + struct widget_instance *heap_widget=malloc(sizeof(*heap_widget)); + struct widget_instance other={300,"other notification",0}; + CHECK(heap_widget!=NULL,94);*heap_widget=widget;heap_widget->definition_tag_index=300; + scenario.type=1;action.flags=128;action.function=MCC_PAUSE_ACTION_SETTINGS; + widget_globals.active_widgets[0]=&other;widget_globals.active_widgets[2]=heap_widget;free_widget_on_delete=TRUE; + CHECK(fire(heap_widget,0,&action)&&released_widget==heap_widget&&settings_controller==2,95); + CHECK(player_ui_globals.edit_profile_index==1002&&player_ui_get_edit_player_profile()->value==1002,96); + CHECK(mcc_settings_controller==2&&settings_history_tag==300&&widget_globals.active_widgets[0]==&other,97); + CHECK(player_ui_globals.local_players[0].active_profile_index==1000&&assigned_controller==NONE,98); + free_widget_on_delete=FALSE;ui_widgets_close_all_for_local_player(2); + CHECK(!player_ui_get_edit_player_profile()&&mcc_settings_controller==NONE,99);return 0; + } + if(!strcmp(argv[1],"settings-split-denied")){ + int count;widget.definition_tag_index=300;scenario.type=1;action.flags=128; + for(count=2;count<=4;count++){ + local_players=count;action.function=MCC_PAUSE_ACTION_SETTINGS; + CHECK(!fire(&widget,0,&action)&&!profile_begin&&!settings_open&&!deleted_count,100); + widget.definition_tag_index=100;action.function=137; + CHECK(!fire(&widget,0,&action)&&!profile_begin&&!settings_open&&!deleted_count,101); + widget.definition_tag_index=300; + } + CHECK(message_count==6&&widget_globals.active_widgets[2]==&widget,102);return 0; + } + if(!strcmp(argv[1],"settings-busy")){ + widget.definition_tag_index=300;scenario.type=1;action.flags=128;action.function=MCC_PAUSE_ACTION_SETTINGS; + player_ui_begin_editing_profile(1000);player_ui_get_edit_player_profile()->value=765; + CHECK(!fire(&widget,0,&action)&&profile_begin==1&&!settings_open,103); + CHECK(player_ui_globals.edit_profile_index==1000&&player_ui_get_edit_player_profile()->value==765,104); + mcc_ui_settings_close(NONE);CHECK(player_ui_globals.edit_profile_index==1000,105); + player_ui_end_editing_profile();player_ui_begin_editing_profile(2000); + CHECK(!fire(&widget,0,&action)&&player_ui_get_edit_playlist_profile()!=NULL&&!settings_open,106); + player_ui_end_editing_profile();CHECK(fire(&widget,0,&action)&&mcc_settings_controller==2,107); + CHECK(!fire(&widget,0,&action)&&settings_open==1&&profile_begin==2,108);return 0; + } + if(!strcmp(argv[1],"settings-lifecycle")){ + struct widget_stack_data history={0}; + widget.definition_tag_index=300;scenario.type=1;action.flags=128;action.function=MCC_PAUSE_ACTION_SETTINGS; + CHECK(fire(&widget,0,&action)&&mcc_settings_controller==2,109); + /* Moving to a nested subpage deletes the root widget but must keep + * its native edit buffer; only closing the whole owner clears it. */ + ui_widget_delete(widget_globals.active_widgets[2]); + settings_widgets[2].definition_tag_index=201;widget_globals.active_widgets[2]=&settings_widgets[2]; + widget_globals.widget_stack[2]=&history;mcc_ui_settings_close(1); + CHECK(player_ui_get_edit_player_profile()!=NULL&&mcc_settings_controller==2,110); + ui_widgets_close_all_for_local_player(2); + CHECK(!player_ui_get_edit_player_profile()&&mcc_settings_controller==NONE&&!widget_globals.widget_stack[2],111); + widget.local_player_index=1;widget_globals.active_widgets[1]=&widget; + CHECK(fire(&widget,0,&action)&&settings_controller==1&&player_ui_globals.edit_profile_index==1001,112); + /* Cancel/save's native profile-clear releases ownership before any + * later unrelated editor begins; closing old UI cannot cancel it. */ + player_ui_end_editing_profile();CHECK(mcc_settings_controller==NONE,113); + player_ui_begin_editing_profile(1000);ui_widgets_close_all_for_local_player(1); + CHECK(player_ui_globals.edit_profile_index==1000,114); + player_ui_end_editing_profile();widget_globals.active_widgets[1]=&widget; + CHECK(fire(&widget,0,&action)&&mcc_settings_controller==1,115); + ui_widgets_close_all();CHECK(!player_ui_get_edit_player_profile()&&mcc_settings_controller==NONE,116); + widget_globals.active_widgets[1]=&widget;CHECK(fire(&widget,0,&action),117); + mcc_ui_settings_close(NONE);CHECK(!player_ui_get_edit_player_profile()&&mcc_settings_controller==NONE,118);return 0; + } + if(!strcmp(argv[1],"settings-open-failure")){ + widget.definition_tag_index=300;scenario.type=1;action.flags=128;action.function=MCC_PAUSE_ACTION_SETTINGS; + settings_load=FALSE; + CHECK(!fire(&widget,0,&action)&&!deleted_count&&!settings_open&&mcc_settings_controller==NONE,119); + CHECK(!player_ui_get_edit_player_profile()&&widget_globals.active_widgets[2]==&widget,120); + settings_load=TRUE;profile=FALSE; + CHECK(!fire(&widget,0,&action)&&!settings_open&&mcc_settings_controller==NONE,121); + profile=TRUE;player_ui_globals.local_players[2].active_profile_index=2000; + CHECK(!fire(&widget,0,&action)&&!player_ui_get_edit_playlist_profile()&&mcc_settings_controller==NONE,127); + player_ui_globals.local_players[2].active_profile_index=1002; + profile=TRUE;CHECK(fire(&widget,0,&action)&&settings_open==1&&player_ui_globals.edit_profile_index==1002,122);return 0; + } + if(!strcmp(argv[1],"settings-profile-reopen")){ + widget.definition_tag_index=300;scenario.type=0;action.flags=128;action.function=MCC_PAUSE_ACTION_SETTINGS; + CHECK(fire(&widget,0,&action)&&mcc_settings_controller==2,131); + CHECK(!mcc_ui_settings_profile_reopen(1000)&&mcc_settings_controller==2,132); + CHECK(mcc_ui_settings_profile_reopen(1002)&&mcc_settings_controller==2,133); + CHECK(player_ui_get_edit_profile_index()==1002,134); + ui_widgets_close_all(); + CHECK(!player_ui_get_edit_player_profile()&&mcc_settings_controller==NONE,135); + player_ui_begin_editing_profile(1000); + CHECK(!mcc_ui_settings_profile_reopen(1000)&&player_ui_get_edit_profile_index()==1000,136); + return 0; + } + if(!strcmp(argv[1],"settings-replaced-editor")){ + widget.definition_tag_index=300;scenario.type=1;action.flags=128;action.function=MCC_PAUSE_ACTION_SETTINGS; + CHECK(fire(&widget,0,&action)&&mcc_settings_controller==2,128); + /* Any later native editor entry invalidates MCC's ownership even + * when it does not call the normal end-edit helper first. */ + player_ui_begin_editing_profile(1000); + CHECK(mcc_settings_controller==NONE&&player_ui_globals.edit_profile_index==1000,129); + ui_widgets_close_all();CHECK(player_ui_globals.edit_profile_index==1000,130);return 0; + } + if(!strcmp(argv[1],"settings-profile-fallback")){ + widget.definition_tag_index=300;scenario.type=1;action.flags=128;action.function=MCC_PAUSE_ACTION_SETTINGS; + player_ui_globals.local_players[2].active_profile_index=NONE; + CHECK(!fire(&widget,0,&action)&&!profile_begin&&assigned_controller==NONE,123); + widget.local_player_index=0;widget_globals.active_widgets[0]=&widget; + player_ui_globals.local_players[0].active_profile_index=NONE; + CHECK(fire(&widget,0,&action)&&player_ui_globals.edit_profile_index==1004&&assigned_controller==0,124); + ui_widgets_close_all_for_local_player(0);player_ui_globals.local_players[0].active_profile_index=NONE;last_profile=NONE; + widget_globals.active_widgets[0]=&widget; + CHECK(fire(&widget,0,&action)&&player_ui_globals.edit_profile_index==1005&&assigned_controller==0,125); + CHECK(player_ui_globals.local_players[2].active_profile_index==NONE,126);return 0; + } + if(!strcmp(argv[1],"trusted-isolation")){ + action.function=MCC_PAUSE_ACTION_RESUME; + CHECK(!mcc_ui_trusted_action(&widget,action.function)&&!fire(&widget,0,&action)&&!deleted_count,64); + widget.definition_tag_index=301; + CHECK(!mcc_ui_trusted_action(&widget,action.function)&&!fire(&widget,0,&action)&&!deleted_count,65); + widget.definition_tag_index=300;pause_owned=FALSE; + CHECK(!fire(&widget,0,&action)&&!deleted_count,66); + pause_owned=TRUE;mcc=FALSE; + CHECK(!fire(&widget,0,&action)&&!deleted_count,67); + mcc=TRUE;action.function=MCC_PAUSE_ACTION_FRIENDLY_FIRE+1; + CHECK(!mcc_ui_trusted_action(&widget,action.function)&&!fire(&widget,0,&action)&&!deleted_count,68);return 0; + } + if(!strcmp(argv[1],"isolation")){ + mcc=FALSE;action.flags=128;fire(&widget,0,&action);CHECK(legacy_count==1&&!revert_count,29); + mcc=TRUE;widget.definition_tag_index=101;fire(&widget,0,&action);CHECK(legacy_count==2&&!revert_count,30); + widget.definition_tag_index=200;action.function=256;fire(&widget,0,&action);CHECK(port_count==1,31); + widget.definition_tag_index=100;fire(&widget,0,&action);CHECK(port_count==1,32); + action.function=67;fire(&widget,0,&action);CHECK(legacy_count==2,33);return 0; + } + if(!strcmp(argv[1],"unsupported")){ + action.function=190;action.flags=140;action.widget_tag.index=300; + CHECK(!fire(&widget,0,&action)&&message_count==1&&!opened_count&&!deleted_count,34);return 0; + } + if(!strcmp(argv[1],"script")){ + action.function=0;action.flags=1024;strcpy(action.script,"my_action");fire(&widget,0,&action); + CHECK(script_count==1&&!revert_count&&!message_count,35);return 0; + } + return 98; +} +''' + work = tmp_path_factory.mktemp("mcc-ui") + path = work / "ui.c" + path.write_text(source) + executable = work / ("ui.exe" if os.name == "nt" else "ui") + command = [compiler, "-std=c99", str(path), "-o", str(executable)] + if os.name == "nt": + command[1:1] = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld", "-D_CRT_SECURE_NO_WARNINGS"] + result = subprocess.run(command, capture_output=True, text=True) + assert result.returncode == 0, result.stderr + return executable + + +@pytest.mark.parametrize("case", ["metadata", "confirmation", "client-denial", "no-checkpoint", "restart", + "quit", "team", "team-balance", "settings", "settings-uppercase", "save", "new-game", "isolation", "unsupported", "script", + "trusted-pause", "trusted-teams", "trusted-end", "trusted-settings", "friendly-fire", "trusted-isolation", "settings-namespace", + "split-resume", "split-team", "split-team-denied", "split-quit", "split-quit-sync", "local-quit", + "network-stale-solo", "campaign-stale-catalog", "settings-no-scenario", + "settings-controller", "settings-split-denied", "settings-busy", "settings-lifecycle", + "settings-open-failure", "settings-profile-fallback", "settings-replaced-editor", "settings-profile-reopen"]) +def test_mcc_widget_events(ui_tool, case): + result = subprocess.run([str(ui_tool), case], capture_output=True, text=True) + assert result.returncode == 0, (case, result.returncode, result.stdout, result.stderr) + + +def test_native_settings_admission_preserves_mcc_pause_ownership(tmp_path): + """Run the real pre-allocation route with stock, CE and MCC tag layouts. + + Stop at the allocation boundary: this checks which maps reach the native + builder and whether its campaign patch is enabled, without loading assets. + """ + compiler = shutil.which("clang") + if not compiler: + pytest.skip("clang is needed for native menu admission tests") + menu = (ROOT / "port/linux/game/menu_tags.c").read_text() + admission = function(menu, "menu_tags_loaded").split("\n\tmenus = ", 1)[0] + source = r''' +#include +#include +typedef int boolean; +#define FALSE 0 +#define NONE (-1) +#define MULTIPLAYER_COLLECTION "collection" +static int mcc, wants_settings, pc=1, campaign_tag, multiplayer_tag; +static int built, built_campaign; +static int frontend; +static int frontend_menu_requested(void){return frontend;} +static void frontend_menu_map_loaded(char const *name,int is_mcc){(void)name;(void)is_mcc;} +static int mcc_cache_tags_loaded(void){return mcc;} +static int mcc_ui_settings_needed(char const *name){(void)name;return wants_settings;} +static int network_coop_campaign_map(void){return 0;} +static int full_screen_campaign_map(void){return campaign_tag;} +static long tag_loaded(long group,char const *name){(void)group;(void)name;return multiplayer_tag?1:NONE;} +static int menus_pc_chosen(void){return pc;} +''' + admission + r''' + built++;built_campaign=campaign; +} +static void check(char const *name,int expected,int expected_campaign) +{ + built=0;built_campaign=0;menu_tags_loaded(name); + assert(built==expected);assert(built_campaign==expected_campaign); +} +int main(void) +{ + /* Upstream's stock/CE campaign Settings and normal menu route remain. */ + check("ui",1,0); + campaign_tag=1;check("a10",1,1);check("custom_maps\\a10",1,1); + campaign_tag=0;multiplayer_tag=1;check("bloodgulch",1,0); + pc=0;check("bloodgulch",0,0);check("ui",0,0);pc=1; + /* The latched frontend now supplies Settings during gameplay too. + Map-family pause roots and the MCC admission guard still own access. */ + frontend=1;pc=0;check("ui",1,0);check("bloodgulch",1,0); + campaign_tag=1;check("a10",1,1);check("custom_maps\\a10",1,1);pc=1; + /* MCC owns its campaign widgets, but requests native Settings with + either main-menu style, without the native campaign widget patch. */ + mcc=1;campaign_tag=1;multiplayer_tag=0; + check("mcc_maps\\a10",0,0); + wants_settings=1;check("mcc_maps\\a10",1,0); + pc=0;check("mcc_maps\\a10",1,0);pc=1; + /* MCC multiplayer retains native Settings without the campaign patch. */ + wants_settings=1;check("mcc_maps\\dangercanyon",1,0); + wants_settings=0;pc=0;check("mcc_maps\\dangercanyon",0,0); + return 0; +} +''' + path = tmp_path / "admission.c" + path.write_text(source) + exe = tmp_path / ("admission.exe" if os.name == "nt" else "admission") + flags = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld"] if os.name == "nt" else [] + result = subprocess.run([compiler, *flags, str(path), "-o", str(exe)], capture_output=True, text=True) + assert result.returncode == 0, result.stderr + result = subprocess.run([str(exe)], capture_output=True, text=True) + assert result.returncode == 0, result.stderr diff --git a/tools/test_mcc_ui_network.py b/tools/test_mcc_ui_network.py new file mode 100644 index 0000000000..1f3727726c --- /dev/null +++ b/tools/test_mcc_ui_network.py @@ -0,0 +1,580 @@ +"""Exercise the MCC restart transaction across the round-lifecycle boundary.""" +import os +from pathlib import Path +import shutil +import subprocess + +import pytest +from harness import function + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.fixture(scope="module") +def restart_tool(tmp_path_factory): + compiler = os.environ.get("CC") or shutil.which("clang") or shutil.which("cc") + if not compiler: + pytest.skip("a C compiler is needed") + directory = tmp_path_factory.mktemp("mcc_ui_network") + (directory / "mcc_cache.h").write_text("") + (directory / "mcc_share.h").write_text("") + (directory / "mcc_validation.h").write_text((ROOT / "port/linux/game/mcc_validation.h").read_text()) + (directory / "mcc_precache.h").write_text((ROOT / "port/linux/game/mcc_precache.h").read_text()) + (directory / "mcc_identity.h").write_text((ROOT / "port/linux/game/mcc_identity.h").read_text()) + implementation = (ROOT / "port/linux/game/mcc_ui_network.inl").read_text() + server_source = (ROOT / "source/networking/network_server_manager.c").read_text() + widget_source = (ROOT / "source/interface/ui_widget.c").read_text() + pregame = function(server_source, "network_game_server_idle_pregame_tasks") + # Keep the real countdown/start/heartbeat else-if chain: a mocked timer + # alone cannot expose a deferred start suppressing every keepalive. + heartbeat = pregame[pregame.index("\t\tif (server->countdown_state.active == TRUE)"): + pregame.index("\n\t}\n\telse if (server->time_of_first_client_loading_completion)")] + source = r''' +#include +#include +#include +#include +#include +typedef int boolean; +#define TRUE 1 +#define FALSE 0 +#define NONE (-1) +#define _error_silent 0 +boolean pc_menu_new_game_apply(void){return FALSE;} +#define NETWORK_SERVER_MANAGER_FILE "network_server_manager.c" +#define match_assert(file,line,condition) assert(condition) +#define MAXIMUM_NETWORK_PLAYER_COUNT 3 +#define MAXIMUM_NETWORK_MACHINE_COUNT 4 +#define TEST_FLAG(flags,bit) (((flags) & (1u << (bit))) != 0) +#define SET_FLAG(flags,bit,value) ((flags) = (value) ? ((flags) | (1u << (bit))) : ((flags) & ~(1u << (bit)))) +#define _network_client_machine_precached_bit 0 +#define csstrcmp strcmp +#define csmemcpy memcpy +#define csmemset memset +#define MILLISECONDS_PER_SECOND 1000 +enum { _network_game_server_state_pregame, _network_game_server_state_ingame, _network_game_server_state_postgame }; +struct network_player { int machine_index, controller_index, player_list_index, team_index; }; +struct network_game { + struct { int version; char name[128]; } map; + int variant, variant_options, cooperative_flags, minimum_players, maximum_players, maximum_teams, difficulty; + char name[32]; + struct network_player players[3]; + int number_of_games_played, local_data, machine_count; +}; +struct network_game_server_client_machine {int machine_index,flags,joined;}; +struct network_game_server { int state,sent_start_game_message; struct network_game game; + struct network_game_server_client_machine client_machines[4]; + struct {int timer;boolean active,paused,adjusted_time_this_tick;long last_countdown_message_time;} countdown_state; + long time_of_last_keep_alive; +} server,other_server; +static int exists=1,loaded=1,fail_reset,countdowns,opened,switched,reset,leaver; +static int splitscreen,quickstart,closed_ui,loaded_ui,errors; +static int client_exists=1,local_machine=NONE,map_changes; +static int validation=1,updates,cancels; +static unsigned long heartbeat_clock,last_heartbeat; +static int heartbeat_messages,start_attempts; +struct network_message {int unused;}; +struct message_server_pregame_countdown {short seconds_to_start;}; +struct message_server_pregame_keep_alive {long unused;}; +enum {_message_server_pregame_countdown,_message_server_pregame_keep_alive}; +static unsigned long system_milliseconds(void) {return heartbeat_clock;} +static boolean server_ok_to_countdown(struct network_game_server *s) {(void)s;return TRUE;} +static struct network_message *create_network_game_message(int kind,void *packet,unsigned long size) { + static struct network_message message;(void)kind;(void)packet;(void)size;return &message; +} +static boolean network_game_server_send_message_to_all_machines(struct network_game_server *s, + struct network_message *message) { + (void)s;(void)message;heartbeat_messages++;last_heartbeat=heartbeat_clock;return TRUE; +} +static void mcc_load_network_start(struct network_game const *game) {(void)game;} +static int download_active[4],download_needs[4]; +static int mcc_share_game_machine_active(long i) {return download_active[i];} +static int map_share_machine_needs_map(long i) {return download_needs[i];} +static int network_game_server_client_machine_is_joined_to_game(struct network_game_server *s, + struct network_game_server_client_machine *m) {(void)s;return m->joined;} +static int network_game_server_machine_has_players(struct network_game_server *s,long machine) { + int i;for(i=0;i<3;i++)if(s->game.players[i].machine_index==machine)return 1;return 0; +} +static int network_game_server_client_machine_is_local(struct network_game_server *s, + struct network_game_server_client_machine *m) {(void)s;return m->machine_index==0;} +static int halo_server_mode(void) {return 0;} +static int cache_files_precache_map_loaded(char const *name) {(void)name;return 1;} +int mcc_validation_request(char const *name,uint32_t *sum,unsigned char digest[32]) { + (void)name;(void)digest;if(sum)*sum=123;return validation; +} +int mcc_validation_lookup(char const *name,uint32_t *sum,unsigned char digest[32]) { + return mcc_validation_request(name,sum,digest)==1; +} +void mcc_validation_update(void) {updates++;} +void mcc_validation_cancel(void) {cancels++;} +char const *mcc_validation_error(void) {return "bad package";} +int mcc_identity_prepare_host(char const *name) {(void)name;return validation==1;} +void display_error_text_when_main_menu_loaded(wchar_t const *text) {(void)text;errors++;} +static struct network_game_server *selected_server=&server; +static struct network_game original; +static char map_name[128],screen_name[256]; +static struct network_game_server *global_network_game_server_get(void) {return exists ? selected_server : NULL;} +static void *global_network_game_client_get(void) {return client_exists ? &client_exists : NULL;} +static short network_game_client_get_local_machine_index(void) {return (short)local_machine;} +static void network_game_server_change_map_name(struct network_game_server *s,char const *name) { + strcpy(s->game.map.name,name);s->game.map.version=123;map_changes++; +} +static int mcc_cache_tags_loaded(void) {return loaded;} +static int mcc_level_name(char const *name) {return !strncmp(name,"mcc_maps\\",9);} +static int network_player_is_valid(struct network_player const *p) {return p->machine_index>=0;} +static void main_set_multiplayer_map_name(char const *name) {strcpy(map_name,name);} +static char const *main_get_multiplayer_map_name(void) {return server.game.map.name;} +static void network_game_server_open_game(struct network_game_server *s) {(void)s;opened++;} +static void third_person_session_lock(void) {} +static void network_game_server_switch_to_postgame(struct network_game_server *s) {s->state=_network_game_server_state_postgame;switched++;} +static void network_game_server_port_cooperative_won(char const *next) { + switched++;reset++;server.state=_network_game_server_state_postgame; + if(fail_reset)return; + server.game.number_of_games_played++; + if(next)strcpy(server.game.map.name,next); + server.state=_network_game_server_state_pregame; +} +static void network_event(char const *s) {(void)s;} +static void countdown_timer_set_time_remaining(int *timer,long ms) {*timer=(int)ms;} +static long countdown_timer_get_time_remaining(int *timer) {return *timer;} +static void network_game_server_countdown_started(struct network_game_server *s) { + assert(s->state==_network_game_server_state_pregame);countdowns++; +} +static void ui_widgets_close_all(void) {closed_ui++;} +static boolean network_game_is_splitscreen_local(void) {return splitscreen;} +static boolean network_game_is_quickstart_local(void) {return quickstart;} +static char const *pc_menus_screen(char const *name) {return name;} +static boolean ui_widget_load_by_name_or_tag(char const *name,long tag,void *parent,long controller,long a,long b,long c) { + (void)tag;(void)parent;(void)controller;(void)a;(void)b;(void)c; + strcpy(screen_name,name);loaded_ui++;return TRUE; +} +static void error(int priority,char const *text,...) {(void)priority;(void)text;errors++;} +boolean mcc_ui_network_restart_settings(struct network_game_server *s); +static int network_game_server_reset_to_pregame(struct network_game_server *s) { + int i;reset++; + memset(&s->countdown_state,0,sizeof(s->countdown_state)); + s->game.number_of_games_played++; + if(fail_reset)return 0; + s->game.local_data=0; + for(i=0;i<3;i++)s->game.players[i].team_index=1-s->game.players[i].team_index; + if(leaver)s->game.players[2].machine_index=-1; + if(!mcc_ui_network_restart_settings(s))exit(81); + /* Existing reset sends this exact state to every machine. */ + if(strcmp(s->game.map.name,original.map.name) || s->game.variant!=original.variant || + s->game.variant_options!=original.variant_options || s->game.difficulty!=original.difficulty || + s->game.cooperative_flags!=original.cooperative_flags || strcmp(s->game.name,original.name) || + s->game.map.version!=original.map.version || s->game.machine_count!=original.machine_count || + s->game.minimum_players!=original.minimum_players || s->game.maximum_players!=original.maximum_players || + s->game.maximum_teams!=original.maximum_teams)exit(82); + s->state=_network_game_server_state_pregame;return 1; +} +''' + '\n'.join(function(server_source, name) for name in [ + "network_game_server_pause_countdown", "network_game_server_begin_game_start_countdown", + "network_game_server_client_machine_is_precached", "network_game_server_have_all_machines_have_precached" + ]) + '\nstatic void network_game_server_start_now(struct network_game_server *s) {network_game_server_begin_game_start_countdown(s,0); }\n' + implementation + '\n' + function(widget_source, "network_game_reset_to_pregame_ui") + '\n' + ( + # Exercise the production early-return boundary without starting a world. + function(server_source, "network_game_server_start_network_game").split( + "if (server->sent_start_game_message")[0] + "start_attempts++;return FALSE;\n}\n" + ) + "static boolean heartbeat_tick(struct network_game_server *server) {\n" + ( + "long now=(long)heartbeat_clock;boolean success=TRUE;\n" + heartbeat + "\nreturn success;\n}\n" + ) + r''' +#define CHECK(c,n) do {if(!(c))return n;} while(0) +int main(int argc,char **argv) { + int i,result;struct network_game_server untouched; + if(argc!=2)return 99; + if(!strncmp(argv[1],"heartbeat-",10)) { + char const *mode=argv[1]+10; + server.state=_network_game_server_state_pregame;local_machine=0;validation=0; + strcpy(server.game.map.name,"levels\\test\\carousel\\carousel");server.game.map.version=123; + server.game.players[0].machine_index=0; + server.game.players[1].machine_index=server.game.players[2].machine_index=NONE; + for(i=0;i<4;i++){server.client_machines[i].machine_index=i;server.client_machines[i].flags=1;} + CHECK(mcc_ui_network_defer_map(&server,"mcc_maps\\Package\\mission"),110); + network_game_server_begin_game_start_countdown(&server,1000); + if(!strcmp(mode,"long")) { + server.countdown_state.timer=30000;mcc_ui_network_update_map(&server); + CHECK(server.countdown_state.timer==30000,111);return 0; + } + if(!strcmp(mode,"ce")||!strcmp(mode,"xbox")||!strcmp(mode,"cancel")|| + !strcmp(mode,"other-server")||!strcmp(mode,"disconnected")|| + !strcmp(mode,"started")||!strcmp(mode,"ingame")) { + if(!strcmp(mode,"ce"))CHECK(!mcc_ui_network_defer_map(&server,"custom_maps\\arena"),112); + if(!strcmp(mode,"xbox"))CHECK(!mcc_ui_network_defer_map(&server,"levels\\a10\\a10"),113); + if(!strcmp(mode,"cancel"))mcc_ui_network_server_dispose(&server); + if(!strcmp(mode,"other-server"))selected_server=&other_server; + if(!strcmp(mode,"disconnected"))client_exists=0; + if(!strcmp(mode,"started"))server.sent_start_game_message=1; + if(!strcmp(mode,"ingame"))server.state=_network_game_server_state_ingame; + mcc_ui_network_update_map(&server); + CHECK(server.countdown_state.timer==1000&&!mcc_ui_network_map_pending(&server),114);return 0; + } + if(!strcmp(mode,"failed")||!strcmp(mode,"failed-cancel"))validation=-1; + if(!strcmp(mode,"paused"))network_game_server_pause_countdown(&server,TRUE); + if(!strcmp(mode,"stopped"))server.countdown_state.active=FALSE; + CHECK(network_game_server_have_all_machines_have_precached(&server),115); + for(i=1;i<=40;i++) { + heartbeat_clock=(unsigned long)i*1000; + if(server.countdown_state.active && server.countdown_state.timer>0) + server.countdown_state.timer-=1000; + mcc_ui_network_update_map(&server);heartbeat_tick(&server); + CHECK(heartbeat_clock-last_heartbeat<=15000,116); + CHECK(!start_attempts&&!server.sent_start_game_message,117); + } + CHECK(heartbeat_messages>=6&&!map_changes,118); + if(!strcmp(mode,"paused")||!strcmp(mode,"stopped")) { + CHECK(!server.countdown_state.active,119); + CHECK(server.countdown_state.paused==!strcmp(mode,"paused"),120);return 0; + } + CHECK(heartbeat_messages>=15&&server.countdown_state.timer==3000,121); + if(validation<0) { + CHECK(errors==1,122); + if(!strcmp(mode,"failed-cancel")) { + CHECK(!mcc_ui_network_defer_map(&server,"custom_maps\\arena"),123); + server.countdown_state.timer=1000;mcc_ui_network_update_map(&server); + CHECK(!mcc_ui_network_map_pending(&server)&&server.countdown_state.timer==1000,124); + } + return 0; + } + validation=1;mcc_ui_network_update_map(&server); + CHECK(map_changes==1&&!mcc_ui_network_map_pending(&server),125); + if(!strcmp(mode,"revision")) { + /* A changed current package is unvalidated even without a deferred + * selection token; its timer must resume the same heartbeat path. */ + validation=0;server.countdown_state.timer=0;mcc_ui_network_update_map(&server); + CHECK(mcc_ui_network_map_pending(&server)&&server.countdown_state.timer==3000,126); + validation=1;mcc_ui_network_update_map(&server); + CHECK(!mcc_ui_network_map_pending(&server),127); + } + server.countdown_state.timer=0;heartbeat_tick(&server); + CHECK(start_attempts==1,128);return 0; + } + if(!strncmp(argv[1],"validation-",11)) { + char const *name="mcc_maps\\Package\\arena"; + server.state=_network_game_server_state_pregame;local_machine=0;validation=0; + if(!strcmp(argv[1],"validation-dedicated"))client_exists=0; + strcpy(server.game.map.name,"levels\\test\\bloodgulch\\bloodgulch"); + CHECK(mcc_ui_network_defer_map(&server,name)&&!updates,50); + CHECK(mcc_ui_network_map_pending(&server),51); + CHECK(network_game_server_start_network_game(&server)&&!server.sent_start_game_message,61); + mcc_ui_network_update_map(&server);CHECK(updates==1&&!map_changes,52); + if(!strcmp(argv[1],"validation-ready")||!strcmp(argv[1],"validation-dedicated")) { + validation=1;mcc_ui_network_update_map(&server); + CHECK(map_changes==1&&!mcc_ui_network_map_pending(&server),53); + mcc_ui_network_update_map(&server);CHECK(map_changes==1&&updates==1,54); + } else if(!strcmp(argv[1],"validation-failed")) { + validation=-1;for(i=0;i<10;i++)mcc_ui_network_update_map(&server); + CHECK(errors==1&&!map_changes&&updates==1,55); + CHECK(mcc_ui_network_map_pending(&server),56); + } else { + if(!strcmp(argv[1],"validation-gameplay"))server.state=_network_game_server_state_ingame; + else if(!strcmp(argv[1],"validation-started"))server.sent_start_game_message=1; + else if(!strcmp(argv[1],"validation-back"))mcc_ui_network_server_dispose(&server); + else if(!strcmp(argv[1],"validation-xbox"))CHECK(!mcc_ui_network_defer_map(&server,"levels\\a10\\a10"),57); + else if(!strcmp(argv[1],"validation-ce"))CHECK(!mcc_ui_network_defer_map(&server,"custom_maps\\arena"),58); + else return 59; + for(i=0;i<10;i++)mcc_ui_network_update_map(&server); + CHECK(updates==1&&!map_changes&&cancels>=2,60); + } + return 0; + } + if(!strncmp(argv[1],"map-",4)) { + char const *name="mcc_maps\\Package\\arena"; + server.state=_network_game_server_state_pregame; + strcpy(server.game.map.name,"levels\\test\\bloodgulch\\bloodgulch"); + untouched=server; + CHECK(mcc_ui_network_defer_map(&server,name),31); + CHECK(mcc_ui_network_map_pending(&server)&&!mcc_ui_network_map_pending(&other_server),32); + for(i=0;i<100;i++)mcc_ui_network_update_map(&server); + CHECK(!map_changes&&!memcmp(&server,&untouched,sizeof(server)),33); + if(!strcmp(argv[1],"map-replace")) { + name="mcc_maps\\Other\\arena";CHECK(mcc_ui_network_defer_map(&server,name),34); + } + if(!strcmp(argv[1],"map-xbox"))CHECK(!mcc_ui_network_defer_map(&server,"levels\\a10\\a10"),35); + if(!strcmp(argv[1],"map-ce"))CHECK(!mcc_ui_network_defer_map(&server,"custom_maps\\a10"),36); + if(!strcmp(argv[1],"map-dispose"))mcc_ui_network_server_dispose(&server); + if(!strcmp(argv[1],"map-no-client"))client_exists=0; + if(!strcmp(argv[1],"map-other-server"))selected_server=&other_server; + if(!strcmp(argv[1],"map-started"))server.sent_start_game_message=1; + if(!strcmp(argv[1],"map-ingame"))server.state=_network_game_server_state_ingame; + local_machine=0;mcc_ui_network_update_map(&server); + CHECK(!mcc_ui_network_map_pending(&server),37); + if(!strcmp(argv[1],"map-join")||!strcmp(argv[1],"map-replace")) { + CHECK(map_changes==1&&!strcmp(server.game.map.name,name),38); + CHECK(!mcc_ui_network_defer_map(&server,name),39); + } else CHECK(!map_changes,40); + mcc_ui_network_update_map(&server);CHECK(map_changes<=1,41); + client_exists=0;CHECK(!mcc_ui_network_defer_map(&server,name),42); + return 0; + } + server.state=_network_game_server_state_ingame; + strcpy(server.game.map.name,"mcc_maps\\a10");server.game.map.version=123; + strcpy(server.game.name,"MCC game"); + server.game.variant=atoi(argv[1])==1 ? 0 : 7; + server.game.variant_options=13;server.game.cooperative_flags=1; + server.game.minimum_players=2;server.game.maximum_players=16; + server.game.maximum_teams=2;server.game.difficulty=3; + server.game.number_of_games_played=4;server.game.local_data=1;server.game.machine_count=3; + for(i=0;i<3;i++) {server.game.players[i].machine_index=i;server.game.players[i].controller_index=0; + server.game.players[i].player_list_index=i;server.game.players[i].team_index=i%2;} + original=server.game; + + if(!strncmp(argv[1],"download-",9)) { + int expected=1; + char const *next="mcc_maps\\Package\\mission_two"; + local_machine=0;server.game.map.version=123; + for(i=0;i<4;i++){server.client_machines[i].machine_index=i;server.client_machines[i].flags=1; + server.client_machines[i].joined=1;} + if(!strcmp(argv[1],"download-campaign")) { + mcc_ui_network_campaign_won(next);loaded=0;network_game_reset_to_pregame_ui(); + CHECK(strstr(screen_name,"connected_pregame_screen")&&countdowns==1,90); + } else { + server.state=_network_game_server_state_pregame; + network_game_server_begin_game_start_countdown(&server,3000); + } + server.countdown_state.timer=1000; + download_active[1]=1;download_needs[1]=1;server.client_machines[1].flags=0; + server.game.players[1].machine_index=NONE;server.game.players[2].machine_index=NONE; + if(!strcmp(argv[1],"download-campaign"))server.game.players[1].machine_index=1; + if(!strcmp(argv[1],"download-admission"))download_needs[1]=0; + if(!strcmp(argv[1],"download-off")){download_active[1]=0;download_needs[1]=0;expected=0;} + if(!strcmp(argv[1],"download-ce")){strcpy(server.game.map.name,"custom_maps\\arena");expected=0;} + if(!strcmp(argv[1],"download-xbox")){strcpy(server.game.map.name,"levels\\test\\bloodgulch\\bloodgulch");expected=0;} + if(!strcmp(argv[1],"download-unjoined")){server.client_machines[1].joined=0;expected=0;} + if(!strcmp(argv[1],"download-ingame")){server.state=_network_game_server_state_ingame;expected=0;} + if(!strcmp(argv[1],"download-started")){server.sent_start_game_message=1;expected=0;} + if(!strcmp(argv[1],"download-other-server")){selected_server=&other_server;expected=0;} + if(!strcmp(argv[1],"download-long"))server.countdown_state.timer=30000; + if(!strcmp(argv[1],"download-paused"))network_game_server_pause_countdown(&server,TRUE); + if(!strcmp(argv[1],"download-stopped"))server.countdown_state.active=FALSE; + /* The real inherited predicate intentionally ignores a playerless + * downloader. The MCC barrier must prevent that from starting a load. */ + CHECK(network_game_server_have_all_machines_have_precached(&server),91); + mcc_ui_network_update_map(&server); + CHECK(!!mcc_ui_network_map_pending(&server)==expected,92); + if(!expected){CHECK(server.countdown_state.timer==1000&&countdowns==1,93);return 0;} + CHECK(network_game_server_start_network_game(&server)&&!server.sent_start_game_message,94); + if(!strcmp(argv[1],"download-long")){CHECK(server.countdown_state.timer==30000,95);return 0;} + if(!strcmp(argv[1],"download-paused")||!strcmp(argv[1],"download-stopped")){ + CHECK(!server.countdown_state.active&&countdowns==1,96); + CHECK(server.countdown_state.paused==!strcmp(argv[1],"download-paused"),104);return 0; + } + CHECK(server.countdown_state.active&&!server.countdown_state.paused&& + server.countdown_state.timer==3000&&countdowns==1,97); + for(i=0;i<8;i++){server.countdown_state.timer=2000;mcc_ui_network_update_map(&server);} + CHECK(server.countdown_state.timer==3000&&countdowns==1,98); + /* DONE permits AddPlayer but the short admission guard still holds + * this pre-load barrier. A valid player then resumes ordinary precache. */ + download_needs[1]=0;server.countdown_state.timer=1000;mcc_ui_network_update_map(&server); + CHECK(server.countdown_state.timer==3000&&mcc_ui_network_map_pending(&server),99); + download_active[1]=0;server.game.players[1].machine_index=1; + server.countdown_state.timer=2000;mcc_ui_network_update_map(&server); + CHECK(server.countdown_state.timer==2000&&!mcc_ui_network_map_pending(&server),100); + CHECK(!network_game_server_have_all_machines_have_precached(&server),101); + network_game_server_client_machine_is_precached(&server,&server.client_machines[1],"mcc_maps\\wrong"); + CHECK(!network_game_server_have_all_machines_have_precached(&server),102); + network_game_server_client_machine_is_precached(&server,&server.client_machines[1],server.game.map.name); + CHECK(network_game_server_have_all_machines_have_precached(&server),103); + return 0; + } + if(!strncmp(argv[1],"campaign-",9)) { + char const *next="mcc_maps\\Package\\mission_two"; + int refuse=0,fallback=0; + if(!strcmp(argv[1],"campaign-end")){next=NULL;fallback=1;} + if(!strcmp(argv[1],"campaign-failure")){fail_reset=1;fallback=1;} + if(!strcmp(argv[1],"campaign-xbox")){strcpy(server.game.map.name,"levels\\a10\\a10");refuse=1;} + if(!strcmp(argv[1],"campaign-ce")){strcpy(server.game.map.name,"custom_maps\\a10");refuse=1;} + if(!strcmp(argv[1],"campaign-target-xbox")){next="levels\\a30\\a30";refuse=1;} + if(!strcmp(argv[1],"campaign-inactive")){loaded=0;refuse=1;} + if(!strcmp(argv[1],"campaign-client")){exists=0;refuse=1;} + if(!strcmp(argv[1],"campaign-not-ingame")){server.state=_network_game_server_state_pregame;refuse=1;} + mcc_ui_network_campaign_won(next); + if(refuse){CHECK(!reset&&!switched&&!mcc_ui_network_restart_pregame(),70);return 0;} + CHECK(reset==1&&switched==1&&!countdowns,71); + if(fallback){ + CHECK(!mcc_ui_network_restart_pregame()&&!countdowns,72); + CHECK(!strcmp(server.game.map.name,original.map.name),73);return 0; + } + CHECK(!strcmp(server.game.map.name,next),74); + loaded=0; /* The intended unload must not invalidate the UI token. */ + if(!strcmp(argv[1],"campaign-checksum")){ + server.game.map.version++;local_machine=0; + CHECK(!mcc_ui_network_defer_map(&server,next),75); + } + if(!strcmp(argv[1],"campaign-dispose")){mcc_ui_network_server_dispose(&server);fallback=1;} + if(!strcmp(argv[1],"campaign-round")){server.game.number_of_games_played++;fallback=1;} + if(!strcmp(argv[1],"campaign-other-server")){selected_server=&other_server;fallback=1;} + if(!strcmp(argv[1],"campaign-reselect")){ + mcc_ui_network_defer_map(&server,"custom_maps\\arena"); + mcc_ui_network_defer_map(&server,next);fallback=1; + } + if(!strcmp(argv[1],"campaign-map")){strcpy(server.game.map.name,"mcc_maps\\different");fallback=1;} + if(!strcmp(argv[1],"campaign-state")){server.state=_network_game_server_state_ingame;fallback=1;} + if(fallback){ + CHECK(!mcc_ui_network_restart_pregame()&&!countdowns,76); + selected_server=&server;CHECK(!mcc_ui_network_restart_pregame(),77);return 0; + } + network_game_reset_to_pregame_ui(); + CHECK(closed_ui==1&&loaded_ui==1&&!errors&&countdowns==1,78); + CHECK(!server.countdown_state.paused&&server.countdown_state.active,79); + CHECK(strstr(screen_name,"connected_pregame_screen")&&!strstr(screen_name,"map_select"),80); + CHECK(!strcmp(server.game.map.name,next)&&!mcc_ui_network_restart_pregame(),81); + network_game_reset_to_pregame_ui(); + CHECK(server.countdown_state.paused&&strstr(screen_name,"map_select_postgame"),82); + return 0; + } + if(!strcmp(argv[1],"no-server"))exists=0; + if(!strcmp(argv[1],"inactive"))loaded=0; + if(!strcmp(argv[1],"xbox"))strcpy(server.game.map.name,"levels\\a10\\a10"); + if(!strcmp(argv[1],"ce"))strcpy(server.game.map.name,"custom_maps\\a10"); + if(!strcmp(argv[1],"pregame"))server.state=_network_game_server_state_pregame; + if(!strcmp(argv[1],"leaver"))leaver=1; + if(!strcmp(argv[1],"failure"))fail_reset=1; + if(!strcmp(argv[1],"dispose"))fail_reset=1; + if(!strcmp(argv[1],"splitscreen"))splitscreen=1; + untouched=server; + CHECK(!mcc_ui_network_restart_settings(NULL),1); + CHECK(!mcc_ui_network_restart_settings(&server),2); + result=mcc_ui_restart_network_game(); + if(!exists || !loaded || !mcc_level_name(untouched.game.map.name) || untouched.state==_network_game_server_state_pregame) { + CHECK(!result && !switched && !reset && !countdowns && !opened,3); + CHECK(!memcmp(&server,&untouched,sizeof(server)),4); + CHECK(!mcc_ui_network_restart_pregame(),15); + network_game_reset_to_pregame_ui(); + CHECK(closed_ui==1&&loaded_ui==1&&!countdowns,16); + if(exists)CHECK(server.countdown_state.paused&&strstr(screen_name,"map_select_postgame"),17); + else CHECK(strstr(screen_name,"connected_pregame_screen"),18); + return 0; + } + if(fail_reset) { + CHECK(!result && !countdowns && !opened,5); + CHECK(server.state==_network_game_server_state_postgame,6); + if(!strcmp(argv[1],"dispose")) { + mcc_ui_network_server_dispose(&server); + CHECK(!mcc_ui_network_restart_settings(&server),14); + server=untouched; + } + fail_reset=0;result=mcc_ui_restart_network_game(); + } + CHECK(result && !countdowns && opened==1,7); + CHECK(server.game.number_of_games_played==5 && !server.game.local_data,8); + CHECK(!strcmp(map_name,original.map.name),9); + CHECK(server.game.players[0].team_index==0 && server.game.players[1].team_index==1,10); + if(leaver)CHECK(server.game.players[2].machine_index==-1,11); + CHECK(!mcc_ui_network_restart_settings(&server),12); + CHECK(!mcc_ui_restart_network_game(),13); + /* Reliable messages are delivered later. The local client has unloaded + * the MCC map before this actual native UI transition executes. */ + loaded=0; + if(!strncmp(argv[1],"ui-",3)) { + struct network_game_server pending=server; + if(!strcmp(argv[1],"ui-dispose"))mcc_ui_network_server_dispose(&server); + if(!strcmp(argv[1],"ui-map"))strcpy(server.game.map.name,"mcc_maps\\different"); + if(!strcmp(argv[1],"ui-version"))server.game.map.version++; + if(!strcmp(argv[1],"ui-round"))server.game.number_of_games_played++; + if(!strcmp(argv[1],"ui-state"))server.state=_network_game_server_state_ingame; + if(!strcmp(argv[1],"ui-server"))selected_server=&other_server; + if(!strcmp(argv[1],"ui-exit"))exists=0; + CHECK(!mcc_ui_network_restart_pregame()&&!countdowns,19); + selected_server=&server;exists=1;server=pending; + CHECK(!mcc_ui_network_restart_pregame()&&!countdowns,20); + network_game_reset_to_pregame_ui(); + CHECK(server.countdown_state.paused&&strstr(screen_name,"map_select_postgame"),21); + return 0; + } + network_game_reset_to_pregame_ui(); + CHECK(closed_ui==1&&loaded_ui==1&&!errors&&countdowns==1,22); + CHECK(server.countdown_state.active&&!server.countdown_state.paused&&server.countdown_state.timer==3000,23); + CHECK(strstr(screen_name,splitscreen?"splitscreen_pregame_wrapper_normal":"connected_pregame_screen"),24); + CHECK(!strstr(screen_name,"map_select_postgame"),25); + CHECK(!mcc_ui_network_restart_pregame()&&countdowns==1,26); + if(!strcmp(argv[1],"second-round")) { + server.state=_network_game_server_state_ingame;loaded=1;original=server.game; + CHECK(mcc_ui_restart_network_game()&&countdowns==1&&server.game.number_of_games_played==6,27); + loaded=0;network_game_reset_to_pregame_ui(); + CHECK(countdowns==2&&closed_ui==2&&loaded_ui==2&&!server.countdown_state.paused,28); + } else if(!splitscreen) { + /* A subsequent ordinary End Game must return to its original map + * picker and pause the timer, not reuse an old restart token. */ + network_game_reset_to_pregame_ui(); + CHECK(server.countdown_state.paused&&!server.countdown_state.active&&countdowns==1,29); + CHECK(strstr(screen_name,"map_select_postgame"),30); + } + return 0; +} +''' + path = directory / "restart.c" + path.write_text(source) + executable = directory / ("restart.exe" if os.name == "nt" else "restart") + command = [compiler, "-std=c99", "-I", str(directory), str(path), "-o", str(executable)] + if os.name == "nt": + command[1:1] = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld", "-D_CRT_SECURE_NO_WARNINGS"] + result = subprocess.run(command, capture_output=True, text=True) + assert result.returncode == 0, result.stderr + return executable + + +@pytest.mark.parametrize("case", ["1", "2", "leaver", "failure", "dispose", "no-server", "inactive", "xbox", "ce", "pregame", + "splitscreen", "second-round", "ui-dispose", "ui-map", "ui-version", "ui-round", + "ui-state", "ui-server", "ui-exit", "map-join", "map-replace", + "map-xbox", "map-ce", "map-dispose", "map-no-client", + "map-other-server", "map-started", "map-ingame", + "validation-ready", "validation-dedicated", "validation-failed", "validation-gameplay", + "validation-started", "validation-back", "validation-xbox", "validation-ce"]) +def test_restart_transaction(restart_tool, case): + subprocess.run([str(restart_tool), case], check=True, capture_output=True) + + +@pytest.mark.parametrize("case", ["ready", "checksum", "end", "failure", "xbox", "ce", "target-xbox", + "inactive", "client", "not-ingame", "dispose", "round", "other-server", + "reselect", "map", "state"]) +def test_campaign_follow_on_lobby(restart_tool, case): + subprocess.run([str(restart_tool), "campaign-"+case], check=True, capture_output=True) + + +def test_prior_campaign_handoff_exposes_paused_map_picker(restart_tool, tmp_path): + source = (restart_tool.parent / "restart.c").read_text() + # Previously mcc_main called this shared transition directly. Keep the + # real UI dispatcher and reproduce that path without the MCC UI token. + original = function(source, "mcc_ui_network_campaign_won") + source = source.replace(original, "void mcc_ui_network_campaign_won(char const *next) {" + "network_game_server_port_cooperative_won(next);}\n") + path = tmp_path / "prior.c" + path.write_text(source) + executable = tmp_path / "prior.exe" + compiler = os.environ.get("CC") or shutil.which("clang") or shutil.which("cc") + command = [compiler, "-std=c99", "-I", str(restart_tool.parent), str(path), "-o", str(executable)] + if os.name == "nt": + command[1:1] = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld", "-D_CRT_SECURE_NO_WARNINGS"] + built = subprocess.run(command, capture_output=True, text=True) + assert built.returncode == 0, built.stderr + result = subprocess.run([str(executable), "campaign-ready"], capture_output=True, text=True) + assert result.returncode == 78, "The prior handoff must fail the ready-lobby/countdown assertion" + + +@pytest.mark.parametrize("case", ["initial", "campaign", "admission", "long", "paused", + "stopped", "off", "ce", "xbox", "unjoined", "ingame", "started", "other-server"]) +def test_download_preload_barrier(restart_tool, case): + subprocess.run([str(restart_tool), "download-"+case], check=True, capture_output=True) + + +@pytest.mark.parametrize("case", ["pending", "failed", "failed-cancel", "revision", "long", "paused", "stopped", + "cancel", "ce", "xbox", "other-server", "disconnected", "started", "ingame"]) +def test_pending_validation_preserves_heartbeat(restart_tool, case): + subprocess.run([str(restart_tool), "heartbeat-"+case], check=True, capture_output=True) + + +def test_without_barrier_playerless_downloader_does_not_hold_start(restart_tool, tmp_path): + source = (restart_tool.parent / "restart.c").read_text() + source = source.replace(function(source, "mcc_ui_network_download_pending"), + "static boolean mcc_ui_network_download_pending(struct network_game_server *s) {return FALSE;}\n") + path = tmp_path / "without_barrier.c" + path.write_text(source) + executable = tmp_path / "without_barrier.exe" + compiler = os.environ.get("CC") or shutil.which("clang") or shutil.which("cc") + command = [compiler, "-std=c99", "-I", str(restart_tool.parent), str(path), "-o", str(executable)] + if os.name == "nt": + command[1:1] = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld", "-D_CRT_SECURE_NO_WARNINGS"] + built = subprocess.run(command, capture_output=True, text=True) + assert built.returncode == 0, built.stderr + result = subprocess.run([str(executable), "download-initial"], capture_output=True, text=True) + assert result.returncode == 92, "Without the barrier a playerless downloader is omitted from pre-load readiness" diff --git a/tools/test_mcc_ui_teams.py b/tools/test_mcc_ui_teams.py new file mode 100644 index 0000000000..73b9b7bf2f --- /dev/null +++ b/tools/test_mcc_ui_teams.py @@ -0,0 +1,259 @@ +"""Exercise the real network settings handler and MCC's team-only ingress.""" +import os +from pathlib import Path +import shutil +import subprocess + +import pytest +from harness import function, structure + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.fixture(scope="module") +def teams_tool(tmp_path_factory): + compiler = os.environ.get("CC") or shutil.which("clang") or shutil.which("cc") + if not compiler: + pytest.skip("a C compiler is needed") + own = (ROOT / "port/linux/game/mcc_ui_teams.c").read_text() + native = (ROOT / "source/networking/network_server_message_handler.c").read_text() + engine = (ROOT / "source/game/game_engine.c").read_text() + slayer = (ROOT / "source/game/game_engine_slayer.c").read_text() + damage = function((ROOT / "source/objects/damage.c").read_text(), "object_damage_aftermath") + start = damage.index("{", damage.index("else if (game_engine_can_score())")) + end, depth = start + 1, 1 + while depth: + depth += (damage[end] == "{") - (damage[end] == "}") + end += 1 + no_statistics_branch = damage[start:end] + cache = (ROOT / "port/linux/game/mcc_cache.c").read_text() + source = r''' +#include +#include +#include +#include +typedef int boolean; +typedef uint16_t word; +#define TRUE 1 +#define FALSE 0 +#define NONE (-1) +#define NUMBEROF(a) (sizeof(a)/sizeof(*(a))) +#define VALID_INDEX(i,n) ((unsigned long)(i)<(unsigned long)(n)) +#define MAXIMUM_NUMBER_OF_PLAYERS 4 +#define NUMBER_OF_MULTIPLAYER_TEAMS 2 +#define HALO_PORT_NETWORK_GAME_MESSAGE_VERSION 12 +#define NETWORK_GAME_MESSAGE_VERSION HALO_PORT_NETWORK_GAME_MESSAGE_VERSION +#define _message_client_player_settings_request 16 +#define _network_game_packet_class_client_pregame 3 +#define HALO_PORT_MAXIMUM_NETWORK_PLAYERS 4 +#define DATUM_INDEX_TO_ABSOLUTE_INDEX(i) ((unsigned long)(i)&0xFFFF) +#define TEST_FLAG(v,b) ((v)&(1u<<(b))) +#define _object_die_act_of_god_no_statistics_bit 2 +#define _damage_no_statistics_bit 3 +#define _game_connection_network_server 2 +#define _game_connection_network_client 1 +#define _object_type_vehicle 1 +#define TICKS_PER_SECOND 30 +#define MIN(a,b) ((a)<(b)?(a):(b)) +#define MAX(a,b) ((a)>(b)?(a):(b)) +#define match_assert(file,line,condition) do{if(!(condition))exit(91);}while(0) +struct network_player {uint16_t name[12];short color,icon;char machine_index,controller_index,team_index,player_list_index;}; +struct network_game {struct {char name[128];} map;struct {struct {int teams;}universal_variant;}variant;struct network_player players[4];int machines[4];}; +struct network_game_server {int state;struct network_game game;}server; +struct network_game_server_client_machine {int index;}machine; +struct player_datum {int quit_out_of_game,team_index,unit_index;struct network_player network_player_data; + long quit_out_of_game_time,death_time,respawn_timer,respawn_penalty,multiplayer_special; + struct {int multiple_kills,kills_in_a_row;}statistics;}players[4]; +struct unit_datum {struct {unsigned damage_flags;}object;}units[4]; +struct object_datum {struct {int type;}object;}object; +static long player_handles[4]={0x10000,0x10001,0x10002,0x10003}; +static long unit_handles[4]={0x20000,0x20001,0x20002,0x20003}; +struct data_iterator {int i;long datum_index;}; +struct {int auto_team_balance,friendly_fire_penalty,infection_respawn_time;}options; +static boolean infection_enabled(void){return FALSE;} +static void game_modes_player_killed(long killer,long dead,boolean friendly){(void)killer;(void)dead;(void)friendly;} +static int player_data,mcc=1,bad_decode,legacy,send_count,kill_count,killed,decoded; +static int connection=2,score,death_broadcast,death_friendly,engine_active=1; +static long death_killer,death_object; +static struct network_player request; +static struct {int type;}scenario={1}; +#define global_scenario (&scenario) +static boolean mcc_cache_tags_loaded(void){return mcc;} +static short game_connection(void){return (short)connection;} +static struct player_datum *player_try_and_get(long index){unsigned long i=DATUM_INDEX_TO_ABSOLUTE_INDEX(index);return i<4&&player_handles[i]==index?&players[i]:NULL;} +static struct player_datum *player_get(long index){struct player_datum *p=player_try_and_get(index);if(!p)exit(92);return p;} +static struct unit_datum *unit_try_and_get(long index){unsigned long i=DATUM_INDEX_TO_ABSOLUTE_INDEX(index);return i<4&&unit_handles[i]==index?&units[i]:NULL;} +static int network_game_server_get_state(struct network_game_server *s,void *unused){(void)unused;return s->state;} +static struct network_game *network_game_server_get_game(struct network_game_server *s){return &s->game;} +static boolean mcc_level_name(char const *s){return !strncmp(s,"mcc_maps\\",9);} +static boolean decode_network_game_message(void *out,void const *wire,short *size,short *type,short *version,int cls){ + (void)wire;(void)size;decoded++;if(*type!=16||*version!=12||cls!=3)exit(80);memcpy(out,&request,sizeof(request));return !bad_decode; +} +static void *network_game_server_get_client_machine(struct network_game_server *s,struct network_game_server_client_machine *m,long *index){(void)s;*index=m->index;return m->index==-1?NULL:m;} +static boolean network_player_is_valid(struct network_player *p){return p->machine_index>=0;} +static void data_iterator_new(struct data_iterator *it,int data){(void)data;it->i=0;} +static void *data_iterator_next(struct data_iterator *it){if(it->i>=4)return NULL;it->datum_index=player_handles[it->i];return &players[it->i++];} +static void *game_variant_options_get(void); +#define game_variant_options_get() (&options) +static void unit_kill_no_statistics(long unit){struct unit_datum *p=unit_try_and_get(unit);if(!p)exit(93);p->object.damage_flags|=1u<<_object_die_act_of_god_no_statistics_bit;kill_count++;killed=(int)unit;} +static void network_event(char const *fmt,...){(void)fmt;} +static boolean network_game_server_lobby_is_open(struct network_game_server *s){legacy++;return s->state==0;} +static void network_game_server_clean_player_name(struct network_game_server *s,struct network_player *p,long slot){(void)s;(void)p;(void)slot;} +static boolean network_game_update_player(struct network_game *g,struct network_player *p){g->players[p->player_list_index]=*p;return TRUE;} +static boolean network_game_server_send_game_data_pregame(struct network_game_server *s){(void)s;send_count++;return TRUE;} +/* Native game-engine and Slayer callbacks below run unchanged. */ +static struct {struct {int respawn_time,respawn_time_growth,suicide_penalty,teams;}universal_variant;}global_variant; +static short game_engine_betrayal_penalty[4]; +static struct {struct {struct {int kill_in_order;}slayer;}game_engine_variant;}variant; +static struct {void (*player_killed_player)(long,long,long,boolean);}engine_callbacks; +#define game_engine (engine_active?&engine_callbacks:NULL) +static int network_game_distributed_client(void){return connection==1;} +static void network_distributed_player_killed(long *k,long *o,long d,boolean *f){(void)d;death_broadcast++;death_killer=*k;death_object=*o;death_friendly=*f;} +static long game_time_get(void){return 1000;} +static struct network_game_server *global_network_game_server_get(void){return connection==2?&server:NULL;} +static struct object_datum *object_get(long index){(void)index;return &object;} +static long player_index_from_unit_index(long unit){int i;for(i=0;i<4;i++)if(players[i].unit_index==unit)return player_handles[i];return NONE;} +struct damage_data {unsigned flags;}; +static void game_show_score_extended(long p,long m,long d){(void)p;(void)m;(void)d;} +static void multiplayer_message(long p,long m,long d){(void)p;(void)m;(void)d;} +static void update_speed_for_score(long d,long k){(void)d;(void)k;} +#define game_engine_get_variant() (&variant) +static void find_next_target(long p){(void)p;} +static void slayer_engine_adjust_score(long p,int amount){(void)p;score+=amount;} +enum {_game_engine_message_killed_by_unknown,_game_engine_message_killed_by_biped,_game_engine_message_killed_by_vehicle, +_game_engine_message_killed_by_self,_game_engine_message_killed_by_player,_game_engine_message_killed_by_friendly_fire, +_game_engine_message_quit,_game_engine_message_killed_friendly,_game_engine_message_multi_kill,_game_engine_message_triple_kill, +_game_engine_message_double_kill,_game_engine_message_five_kills_in_row,_game_engine_message_killed_enemy,_game_engine_message_ten_kills_in_a_row}; +#define _object_type_biped 0 +''' + structure(own, "mcc_team_respawn") + r''' +static struct mcc_team_respawn mcc_team_respawns[HALO_PORT_MAXIMUM_NETWORK_PLAYERS]; +''' + '\n'.join(function(own, n) for n in ["mcc_ui_teams_reset", "mcc_ui_team_respawn_track", "mcc_ui_team_respawn_damage", "mcc_ui_team_respawn_death", + "mcc_ui_team_balance_allows", "mcc_ui_team_request"]) + '\n' + function( + native, "network_game_server_handle_message_client_player_settings_request") + '\n' + function( + slayer, "slayer_engine_player_killed_player") + '\n' + function(engine, "game_engine_player_killed") + '\n' + \ + 'static void no_statistics_death(long object_index, struct damage_data *damage)\n' + no_statistics_branch + r''' +/* Exercise the actual MCC teardown, with resource releases reduced to fakes. */ +static struct {void *tags;unsigned capacity;}mcc_loaded_cache; +static int mcc_loaded; +static FILE *mcc_stream; +static void cleanup(void *unused){(void)unused;} +#define mcc_checkpoint_dispose() cleanup(NULL) +#define mcc_script_threads_dispose() cleanup(NULL) +#define mcc_validation_cancel() cleanup(NULL) +#define mcc_cache_validation_clear() cleanup(NULL) +#define mcc_cache_precache_clear() cleanup(NULL) + #define mcc_hud_glyphs_dispose() cleanup(NULL) +#define mcc_campaign_dispose() cleanup(NULL) +#define mcc_resources_dispose(p) cleanup(p) +#define mcc_grenades_reset() cleanup(NULL) +#define mcc_object_names_clear() cleanup(NULL) +#define mcc_parameters_dispose() cleanup(NULL) +#define mcc_texture_cache_dispose() cleanup(NULL) +#define mcc_geometry_dispose(p) cleanup(p) +#define mcc_audio_dispose(p) cleanup(p) +#define mcc_bitmaps_dispose(p) cleanup(p) +#define mcc_validation_dispose(p) cleanup(p) +#define mcc_memory_release(p,n) cleanup(p) +''' + function(cache, "mcc_cache_tags_unload") + r''' +#define CHECK(c,n) do{if(!(c)){fprintf(stderr,"check%d failed\n",n);return n;}}while(0) +int main(int argc,char **argv){ + word wire[18]={16};int i;short size=sizeof(wire);struct network_game before;struct player_datum prior[4]; + char const *test=argc>1?argv[1]:""; + ((unsigned char *)wire)[size-1]=16; + strcpy(server.game.map.name,"mcc_maps\\dangercanyon");server.game.variant.universal_variant.teams=TRUE;server.state=1;machine.index=2; + for(i=0;i<4;i++){server.game.players[i].machine_index=-1;players[i].quit_out_of_game=TRUE;players[i].unit_index=NONE;} + request=(struct network_player){{'A',0},2,3,2,1,0,1};server.game.players[1]=request; + players[1].quit_out_of_game=FALSE;players[1].team_index=0;players[1].unit_index=0x20001;players[1].network_player_data=request; + players[1].quit_out_of_game_time=NONE;engine_callbacks.player_killed_player=slayer_engine_player_killed_player; + global_variant.universal_variant.respawn_time=120; + request.team_index=1; + if(!strcmp(test,"non-mcc"))mcc=0; + if(!strcmp(test,"non-namespace"))strcpy(server.game.map.name,"custom_maps\\x"); + if(!strcmp(test,"pregame"))server.state=0; + if(!strcmp(test,"postgame"))server.state=2; + if(!strcmp(test,"no-teams"))server.game.variant.universal_variant.teams=FALSE; + if(!strcmp(test,"campaign"))scenario.type=0; + if(!strcmp(test,"unjoined"))machine.index=-1; + if(!strcmp(test,"malformed"))bad_decode=1; + if(!strcmp(test,"short"))size=1; + if(!strcmp(test,"negative"))size=-1; + if(!strcmp(test,"minimum"))size=-32768; + if(!strcmp(test,"oversized"))size=128; + if(!strcmp(test,"wrong-packet"))((unsigned char *)wire)[size-1]=15; + if(!strcmp(test,"machine"))machine.index=3; + if(!strcmp(test,"controller"))request.controller_index=2; + if(!strcmp(test,"bad-team"))request.team_index=2; + if(!strcmp(test,"bad-slot"))request.player_list_index=-1; + if(!strcmp(test,"unknown-slot"))request.player_list_index=2; + if(!strcmp(test,"name"))request.name[0]='B'; + if(!strcmp(test,"color"))request.color=4; + if(!strcmp(test,"icon"))request.icon=4; + if(!strcmp(test,"unknown-live"))players[1].network_player_data.controller_index=2; + if(!strcmp(test,"already-team"))request.team_index=0; + if(!strcmp(test,"dead"))players[1].unit_index=NONE; + if(!strcmp(test,"balance")){options.auto_team_balance=TRUE;players[0].quit_out_of_game=FALSE;players[0].team_index=1;} + before=server.game;memcpy(prior,players,sizeof(prior)); + CHECK(network_game_server_handle_message_client_player_settings_request(&server,&machine,wire,size),1); + if(!strcmp(test,"valid")||!strcmp(test,"dead")){ + CHECK(!legacy&&server.game.players[1].team_index==1&&players[1].team_index==1&&players[1].network_player_data.team_index==1,2); + CHECK(kill_count==(!strcmp(test,"valid")?1:0),3);if(kill_count)CHECK(killed==0x20001,4);return 0; + } + if(!strncmp(test,"death-",6)){ + long victim=player_handles[1],killer=victim,unit=unit_handles[1]; + struct damage_data cause={1u<<_damage_no_statistics_bit}; + CHECK(kill_count==1,9); + if(strcmp(test,"death-real-suicide"))mcc_ui_team_respawn_damage(victim,unit,TRUE); + if(!strcmp(test,"death-unload"))mcc_cache_tags_unload(); + if(!strcmp(test,"death-non-mcc"))mcc=FALSE; + if(!strcmp(test,"death-client"))connection=1; + if(!strcmp(test,"death-new-player")){player_handles[1]=0x30001;victim=killer=player_handles[1];} + if(!strcmp(test,"death-new-unit")){unit_handles[1]=0x40001;unit=players[1].unit_index=unit_handles[1];} + if(!strcmp(test,"death-deleted-unit"))unit_handles[1]=NONE; + if(!strcmp(test,"death-no-flag"))units[1].object.damage_flags=0; + if(!strcmp(test,"death-other-killer"))killer=player_handles[0]; + if(!strcmp(test,"death-no-engine")){ + engine_active=FALSE;no_statistics_death(unit,&cause);CHECK(!death_broadcast,16);engine_active=TRUE; + } + if(!strcmp(test,"death-neutral"))no_statistics_death(unit,&cause); + else game_engine_player_killed(killer,unit,victim,TRUE); + CHECK(death_broadcast==1&&players[1].death_time==1000&&players[1].respawn_timer==120,10); + if(!strcmp(test,"death-neutral")){ + CHECK(!score&&death_killer==NONE&&death_object==NONE&&!death_friendly,11); + game_engine_player_killed(killer,unit,victim,TRUE); + CHECK(score==-1&&death_killer==killer&&death_object==unit&&death_friendly,12); + }else if(!strcmp(test,"death-client"))CHECK(!score&&death_killer==killer,13); + else { + CHECK(score==-1&&death_killer==killer&&death_object==unit&&death_friendly,14); + if(!strcmp(test,"death-other-killer")){ + game_engine_player_killed(victim,unit,victim,TRUE); + CHECK(score==-2&&death_killer==victim,15); + } + } + return 0; + } + if(!strcmp(test,"pregame")){CHECK(legacy==1&&send_count==1&&!kill_count,5);return 0;} + CHECK(!memcmp(&before,&server.game,sizeof(before))&&!memcmp(prior,players,sizeof(prior))&&!kill_count,6); + if(!strcmp(test,"non-mcc")||!strcmp(test,"non-namespace")||!strcmp(test,"postgame"))CHECK(legacy==1,7); + else CHECK(!legacy,8); + return 0; +} +''' + work = tmp_path_factory.mktemp("mcc-ui-teams") + path = work / "teams.c" + path.write_text(source) + executable = work / ("teams.exe" if os.name == "nt" else "teams") + command = [compiler, "-std=c99", str(path), "-o", str(executable)] + if os.name == "nt": + command[1:1] = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld", "-D_CRT_SECURE_NO_WARNINGS"] + result = subprocess.run(command, capture_output=True, text=True) + assert result.returncode == 0, result.stderr + return executable + + +@pytest.mark.parametrize("case", ["valid", "dead", "non-mcc", "non-namespace", "pregame", "postgame", "no-teams", + "campaign", "unjoined", "malformed", "short", "negative", "minimum", "oversized", "wrong-packet", "machine", "controller", "bad-team", "bad-slot", "unknown-slot", "name", "color", "icon", + "unknown-live", "already-team", "balance", "death-neutral", "death-unload", "death-non-mcc", "death-client", + "death-new-player", "death-new-unit", "death-deleted-unit", "death-no-flag", "death-other-killer", "death-real-suicide", "death-no-engine"]) +def test_mcc_ingame_team_request(teams_tool, case): + result = subprocess.run([str(teams_tool), case], capture_output=True, text=True) + assert result.returncode == 0, (case, result.returncode, result.stdout, result.stderr) diff --git a/tools/test_mcc_validation.py b/tools/test_mcc_validation.py new file mode 100644 index 0000000000..8397aaefb7 --- /dev/null +++ b/tools/test_mcc_validation.py @@ -0,0 +1,293 @@ +"""MCC menu admission reuses only successful, unchanged package checksums.""" +from pathlib import Path +import re +import subprocess +import pytest +from harness import function +from test_mcc_identity import compile_tool + +ROOT = Path(__file__).resolve().parents[1] + + +def test_menu_validation_cache(tmp_path): + source = (ROOT / "port/linux/game/mcc_cache.c").read_text() + state = re.search(r"static struct \{.*?\} mcc_validation;", source, re.S) + declarations = state.group() + names = ["mcc_cache_validation_clear", "mcc_cache_probe"] + helpers = "\n".join(function(source, name) for name in names) + (tmp_path / "cseries.h").write_text("typedef int boolean;\ntypedef unsigned char byte;\n#define TRUE 1\n#define FALSE 0\n") + test = r''' +#include "cseries.h" +#include "mcc_precache.h" +#include "mcc_cache_format.h" +#include "mcc_errors.h" +#include +#include +#include +static int probes, valid=1, stamped=1, changing, prepares, identity_ok=1; +static struct mcc_precache_snapshot files; +static int mcc_validation_lookup(char const *name,uint32_t *checksum,unsigned char *digest) { + (void)name;(void)checksum;(void)digest;return 0; +} +int mcc_precache_snapshot(char const *name, struct mcc_precache_snapshot *out) { + (void)name; *out=files; return stamped; +} +static char const *mcc_identity_local_name(char const *name) {return name;} +static int mcc_identity_prepare_host(char const *name) {(void)name; prepares++;return identity_ok;} +static int mcc_identity_check(char const *name) {(void)name;return identity_ok;} +static FILE *mcc_open(char const *name, struct mcc_cache_source *s, struct mcc_cache_identity *i) { + (void)s;(void)i;return name && !strncmp(name,"mcc_maps/",9) ? (FILE *)1 : NULL; +} +static FILE *mcc_open_explain(char const *name, struct mcc_cache_source *s, struct mcc_cache_identity *i, + char *reason,size_t size) { + if(reason && size)reason[0]=0; + return mcc_open(name,s,i); +} +static int close_stub(FILE *f) {(void)f;return 0;} +#define fclose close_stub +static int mcc_resources_probe_explain(char const *name,struct mcc_cache_source const *s,uint32_t *checksum, + char *reason,size_t size) { + (void)name;(void)s;probes++;*checksum=123; + if(!valid && reason && size)snprintf(reason,size,"No matching sounds.map. Install its MCC package resources beside the level."); + if(changing)files.files[0].written_low++; + return valid; +} +''' + declarations + "\n" + helpers + r''' +/* This cache test supplies an already-complete lobby result. Incremental + * requests and cancellation are exercised separately below. */ +static int mcc_validation_request(char const *name,uint32_t *sum,unsigned char *digest) { + (void)digest;return mcc_cache_probe(name,NULL,sum,NULL,0); +} +''' + "\n".join(function(source, name) for name in + ["mcc_cache_checksum", "mcc_cache_present"]) + r''' +int main(void) { + char message[256],reason[320];uint32_t checksum;int i,old; + char const *name="mcc_maps/package/a10"; + assert(mcc_cache_checksum(name)==123);assert(probes==1 && prepares==1); + for(i=0;i<100;i++)assert(mcc_cache_present(name,123,message,sizeof(message))); + assert(probes==1); + strcpy(reason,"stale failure"); + assert(mcc_cache_probe(name,NULL,&checksum,reason,sizeof(reason))); + assert(!reason[0] && checksum==123 && probes==1); + assert(!mcc_cache_present(name,124,message,sizeof(message)));assert(probes==1); + assert(mcc_cache_checksum(name)==123);assert(probes==1 && prepares==2); + identity_ok=0;assert(!mcc_cache_present(name,123,message,sizeof(message))); + assert(!mcc_cache_checksum(name));identity_ok=1; + for(i=0;i +#include +#include +#include +static struct mcc_precache_snapshot stamps; +static int snapshots,change_at_snapshot; +static char redirected[128]; +void mcc_package_stage_redirect(char const *name,char const *directory) { + (void)name;snprintf(redirected,sizeof(redirected),"%s",directory ? directory : ""); +} +static int opened,closed,allocated,freed,steps,bad,unreadable,changes; +static int allocation_failed; +static void *check_allocate(size_t bytes) {return allocation_failed ? NULL : malloc(bytes);} +#define malloc check_allocate +struct mcc_resource_check {int step;}; +int mcc_package_name(char const *name,char *out) { + if(strncmp(name,"mcc_maps/",9)||strlen(name)>=64)return 0; + strcpy(out,name);return 1; +} +int mcc_precache_snapshot(char const *name,struct mcc_precache_snapshot *out) { + (void)name;if(++snapshots==change_at_snapshot)stamps.files[0].written_low++; + *out=stamps;return !unreadable; +} +static FILE *mcc_open_explain(char const *n,struct mcc_cache_source *s,struct mcc_cache_identity *i, + char *reason,size_t size) { + (void)n;(void)s;(void)i;(void)reason;(void)size;opened++;return tmpfile(); +} +static int close_file(FILE *f) {closed++;return fclose(f);} +#define fclose close_file +static struct mcc_resource_check *mcc_resources_check_begin(char const *n, + struct mcc_cache_source const *s,char *r,size_t z) { + (void)n;(void)s;(void)r;(void)z;allocated++;return calloc(1,sizeof(struct mcc_resource_check)); +} +static int mcc_resources_check_step(struct mcc_resource_check *c,uint32_t *sum,unsigned char *digest) { + steps++;if(bad)return -1; + if(++c->step<3)return 0; + *sum=123;memset(digest,42,32);if(changes)stamps.files[0].written_low++;return 1; +} +static int mcc_resources_check_paths(struct mcc_resource_check const *c,char paths[2][128]) { + (void)c;memset(paths,0,256); + snprintf(paths[1],128,"%s/sounds.map",redirected[0] ? redirected : "mcc_maps/p");return 1; +} +static void mcc_resources_check_end(struct mcc_resource_check *c) {if(c){freed++;free(c);}} +''' + (ROOT / "port/linux/game/mcc_validation.inl").read_text() + r''' +static void finish(char const *name) { + int i;assert(!mcc_validation_request(name,NULL,NULL)); + for(i=0;i<4;i++)mcc_validation_update(); + assert(mcc_validation_lookup(name,NULL,NULL)); +} +int main(void) { + char const *name="mcc_maps/p/a";uint32_t sum;unsigned char digest[32];char paths[2][128];int i,old; + assert(!mcc_validation_resources(name,paths)); + assert(!mcc_validation_request(name,NULL,NULL));assert(!opened&&!steps); + mcc_validation_update();assert(opened==1 && !steps); + if(worker_enabled) {worker_hold=1;mcc_validation_update();assert(!steps&&!closed);worker_hold=0;} + if(!worker_enabled) {mcc_validation_update();assert(steps==1 && !mcc_validation_lookup(name,NULL,NULL));} + mcc_validation_cancel();assert(closed==opened && freed==allocated); + /* Creating again does not accept the cancelled result. */ + finish(name);old=steps; + assert(mcc_validation_resources(name,paths) && !paths[0][0] && !strcmp(paths[1],"mcc_maps/p/sounds.map")); + assert(mcc_validation_request(name,&sum,digest)==1 && sum==123 && digest[31]==42); + mcc_validation_cancel();assert(mcc_validation_request(name,NULL,NULL)==1 && steps==old); + /* Every resource candidate, including absent overrides, is part of validity. */ + for(i=0;i> i) & 1 for i in range(width)) + + def bytes(self): + out = bytearray((len(self.bits) + 7) // 8) + for i, value in enumerate(self.bits): + out[i // 8] |= value << (i % 8) + return bytes(out) + + +def crc32(data): + crc = 0 + for value in data: + crc ^= value << 24 + for _ in range(8): + crc = ((crc << 1) ^ (0x04C11DB7 if crc & 0x80000000 else 0)) & 0xFFFFFFFF + return crc + + +def page(packet, sequence, flags, granule): + lacing = [255] * (len(packet) // 255) + [len(packet) % 255] + result = bytearray(b"OggS" + bytes([0, flags]) + struct.pack(" +#include +#include +#include "mcc_vorbis.h" +#define STB_VORBIS_HEADER_ONLY +#include "stb_vorbis.c" +int main(int argc,char **argv) { + FILE *file;unsigned char *bytes;long size;short *pcm=NULL; + uint32_t frames=0,rate=0;int channels=0,ok; + if(argc!=4)return 2; + file=fopen(argv[1],"rb");if(!file)return 3; + fseek(file,0,SEEK_END);size=ftell(file);rewind(file); + bytes=malloc(size);if(!bytes || fread(bytes,1,size,file)!=(size_t)size)return 4;fclose(file); + if(atoi(argv[3])) { + int error=0;stb_vorbis *v=stb_vorbis_open_memory(bytes,size,&error,NULL); + if(!v){free(bytes);return 1;} + channels=stb_vorbis_get_info(v).channels;rate=stb_vorbis_get_info(v).sample_rate; + pcm=calloc(512*channels,sizeof(short)); + frames=stb_vorbis_get_samples_short_interleaved(v,channels,pcm,512*channels); + ok=frames && stb_vorbis_get_error(v)==0;stb_vorbis_close(v); + } else ok=mcc_vorbis_decode(bytes,(uint32_t)size,1024,&pcm,&frames,&rate,&channels); + if(ok) {file=fopen(argv[2],"wb");if(!file)return 5; + fwrite(&frames,4,1,file);fwrite(&rate,4,1,file);fwrite(&channels,4,1,file); + fwrite(pcm,2,frames*channels,file);fclose(file);} + if(atoi(argv[3]))free(pcm);else mcc_vorbis_free(pcm); + free(bytes);return ok?0:1; +} +''') + exe = work / ("decoder.exe" if os.name == "nt" else "decoder") + flags = ["-target", "i686-pc-windows-msvc"] if os.name == "nt" else [] + subprocess.run([compiler, *flags, str(ROOT / "tools/mcc_loading_stub.c"), "-O2", "-Wno-deprecated-declarations", "-Wno-tautological-compare", + "-I", str(ROOT / "port/linux/game"), + "-I", str(ROOT / "port/third_party/stb_vorbis"), str(source), + str(ROOT / "port/linux/game/mcc_vorbis.c"), + str(ROOT / "port/third_party/stb_vorbis/stb_vorbis.c"), + *([] if os.name == "nt" else ["-lm"]), "-o", str(exe)], check=True, capture_output=True) + return exe + + +def decode(decoder, tmp_path, data, legacy=False): + source, target = tmp_path / "input.ogg", tmp_path / "out.pcm" + source.write_bytes(data) + result = subprocess.run([str(decoder), str(source), str(target), str(int(legacy))], capture_output=True) + assert result.returncode in (0, 1), result.stderr + return target.read_bytes() if result.returncode == 0 else None + + +@pytest.mark.parametrize("channels", [1, 2]) +@pytest.mark.parametrize("residue_type", [0, 1, 2]) +@pytest.mark.parametrize("empty_entries", [1, 625]) +def test_empty_residue_preserves_later_nonzero_pass(decoder, tmp_path, channels, residue_type, empty_entries): + expected = decode(decoder, tmp_path, stream(channels, residue_type, empty=False)) + assert expected is not None + assert struct.unpack_from(" +#include +#include +#include +#include "mcc_vorbis.h" +#define PIN(x,a,b) ((x)<(a)?(a):((x)>(b)?(b):(x))) +#define MCC_AUDIO_FRAME_LIMIT 0x1000000u +static void *tracked; +static int allocations,releases,fail_allocation; +static void *tracked_malloc(size_t size) { + unsigned char *allocation; + if(fail_allocation)return NULL; + if(tracked)exit(70); + allocation=malloc(size+16);if(!allocation)exit(71); + tracked=allocation+16;allocations++;return tracked; +} +static void tracked_free(void *pointer) { + /* A plain decoder pointer is rejected before any header is dereferenced. */ + if(pointer!=tracked || !tracked)exit(72); + free((unsigned char *)pointer-16);tracked=NULL;releases++; +} +#define malloc tracked_malloc +#define free tracked_free +''' + declarations + "\n" + tables + "\n" + routines + r''' +#undef malloc +#undef free +int main(int argc,char **argv) { + unsigned char raw[8]={0,0,1,0,2,0,3,0},bad_adpcm[36]={0}; + FILE *file;long size;unsigned char *bytes;struct mcc_pcm pcm; + if(argc!=2)return 2; + file=fopen(argv[1],"rb");if(!file)return 3; + fseek(file,0,SEEK_END);size=ftell(file);rewind(file);bytes=malloc(size); + if(!bytes || fread(bytes,1,size,file)!=(size_t)size)return 4;fclose(file); + if(!mcc_pcm_open(bytes,size,3,2,22050,&pcm) || !pcm.samples || !pcm.vorbis_owned)return 5; + /* This close must use the decoder's owner, with no tracked allocation. */ + mcc_pcm_close(&pcm);mcc_pcm_close(&pcm); + if(pcm.samples || allocations || releases)return 6; + if(!mcc_pcm_open(raw,8,0,1,22050,&pcm) || pcm.vorbis_owned || pcm.frames!=4)return 7; + mcc_pcm_close(&pcm);mcc_pcm_close(&pcm); + if(pcm.samples || allocations!=1 || releases!=1)return 8; + /* A post-allocation ADPCM failure must also return to the tracked owner. */ + bad_adpcm[2]=89; + if(mcc_pcm_open(bad_adpcm,36,1,1,22050,&pcm))return 9; + mcc_pcm_close(&pcm); + if(allocations!=2 || releases!=2 || tracked)return 10; + if(mcc_pcm_open(raw,8,3,2,22050,&pcm))return 11; + mcc_pcm_close(&pcm); + fail_allocation=1; + if(mcc_pcm_open(raw,8,0,1,22050,&pcm))return 12; + mcc_pcm_close(&pcm); + if(allocations!=2 || releases!=2 || tracked)return 13; + free(bytes);return 0; +} +''') + exe = work / ("allocator.exe" if os.name == "nt" else "allocator") + flags = ["-target", "i686-pc-windows-msvc"] if os.name == "nt" else [] + subprocess.run([compiler, *flags, str(ROOT / "tools/mcc_loading_stub.c"), "-O2", "-Wno-deprecated-declarations", "-Wno-tautological-compare", + "-I", str(ROOT / "port/linux/game"), str(source), + str(ROOT / "port/linux/game/mcc_vorbis.c"), + *([] if os.name == "nt" else ["-lm"]), "-o", str(exe)], check=True, capture_output=True) + return exe + + +def test_pcm_returns_to_its_own_allocator(allocator_decoder, tmp_path): + source = tmp_path / "input.ogg" + source.write_bytes(stream()) + subprocess.run([str(allocator_decoder), str(source)], check=True, capture_output=True) + + +@pytest.mark.parametrize("channels", [1, 2]) +@pytest.mark.parametrize("frames", [256, 280, 304, 320]) +def test_short_final_block_trims_preceding_overlap(decoder, tmp_path, channels, frames): + complete = decode(decoder, tmp_path, stream(channels=channels, transition=True, final_frames=320)) + assert complete is not None + actual = decode(decoder, tmp_path, stream(channels=channels, transition=True, final_frames=frames)) + assert actual is not None + assert struct.unpack_from(" +#include +#include +typedef int boolean; +typedef short director_perspective; +#define TRUE 1 +#define FALSE 0 +#define NONE -1 +#define MAXIMUM_WEAPONS_PER_UNIT 4 +#define MAXIMUM_NUMBER_OF_LOCAL_PLAYERS 4 +static int passenger_camera_enabled(short player) {(void)player;return 0;} +#define TEST_FLAG(v,b) (((v)&(1UL<<(b)))!=0) +#define TAG_BLOCK_GET_ELEMENT(b,i,t) (&((t *)(b)->address)[i]) +enum { _object_dead_bit, _object_mask_unit=2, _unit_seat_third_person_on_enter_bit=6, + _unit_seat_third_person_camera_bit=4, _unit_state_entering_seat=1, + _unit_state_exiting_seat=2, _director_perspective_third_person=1 }; +struct object_datum { long definition_index; struct {long parent_object_index; unsigned long damage_flags; short type;} object; }; +struct unit_datum {long definition_index; struct {long parent_object_index; unsigned long damage_flags; short type;} object; + struct {short current_weapon_index,current_zoom_level,parent_seat_index; + long weapon_object_indices[4];struct {short state;} animation;} unit;}; +struct weapon_datum {long definition_index;}; +struct weapon_definition {struct {unsigned long flags;} weapon;}; +struct unit_seat {unsigned long flags;}; +struct unit_definition {struct {struct {void *address;} seats;} unit;}; +static struct unit_datum units[2]; +static struct weapon_datum weapons[2]={{0},{1}}; +static struct weapon_definition definitions[2]; +static struct unit_seat seat; +static struct unit_definition unit_definition={{{&seat}}}; +static int active=1, reads; +static boolean mcc_cache_tags_loaded(void) {return active;} +static struct unit_datum *unit_try_and_get(long i) {++reads;return i==0x10000?&units[0]:NULL;} +static struct unit_datum *unit_get(long i) {return &units[i&1];} +static struct object_datum *object_get(long i) {return (struct object_datum *)&units[i&1];} +static struct unit_definition *unit_definition_get(long i) {(void)i;return &unit_definition;} +static struct weapon_datum *weapon_try_and_get(long i) {return i==0x20000?&weapons[0]:i==0x20001?&weapons[1]:NULL;} +static struct weapon_definition *weapon_definition_get(long i) {return &definitions[i];} +''' + function(adapter, "mcc_camera_weapon_following") + '\n' + function(director, "director_desired_perspective") + r''' +typedef void (*director_camera_update_proc)(void *,void *,void *); +struct first_person_camera {int unused;};struct following_camera {int unused;}; +struct director {short seat_state;director_camera_update_proc camera_proc;char camera_data[64];float camera_change_pause;}; +static struct director view; +static int changes, interpolated; +static int shoulder_enabled; +static boolean third_person_available(short p){(void)p;return shoulder_enabled&&units[0].object.parent_object_index==NONE;} +static void third_person_camera_update(void *a,void *b,void *c){(void)a;(void)b;(void)c;} +static void first_person_camera_update(void *a,void *b,void *c){(void)a;(void)b;(void)c;} +static void following_camera_update(void *a,void *b,void *c){(void)a;(void)b;(void)c;} +static void first_person_camera_new(struct first_person_camera *p){(void)p;} +static void following_camera_new(struct following_camera *p){(void)p;} +static struct director *director_get(short i){(void)i;return &view;} +static long player_control_get_unit_index(short i){(void)i;return 0x10000;} +static void director_set_camera(short i,director_camera_update_proc p,boolean interpolate){ + (void)i;view.camera_proc=p;++changes;interpolated=interpolate; +} +''' + function(director, "director_choose_game_perspective") + r''' +#define CHECK(v) do {if(!(v)){fprintf(stderr,"line %d\n",__LINE__);return 1;}} while(0) +int main(int argc,char **argv){ + director_perspective perspective; + int n; + if(argc!=2)return 2; + units[0].object.parent_object_index=NONE; + units[0].unit.current_zoom_level=NONE; + units[0].unit.weapon_object_indices[0]=0x20000; + units[0].unit.weapon_object_indices[1]=0x20001; + definitions[0].weapon.flags=0x20000UL; + view.camera_proc=first_person_camera_update; + if(!strcmp(argv[1],"flags")){ + CHECK(mcc_camera_weapon_following(0x10000)); + definitions[0].weapon.flags=0x10000;CHECK(!mcc_camera_weapon_following(0x10000)); + definitions[0].weapon.flags=0x40000;CHECK(!mcc_camera_weapon_following(0x10000)); + }else if(!strcmp(argv[1],"isolation")){ + active=0;CHECK(!mcc_camera_weapon_following(0x10000));CHECK(reads==0); + CHECK(!director_desired_perspective(0x10000,&perspective));CHECK(perspective==0); + active=1;CHECK(mcc_camera_weapon_following(0x10000)); + active=0;CHECK(!mcc_camera_weapon_following(0x10000)); + }else if(!strcmp(argv[1],"invalid")){ + CHECK(!mcc_camera_weapon_following(NONE));CHECK(!mcc_camera_weapon_following(0x30000)); + for(n=-2;n<=5;++n){units[0].unit.current_weapon_index=n; + CHECK(mcc_camera_weapon_following(0x10000)==(n==0));} + units[0].unit.current_weapon_index=0; + units[0].unit.weapon_object_indices[0]=NONE;CHECK(!mcc_camera_weapon_following(0x10000)); + units[0].unit.weapon_object_indices[0]=0x30000;CHECK(!mcc_camera_weapon_following(0x10000)); + }else if(!strcmp(argv[1],"lifecycle")){ + units[0].object.damage_flags=1;CHECK(!mcc_camera_weapon_following(0x10000)); + units[0].object.damage_flags=0;CHECK(mcc_camera_weapon_following(0x10000)); + units[0].unit.current_zoom_level=0;CHECK(!mcc_camera_weapon_following(0x10000)); + units[0].unit.current_zoom_level=NONE;CHECK(mcc_camera_weapon_following(0x10000)); + }else if(!strcmp(argv[1],"seats")){ + units[0].object.parent_object_index=1;units[1].object.type=1; + CHECK(!mcc_camera_weapon_following(0x10000)); + CHECK(!director_desired_perspective(0x10000,&perspective));CHECK(perspective==2); + seat.flags=1<<4;CHECK(director_desired_perspective(0x10000,&perspective));CHECK(perspective==2); + active=0;CHECK(director_desired_perspective(0x10000,&perspective));CHECK(perspective==2); + }else if(!strcmp(argv[1],"switch")){ + director_choose_game_perspective(0,FALSE); + CHECK(view.camera_proc==following_camera_update&&changes==1&&interpolated); + director_choose_game_perspective(0,FALSE);CHECK(changes==1); + units[0].unit.current_weapon_index=1;director_choose_game_perspective(0,FALSE); + CHECK(view.camera_proc==first_person_camera_update&&changes==2); + units[0].unit.current_weapon_index=0;director_choose_game_perspective(0,FALSE); + CHECK(view.camera_proc==following_camera_update&&changes==3); + active=0;director_choose_game_perspective(0,FALSE); + CHECK(view.camera_proc==first_person_camera_update&&changes==4); + }else if(!strcmp(argv[1],"shoulder")){ + shoulder_enabled=1; + director_choose_game_perspective(0,FALSE); + CHECK(view.camera_proc==following_camera_update); /* authored MCC camera wins */ + units[0].unit.current_weapon_index=1; + director_choose_game_perspective(0,FALSE);director_choose_game_perspective(0,FALSE); + CHECK(view.camera_proc==third_person_camera_update); + units[0].unit.current_weapon_index=0;director_choose_game_perspective(0,FALSE); + CHECK(view.camera_proc==following_camera_update); + active=0;director_choose_game_perspective(0,FALSE);director_choose_game_perspective(0,FALSE); + CHECK(view.camera_proc==third_person_camera_update); /* legacy maps keep optional shoulder view */ + shoulder_enabled=0;director_choose_game_perspective(0,FALSE); + CHECK(view.camera_proc==first_person_camera_update); + }else return 3; + return 0; +} +''' + path = work / "camera.c" + path.write_text(source) + exe = work / ("camera.exe" if sys.platform == "win32" else "camera") + command = [clang, "-std=gnu89", "-Wall", "-Wextra", "-Werror", str(path), "-o", str(exe)] + if sys.platform == "win32": + command[1:1] = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld"] + result = subprocess.run(command, capture_output=True, text=True) + assert result.returncode == 0, result.stderr + return exe + + +@pytest.mark.parametrize("case", ["flags", "isolation", "invalid", "lifecycle", "seats", "switch", "shoulder"]) +def test_weapon_camera(camera, case): + result = subprocess.run([str(camera), case], capture_output=True, text=True) + assert result.returncode == 0, result.stderr diff --git a/tools/test_mcc_web_storage.py b/tools/test_mcc_web_storage.py new file mode 100644 index 0000000000..7809b7e04d --- /dev/null +++ b/tools/test_mcc_web_storage.py @@ -0,0 +1,139 @@ +"""The real MCC browser adapter with a deterministic page/OPFS boundary. + +These tests exercise C ABI, quota and visibility decisions; actual OPFS durability +and cross-tab locks are checked separately in browser tests. +""" +from pathlib import Path +import json +import subprocess + +import pytest +from test_mcc_identity import compile_tool + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.fixture(scope="module") +def bridge_tool(tmp_path_factory): + work = tmp_path_factory.mktemp("mcc-web-storage") + (work / "emscripten").mkdir() + (work / "emscripten/threading.h").write_text( + "static int emscripten_futex_wait(void *p,int v,double t){(void)p;(void)v;(void)t;return 0;}\n") + (work / "emscripten.h").write_text("static double emscripten_get_now(void){return 0;}\n") + (work / "pthread.h").write_text( + "#ifndef _WIN32\n#include_next \n#else\n" + "typedef int pthread_mutex_t;\n#define PTHREAD_MUTEX_INITIALIZER 0\n" + "static int pthread_mutex_lock(pthread_mutex_t *p){(void)p;return 0;}\n" + "static int pthread_mutex_unlock(pthread_mutex_t *p){(void)p;return 0;}\n#endif\n") + (work / "unistd.h").write_text( + "#ifdef _WIN32\n#define lstat stat\n#define fileno _fileno\n#endif\n" + "static int fsync(int fd){return fd<0 ? -1 : 0;}\n") + source = work / "test.c" + source.write_text(r''' +#include "mcc_share_stage.h" +#include +#include +#include +#include +void web_mcc_share_io(struct mcc_share_io *); +uint64_t web_mcc_free_bytes(void); +int web_mcc_package_visible(char const *); +int web_mcc_directory_visible(char const *); +int web_mcc_remove_begin(char const *); +void web_mcc_remove_end(char const *); +static int calls,response=1,translated; +static uint64_t quota; +static char last_action[32],last_payload[34000]; +void platform_translate_path(char const *path,char *out,unsigned long size) { + unsigned i; + translated++; + if(strncmp(path,"d:\\",3)){fprintf(stderr,"native path translated twice\n");exit(5);} + snprintf(out,size,"/data/%s",path+3); + for(i=0;out[i];i++)if(out[i]=='\\')out[i]='/'; +} +void web_js_mcc_storage(char const *action,char const *payload,int *box,int generation) { + calls++;snprintf(last_action,sizeof(last_action),"%s",action);snprintf(last_payload,sizeof(last_payload),"%s",payload); + if(box[0]!=generation)exit(6); + box[2]=(int)(uint32_t)quota;box[3]=(int)(uint32_t)(quota>>32);box[1]=response; +} +void web_js_mcc_storage_fence(void){exit(7);} +int main(int argc,char **argv) { + static char const level[]="mcc_maps\\dl_0123456789abcdef0123\\m0"; + static char const directory[]="d:\\mcc_maps\\dl_0123456789abcdef0123"; + struct mcc_share_io io; + struct mcc_share_file file; + if(argc!=2)return 2; + if(!strcmp(argv[1],"quota")) { + response=0;if(web_mcc_free_bytes()!=0)return 10; + response=1;if(web_mcc_free_bytes()!=1)return 11; + quota=UINT64_C(10737418240);if(web_mcc_free_bytes()!=quota)return 12; + } else if(!strcmp(argv[1],"visibility")) { + response=0;if(!web_mcc_package_visible("mcc_maps\\manual\\m0")||calls)return 13; + if(web_mcc_package_visible(level)||calls!=1)return 14; + if(web_mcc_package_visible("mcc_maps\\DL_0123456789ABCDEF0123\\m0"))return 24; + if(web_mcc_directory_visible("/data/mcc_maps/dl_0123456789abcdef0123")||translated)return 15; + response=1;if(!web_mcc_package_visible(level))return 16; + if(!web_mcc_directory_visible(directory)||translated!=1)return 17; + if(!web_mcc_directory_visible("/data/mcc_maps/manual"))return 18; + } else if(!strcmp(argv[1],"begin")) { + memset(&io,0,sizeof(io));web_mcc_share_io(&io);memset(&file,0,sizeof(file)); + strcpy(file.leaf,"Metadata/Mission.json");file.size=123; + if(!io.direct || !io.direct->begin(directory,&file,1) || strcmp(last_action,"begin"))return 19; + puts(last_payload);return 0; + } else if(!strcmp(argv[1],"removal")) { + response=0;if(web_mcc_remove_begin("dl_0123456789abcdef0123"))return 20; + response=1;if(!web_mcc_remove_begin("dl_0123456789abcdef0123"))return 21; + web_mcc_remove_end("dl_0123456789abcdef0123");if(strcmp(last_action,"removeEnd"))return 22; + calls=0;if(web_mcc_remove_begin("../escape") || calls)return 23; + } else return 3; + puts("ok");return 0; +} +''') + return compile_tool(work, [source, ROOT / "port/web/src/web_mcc_storage.c"]) + + +@pytest.mark.parametrize("case", ["quota", "visibility", "removal"]) +def test_browser_storage_boundary(bridge_tool, case): + result = subprocess.run([str(bridge_tool), case], capture_output=True, text=True, timeout=10) + assert result.returncode == 0, result.stderr + assert result.stdout.strip() == "ok" + + +def test_download_journal_request_preserves_exact_paths(bridge_tool): + result = subprocess.run([str(bridge_tool), "begin"], capture_output=True, text=True, timeout=10) + assert result.returncode == 0, result.stderr + assert json.loads(result.stdout) == { + "folder": "dl_0123456789abcdef0123", + "files": [{"path": "Metadata/Mission.json", "size": 123}], + "companions": ["workshop_id.txt", "download.receipt"], + } + + +def test_uncommitted_package_is_unavailable_except_exact_validation_redirect(tmp_path): + source = tmp_path / "test.c" + source.write_text(r''' +#include "mcc_package.h" +#include +static int visible; +int web_mcc_package_visible(char const *name){(void)name;return visible;} +int main(void){ + char path[128]; + if(mcc_package_map_path("mcc_maps\\dl_0123456789abcdef0123\\m0",path))return 1; + if(mcc_package_resource_path("mcc_maps\\dl_0123456789abcdef0123\\m0",1,path))return 2; + mcc_package_stage_redirect("mcc_maps\\dl_0123456789abcdef0123\\m0","mcc_maps/dl_0123456789abcdef0123"); + if(!mcc_package_map_path("mcc_maps\\dl_0123456789abcdef0123\\m0",path))return 3; + if(!mcc_package_resource_path("mcc_maps\\dl_0123456789abcdef0123\\m0",1,path))return 4; + if(mcc_package_map_path("mcc_maps\\dl_0123456789abcdef0123\\m1",path))return 5; + mcc_package_stage_redirect(0,0); + if(mcc_package_map_path("mcc_maps\\dl_0123456789abcdef0123\\m0",path))return 6; + visible=1; + if(!mcc_package_map_path("mcc_maps\\dl_0123456789abcdef0123\\m0",path))return 7; + return 0; +} +''') + wrapper = tmp_path / "package.c" + wrapper.write_text('#define HALO_WEB 1\n#include "' + + (ROOT / "port/linux/game/mcc_package.c").as_posix() + '"\n') + tool = compile_tool(tmp_path, [source, wrapper]) + result = subprocess.run([str(tool)], capture_output=True, text=True, timeout=10) + assert result.returncode == 0, result.stderr diff --git a/tools/test_mcc_workshop.py b/tools/test_mcc_workshop.py new file mode 100644 index 0000000000..3afea70378 --- /dev/null +++ b/tools/test_mcc_workshop.py @@ -0,0 +1,152 @@ +"""The Workshop item id and title travel in the map name's unused bytes; joiners are told which item.""" +from pathlib import Path +import subprocess +from test_mcc_identity import compile_tool + +ROOT = Path(__file__).resolve().parents[1] + + +def test_workshop_identity(tmp_path): + (tmp_path / "cseries.h").write_text( + "#include \ntypedef int boolean;\ntypedef unsigned char byte;\n") + source = tmp_path / "test.c" + source.write_text(r''' +#include "cseries.h" +#include "mcc_workshop.h" +#include +#include +static char steam_title[64]; +boolean mcc_maps_workshop_title(char const *id,char *title,unsigned size){ + if(strcmp(id,"2899609719") || !steam_title[0])return 0; + snprintf(title,size,"%s",steam_title);return 1; +} +#define CHECK(x) do{if(!(x)){fprintf(stderr,"line %d: %s\n",__LINE__,#x);return 1;}}while(0) +int main(void) { + struct mcc_workshop_item item,back;char name[128],text[256],folder[64],title[MCC_WORKSHOP_TITLE_SIZE]; + /* the sidecar: id, optional title; nothing else is an id */ + CHECK(mcc_workshop_parse_sidecar("2899609719\r\nBetter Creek\r\n",&item)); + CHECK(!strcmp(item.id,"2899609719") && !strcmp(item.title,"Better Creek")); + CHECK(mcc_workshop_parse_sidecar("42",&item) && !item.title[0]); + CHECK(!mcc_workshop_parse_sidecar("",&item)); + CHECK(!mcc_workshop_parse_sidecar("12ab",&item)); + CHECK(!mcc_workshop_parse_sidecar("123456789012345678901",&item)); + CHECK(!mcc_workshop_parse_sidecar("..\\evil",&item)); + /* a package folder named by an item id is that item; its title is Steam's when this machine has the item */ + CHECK(mcc_workshop_local_item("mcc_maps\\2899609719\\pat_beavercreek",&item) && !strcmp(item.id,"2899609719")); + CHECK(!strcmp(item.title,"Pat Beavercreek")); + strcpy(steam_title,"Pro Edition \xc3\xa9 of Halo"); + CHECK(mcc_workshop_local_item("mcc_maps\\2899609719\\pat_beavercreek",&item) && !strcmp(item.title,"Pro Edition of Halo")); + steam_title[0]=0; + CHECK(!mcc_workshop_local_item("mcc_maps\\notitem\\pat_beavercreek",&item)); + /* package folders */ + CHECK(mcc_workshop_package_folder("mcc_maps\\2899609719\\pat_beavercreek",folder) && !strcmp(folder,"2899609719")); + CHECK(!mcc_workshop_package_folder("mcc_maps\\a10",folder)); + CHECK(!mcc_workshop_package_folder("maps\\a\\b",folder)); + mcc_workshop_title_from_level("mcc_maps\\x\\pat_beavercreek",title); + CHECK(!strcmp(title,"Pat Beavercreek")); + /* the wire: a name's first 64 bytes are untouched, older builds read the same name */ + memset(name,0,sizeof(name));strcpy(name,"mcc_maps\\2899609719\\pat_beavercreek"); + strcpy(item.id,"2899609719");strcpy(item.title,"Better Creek"); + mcc_workshop_wire_pack(name,&item); + CHECK(!strcmp(name,"mcc_maps\\2899609719\\pat_beavercreek")); + CHECK(mcc_workshop_wire_unpack(name,&back) && !strcmp(back.id,item.id) && !strcmp(back.title,item.title)); + /* longest id and title still fit and end in the field */ + memset(item.id,'7',20);item.id[20]=0;memset(item.title,'T',39);item.title[39]=0; + mcc_workshop_wire_pack(name,&item); + CHECK(mcc_workshop_wire_unpack(name,&back) && !strcmp(back.id,item.id) && strlen(back.title)==39); + /* no id: the tail is cleared, and unpack finds nothing */ + memset(&item,0,sizeof(item));memset(name+64,0x55,64); + mcc_workshop_wire_pack(name,&item); + CHECK(!name[64] && !mcc_workshop_wire_unpack(name,&back)); + /* hostile tails are ignored */ + memset(name+64,0x41,64);CHECK(!mcc_workshop_wire_unpack(name,&back)); + memcpy(name+64,"WS\1" "12x",7);memset(name+71,0,57);CHECK(!mcc_workshop_wire_unpack(name,&back)); + memset(name+64,0,64);memcpy(name+64,"WS\1",3);memset(name+67,'1',61);CHECK(!mcc_workshop_wire_unpack(name,&back)); + /* the texts */ + strcpy(item.id,"2899609719");strcpy(item.title,"Better Creek"); + mcc_workshop_refusal_text(MCC_WORKSHOP_MISSING,&item,"pat_beavercreek",text,sizeof(text)); + CHECK(!strcmp(text,"No identified local copy of Better Creek (Steam Workshop item 2899609719). " + "Download the host's version and copy its map and required resources into mcc_maps.")); + mcc_workshop_refusal_text(MCC_WORKSHOP_DIFFERS,&item,"pat_beavercreek",text,sizeof(text)); + CHECK(!strcmp(text,"Your local package for Better Creek (Steam Workshop item 2899609719) does not match the host. " + "Check versions and copy the matching map and required resources into mcc_maps.")); + item.title[0]=0; + mcc_workshop_refusal_text(MCC_WORKSHOP_MISSING,&item,"pat_beavercreek",text,sizeof(text)); + CHECK(strstr(text,"No identified local copy of Pat Beavercreek")); + mcc_workshop_refusal_text(MCC_WORKSHOP_NOT_WORKSHOP,&item,"pat_beavercreek",text,sizeof(text)); + CHECK(strstr(text,"pat_beavercreek.map") && strstr(text,"SHA-256")); + /* Long metadata still leaves the actionable installation instruction. */ + memset(item.id,'7',20);item.id[20]=0;memset(item.title,'T',39);item.title[39]=0; + mcc_workshop_refusal_text(MCC_WORKSHOP_DIFFERS,&item,"level",text,sizeof(text)); + CHECK(strstr(text,"resources into mcc_maps.") && strlen(text)\ntypedef int boolean;\ntypedef unsigned char byte;\n") + (tmp_path / "stdio.h").write_text( + '#include_next \nFILE *workshop_test_fopen(char const *,char const *);\n' + '#define fopen workshop_test_fopen\n') + for folder, contents in { + "Named": b"2899609719\r\nBetter Creek\r\n", + "12345": b"67890\nSidecar wins\n", + "Bad": b"not-an-id\n", + "42": b"not-an-id\n", + "TitleOnly": b"\nNot an ID\n", + "Long": b"7\n" + b"T" * 300, + "IdOnly": b"2899609719\n", + }.items(): + package = tmp_path / "mcc_maps" / folder + package.mkdir(parents=True) + (package / "workshop_id.txt").write_bytes(contents) + source = tmp_path / "sidecar.c" + source.write_text(r''' +#include "mcc_workshop.h" +#include +#include +#undef fopen +#define CHECK(x) do{if(!(x)){fprintf(stderr,"line %d: %s\n",__LINE__,#x);return 1;}}while(0) +FILE *workshop_test_fopen(char const *path,char const *mode) { + char local[160];unsigned i; + if(strncmp(path,"d:\\mcc_maps\\",12))return NULL; + for(i=3;path[i] && i-3 +#include +#include +#include +#include +typedef int boolean; +#define TRUE 1 +#define FALSE 0 +#define NONE (-1) +#define BUTTON_X 2 +#define SOUND_BACK 1 +#define SOUND_FORWARD 2 +#define NUMBER_OF_GAME_DIFFICULTY_LEVELS 4 +#define MCC_MAPS_FIRST_DISPLAY_INDEX 0x1000 +#define NUMBEROF(a) (sizeof(a)/sizeof((a)[0])) +#define MIN(a,b) ((a)<(b)?(a):(b)) +#define PIN(x,a,b) ((x)<(a)?(a):(x)>(b)?(b):(x)) +#define FRONTEND_MENU_XBOX "ui\\shell\\main_menu\\main_menu" +struct widget_instance { + long definition_tag_index;const char *name;short local_player_index;int visible; + short horizontal_offset,vertical_offset; + struct widget_instance *parent,*child,*next,*previous,*focused_child; + struct {short current_frame_index;} animation; + struct {struct {short selected_index;} list;} parameters; +}; +struct event_record {short type,controller_index;struct {struct {int index,value;} button;} data;}; +struct player_profile {int unused;}; +struct mcc_map_browser {short count,chosen;int campaign;char package[64];}; +static int available=1,main_menu=1,enabled=1,backs,starts,rescans,native_calls,mp_choices; +static const char *style="xbox",*root_tag=FRONTEND_MENU_XBOX; +static long active_profile=2; +static short started_skill; +static char opened[256],started[64]; +static struct widget_instance entry; +static int frontend_menu_available(void){return available;} +static int main_menu_is_active(void){return main_menu;} +static const char *frontend_menu_style(void){return style;} +static int config_boolean(const char *key){(void)key;return enabled;} +static const char *tag_get_name(long tag){return tag==0?root_tag:tag==1?"pc\\mcc_xbox\\card_0":tag==2?"pc\\mcc_xbox\\card_1":"pc\\mcc_xbox\\card_2";} +static struct widget_instance *screen_of(struct widget_instance *w){while(w->parent)w=w->parent;return w;} +static struct widget_instance *named(struct widget_instance *w,const char *name,int n){ + struct widget_instance *c,*found;(void)n;if(!w)return NULL; + for(c=w->child;c;c=c->next){if(!strcmp(c->name,name))return c;found=named(c,name,0);if(found)return found;}return NULL; +} +static struct widget_instance *ui_widget_load_by_name_or_tag(const char *name,long tag,struct widget_instance *parent,short player,long a,long b,short c){ + (void)tag;(void)player;(void)a;(void)b;(void)c;strcpy(opened,name);memset(&entry,0,sizeof(entry));entry.parent=parent;entry.name="campaign_entry";return &entry; +} +static int ui_widget_port_open(struct widget_instance *w,const char *path,boolean *deleted){(void)w;strcpy(opened,path);*deleted=1;return 1;} +static void ui_widget_port_go_back(struct widget_instance *w){(void)w;backs++;} +static short ui_widget_port_list_index(struct widget_instance *w){return w?w->parameters.list.selected_index:-1;} +static void text_set(struct widget_instance *w,const wchar_t *text){(void)w;(void)text;} +static void text_set_length(struct widget_instance *w,const wchar_t *text,short n){(void)n;text_set(w,text);} +static void visible_set(struct widget_instance *w,int visible){if(w)w->visible=visible;} +static int usnprintf(wchar_t *out,int n,const wchar_t *format,...){(void)n;(void)format;out[0]=0;return 0;} +static void mcc_maps_rescan(void){rescans++;} +static void mcc_map_browser_open(struct mcc_map_browser *b,int campaign){b->count=1;b->chosen=0;b->campaign=campaign;} +static void mcc_map_browser_select(struct mcc_map_browser *b,short row){assert(row>=0&&rowcount);b->chosen=row;} +static int mcc_map_browser_enter(struct mcc_map_browser *b,short row){if(b->package[0]||row>=b->count)return 0;strcpy(b->package,"pkg");b->count=4;b->chosen=0;return 1;} +static int mcc_map_browser_back(struct mcc_map_browser *b){if(!b->package[0])return 0;b->package[0]=0;b->count=1;b->chosen=0;return 1;} +static short mcc_map_browser_index(struct mcc_map_browser *b,short row){return b->package[0]&&row>=0&&rowcount?row:-1;} +static void mcc_map_browser_text(struct mcc_map_browser *b,short row,wchar_t text[64]){(void)b;(void)row;wcscpy(text,L"Mission");} +static const char *mcc_maps_level_name(short i){return i>=0&&i<4?"mcc_maps\\pkg\\a10":NULL;} +static const wchar_t *mcc_maps_description(short i){(void)i;return L"Description";} +static unsigned mcc_progress_flags(long p,const char *level){assert(p==2&&level);return 10;} +static long player_ui_get_active_player_profile_index(short p){assert(p==0);return active_profile;} +static int player_profile_get(long p,struct player_profile *profile){(void)profile;return p==2;} +static int game_function(const char *name,struct widget_instance *w,struct event_record *e,boolean *deleted){(void)w;(void)e;(void)deleted;assert(strstr(name,"controller")||strstr(name,"prof"));native_calls++;return 1;} +static void ui_play_audio_feedback_sound(short s){(void)s;} +static int campaign_fail(void){return 0;} +static void campaign_start(const char *level,short skill,short controller){assert(controller==0);strcpy(started,level);started_skill=skill;starts++;} +static int ui_widget_port_mcc_multiplayer_map_choose(const char *level){assert(!strncmp(level,"mcc_maps\\",9));mp_choices++;return 1;} +''' + body + r''' +int main(void){ + struct widget_instance root={0},children[12]={{0}},cards[3]={{0}},parts[3][6]={{{0}}}; + struct widget_instance menu={0},rows[3]={{0}}; + const char *names[]={"heading_campaigns","heading_levels","heading_maps","heading_difficulty","previous","next","difficulty_list","status"}; + const char *leaves[]={"picture","mcc_folder_name","mcc_folder_help","badge_0","badge_1","badge_2"}; + struct event_record event={3,0,{{2,1}}};int deleted=0,i,j; + root.child=children;for(i=0;i<8;i++){children[i].name=names[i];children[i].parent=&root;children[i].next=i<7?children+i+1:cards;} + for(i=0;i<3;i++){cards[i].name=i==0?"card_0":i==1?"card_1":"card_2";cards[i].definition_tag_index=i+1;cards[i].parent=&root;cards[i].next=i<2?cards+i+1:NULL;cards[i].child=parts[i]; + for(j=0;j<6;j++){parts[i][j].name=leaves[j];parts[i][j].parent=cards+i;parts[i][j].next=j<5?parts[i]+j+1:NULL;}} + assert(!mcc_xbox_shortcut(&root,&event)); + assert(mcc_xbox_event("open",&root,&event,&deleted)&&!strcmp(opened,"pc\\mcc_xbox\\profiles")); + event.data.button.value=2;assert(!mcc_xbox_shortcut(&root,&event));event.data.button.value=1; + style="modern";assert(!mcc_xbox_shortcut(&root,&event));style="xbox"; + enabled=0;assert(!mcc_xbox_shortcut(&root,&event));enabled=1; + main_menu=0;assert(!mcc_xbox_shortcut(&root,&event));main_menu=1; + root_tag="pc\\main_menu\\main_menu";assert(!mcc_xbox_shortcut(&root,&event)); + root_tag=FRONTEND_MENU_XBOX; + root.child=&menu;menu.name="main_menu_select_list";menu.parent=&root;menu.child=rows;menu.focused_child=rows; + for(i=0;i<3;i++){rows[i].name=i==0?"load_campaign_item_":i==1?"multiplayer_item":"settings_item"; + rows[i].parent=&menu;rows[i].previous=i?rows+i-1:NULL;rows[i].next=i<2?rows+i+1:NULL;rows[i].horizontal_offset=192;rows[i].vertical_offset=247+i*36;} + enabled=0;mcc_xbox_attach(&root);assert(rows[0].next==rows+1&&rows[1].vertical_offset==283);enabled=1; + style="modern";mcc_xbox_attach(&root);assert(rows[0].next==rows+1);style="xbox"; + mcc_xbox_attach(&root);assert(rows[0].next==&entry&&entry.previous==rows&&entry.next==rows+1&&rows[1].previous==&entry); + assert(entry.parent==&menu&&entry.horizontal_offset==192&&entry.vertical_offset==283); + assert(rows[0].vertical_offset==247&&rows[1].vertical_offset==319&&rows[2].vertical_offset==355&&menu.focused_child==rows); + mcc_xbox_attach(&root);assert(rows[1].vertical_offset==319&&entry.next==rows+1); + assert(mcc_xbox_event("open",&entry,&event,&deleted)&&!strcmp(opened,"pc\\mcc_xbox\\profiles")); + root.child=children; + root_tag=MCC_XBOX_NATIVE "connected\\connected_map_select_wrapper"; + assert(mcc_xbox_shortcut(&root,&event)&&!strcmp(opened,"pc\\mcc_xbox\\connected")); + mcc_xbox_attach(&root);assert(cards[2].next==&entry&&entry.previous==cards+2);cards[2].next=NULL; + root_tag="pc\\mcc_xbox\\profiles";assert(mcc_xbox_event("profile",&root,&event,&deleted)&&native_calls==2&&!strcmp(opened,"pc\\mcc_xbox\\campaign")); + root_tag="pc\\mcc_xbox\\campaign";assert(mcc_xbox_event("init",&root,&event,&deleted)&&rescans==1); + assert(children[0].visible&&!children[1].visible&&!children[6].visible); + assert(mcc_xbox_event("choose",&root,&event,&deleted));assert(mcc_xbox_browser.count==4&&children[1].visible); + assert(parts[0][0].animation.current_frame_index==0x1000); + assert(parts[0][3].visible&&!parts[0][4].visible&&parts[0][5].visible); + for(i=0;i<3;i++)assert(mcc_xbox_event("right",&root,&event,&deleted)); + assert(mcc_xbox_browser.chosen==3&&mcc_xbox_slot==2); + assert(mcc_xbox_event("right",&root,&event,&deleted)&&mcc_xbox_browser.chosen==0); + assert(mcc_xbox_event("choose",&root,&event,&deleted)&&mcc_xbox_difficulty&&children[6].visible&&!cards[0].visible&&children[3].visible); + children[6].parameters.list.selected_index=2; + assert(mcc_xbox_event("choose",&root,&event,&deleted)&&starts==1&&started_skill==2&&!strcmp(started,"mcc_maps\\pkg\\a10")); + active_profile=3;assert(!mcc_xbox_event("choose",&root,&event,&deleted)&&starts==1);active_profile=2; + assert(mcc_xbox_event("back",&root,&event,&deleted)&&!mcc_xbox_difficulty&&mcc_xbox_browser.package[0]); + assert(mcc_xbox_event("back",&root,&event,&deleted)&&!mcc_xbox_browser.package[0]&&!backs); + assert(mcc_xbox_event("back",&root,&event,&deleted)&&backs==1); + root_tag="pc\\mcc_xbox\\connected";assert(mcc_xbox_event("init",&root,&event,&deleted)); + assert(!mcc_xbox_browser.campaign);mcc_xbox_event("choose",&root,&event,&deleted);mcc_xbox_event("choose",&root,&event,&deleted); + assert(mp_choices==1&&!strcmp(opened,MCC_XBOX_NATIVE "connected\\gametype_select_screen_wrapper")); + mcc_xbox_reset();assert(!mcc_xbox_browser.count&&!mcc_xbox_browser.package[0]&&!mcc_xbox_difficulty&&mcc_xbox_profile==NONE); + return 0; +} +''') diff --git a/tools/test_menu_button_glyphs.py b/tools/test_menu_button_glyphs.py index de991c86f8..cdb7b702a5 100644 --- a/tools/test_menu_button_glyphs.py +++ b/tools/test_menu_button_glyphs.py @@ -32,7 +32,7 @@ def test_menu_glyph_policy_fitting_and_state(tmp_path): struct rasterizer_dynamic_screen_geometry_parameters { struct bitmap_data *map[3];struct {real i,j;}map_texture_scale[3],map_scale[3];int framebuffer_blend_function; }; -static int enabled=1,keyboard=1,style_choice=7,fail,backgrounds,labels,quads; +static int enabled=1,hud=1,keyboard=1,style_choice=7,fail,backgrounds,labels,quads; static short observed_port; static char const *menus="pc"; static struct bitmap_data bitmap; @@ -43,7 +43,7 @@ def test_menu_glyph_policy_fitting_and_state(tmp_path): static real bx,by,bw,bh,tx,ty,ts; static wchar_t last_text[32]; static struct dynamic_screen_vertex drawn[4]; -int config_boolean(char const *n){assert(!strcmp(n,"display.menu_button_glyphs"));return enabled;} +int config_boolean(char const *n){if(!strcmp(n,"display.high_res_hud"))return hud;assert(!strcmp(n,"display.menu_button_glyphs"));return enabled;} char const *config_string(char const *n){assert(!strcmp(n,"display.menus"));return menus;} static int keyboard_prompt_enabled(short p){observed_port=p;return keyboard;} static int controller_button_style_for_port(short p){observed_port=p;return style_choice;} @@ -88,6 +88,9 @@ def test_menu_glyph_policy_fitting_and_state(tmp_path): enabled=0;assert(!menu_button_glyph_draw(0,0,&box,0,0x80ffffff)); assert(!wcscmp(menu_button_glyph_join_hint(0,0),L"ENTER: select ESC: back")); enabled=1;menus="xbox";assert(!menu_button_glyph_draw(0,0,&box,0,0x80ffffff)); + menus="pc";hud=0;assert(!menu_button_glyph_draw(0,0,&box,0,0x80ffffff)); + assert(!wcscmp(menu_button_glyph_join_hint(0,0),L"ENTER: select ESC: back")); + keyboard=0;assert(!menu_button_glyph_draw(0,0,&box,0,0x80ffffff));keyboard=1;hud=1; menus="pc";assert(!menu_button_glyph_draw(-1,0,&box,0,0));assert(!menu_button_glyph_draw(4,0,&box,0,0)); assert(!menu_button_glyph_draw(0,-1,&box,0,0));assert(!menu_button_glyph_draw(0,4,&box,0,0)); assert(!backgrounds&&!quads&&!labels); @@ -145,7 +148,7 @@ def test_menu_toggle_defaults_off_and_generator_owns_screens(): def test_legend_expansion_moves_text_and_hit_target_together(tmp_path): - source=(ROOT/'port/linux/game/menu_functions.c').read_text() + source=(ROOT/'port/linux/game/menu_button_widgets.inl').read_text() run_c(tmp_path,r""" #include #include diff --git a/tools/test_net_compare.py b/tools/test_net_compare.py index b63b698191..6d8be6e844 100644 --- a/tools/test_net_compare.py +++ b/tools/test_net_compare.py @@ -15,6 +15,13 @@ import net_compare # noqa: E402 +def test_log_judge_imports_without_posix_hangup(monkeypatch): + import runpy + monkeypatch.delattr(signal, "SIGHUP", raising=False) + module = runpy.run_path(net_compare.__file__) + assert module['STOP_SIGNALS'] == (signal.SIGINT, signal.SIGTERM) + + def player(index, x, y=10.0, z=0.5, *, dead=False, kills=0, deaths=0, grenades="2/2", rounds=60, team=0, machine=0): if dead: return f" player {index}: dead s{kills} k{kills} d{deaths} f0 t{team} m{machine}" @@ -146,6 +153,7 @@ def make_data(tmp_path): return data +@pytest.mark.skipif(os.name == 'nt', reason='POSIX launcher uses symlinked libraries/data') def test_copy_of_a_flat_folder(tmp_path): build = tmp_path / "build" build.mkdir() @@ -226,6 +234,7 @@ def read_pids(pids): return [int(pid) for pid in pids.read_text().split()] if pids.exists() else [] +@pytest.mark.skipif(os.name == 'nt', reason='POSIX shell and process-group lifecycle') def test_stop_ends_the_copy_and_what_it_started(tmp_path): game, pids = fake_game(tmp_path) process = net_compare.start([str(game)]) @@ -236,7 +245,8 @@ def test_stop_ends_the_copy_and_what_it_started(tmp_path): assert wait_for(lambda: not any(alive(pid) for pid in read_pids(pids))) -@pytest.mark.parametrize("number", [signal.SIGTERM, signal.SIGHUP, signal.SIGINT]) +@pytest.mark.skipif(os.name == 'nt', reason='POSIX shell and process-group lifecycle') +@pytest.mark.parametrize("number", net_compare.STOP_SIGNALS) def test_the_tool_stopped_leaves_no_copy(tmp_path, number): game, pids = fake_game(tmp_path) tool = subprocess.Popen([sys.executable, str(Path(net_compare.__file__)), "--a", str(game), "--data", @@ -256,6 +266,7 @@ def test_the_tool_stopped_leaves_no_copy(tmp_path, number): assert not [pid for pid in read_pids(pids) if alive(pid)] +@pytest.mark.skipif(sys.platform != 'linux', reason='Linux PR_SET_PDEATHSIG lifecycle') def test_a_copy_dies_with_a_killed_tool(tmp_path): # (SIGKILL cannot be caught: the kernel ends the copies, PR_SET_PDEATHSIG; # what a copy started is its own, and the test's to end) diff --git a/tools/test_network_messages.py b/tools/test_network_messages.py index 578568b92f..a5bb72c442 100644 --- a/tools/test_network_messages.py +++ b/tools/test_network_messages.py @@ -5,9 +5,11 @@ byte_swapping.c), compiled with the build's own flags (from build.ninja, so `python3 configure.py` first) plus AddressSanitizer, and checks: -- each message encodes to the same bytes as REFERENCE, captured from the - packet table as upstream ships it: the wire is shared with OpenCE and - every earlier build, and must not move a byte; +- each message encodes to the historical REFERENCE captured from OpenCE + build 138. This reference predates account-link joins and GulchCE's shared + checkpoint agreement; it is not the current protocol's acceptance oracle. + See test_join_protocol.py for the current join codec and test_mcc_protocol.py + for the audited differences from the later OpenCE 41 baseline; - no encode or decode reads or writes past a message's structure (each sits alone in its own allocation, which AddressSanitizer guards). diff --git a/tools/test_network_test_sampling.py b/tools/test_network_test_sampling.py new file mode 100644 index 0000000000..6927094699 --- /dev/null +++ b/tools/test_network_test_sampling.py @@ -0,0 +1,94 @@ +"""Run the real debug observation/action gates against controlled frame ticks.""" +import os +from pathlib import Path +import shutil +import subprocess + +import pytest +from harness import function +from net_compare import pair_ticks + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.fixture(scope="module") +def sampler(tmp_path_factory): + compiler = os.environ.get("CC") or shutil.which("clang") or shutil.which("cc") + if not compiler: + pytest.skip("a C compiler is needed") + work = tmp_path_factory.mktemp("network-test-sampling") + update = function((ROOT / "port/linux/game/network_test.c").read_text(), "network_test_update") + # Keep the production reset, cue, observation and scripted-action gates. + # The unrelated action bodies are represented by an action-time recorder. + start = update.index("\t/* the game running:") + stop = update.index("\t\tif (network_test.shoot_interval", start) + gate = update[start:stop] + source = work / "sampling.c" + source.write_text(r''' +#include +#include +#define TICKS_PER_SECOND 30 +#define NONE -1 +static struct {long logged_time, sample_time, cues_start, next_cue;} network_test; +static long tick; +static int active=1; +static long game_time_get(void) {return tick;} +static int game_in_progress(void) {return active;} +static void network_test_log_players(void) {printf("S %ld\n",tick);} +static void network_test_run_cues(void) {} +static void frame(int main_menu_loaded) { +''' + gate + r''' + printf("A %ld\n",tick); + } +} +int main(int argc,char **argv) { + int i,menu; + for(i=1;i +typedef float real; +typedef int boolean; +typedef struct {real red, green, blue;} real_rgb_color; +#define FALSE 0 +#define TRUE 1 +#define NONE (-1) +#define MIN(a,b) ((a) < (b) ? (a) : (b)) +#define PIN(x,lo,hi) MIN(MAX(x,lo),hi) +#define TEST_FLAG(flags,bit) ((flags) & (1 << (bit))) +#define _object_dead_bit 0 +#define _object_shield_over_charging_bit 1 +#define MAX(a,b) ((a) > (b) ? (a) : (b)) +#define CHECK(c) do {if (!(c)) return __LINE__;} while (0) +static boolean enabled = TRUE; +static boolean overshield_effect_enabled(void) { return enabled; } +static int near(real a, real b) {real d = a - b; return d > -.00001f && d < .00001f;} +''' + code += f"\n#define OVERSHIELD_EFFECT_MAXIMUM {constant(text, 'OVERSHIELD_EFFECT_MAXIMUM')}\n" + code += "\n".join(re.findall(r"^#define OVERSHIELD_EFFECT_(?:ENERGY_SPEED|EDGE|RISE|RISE_FROM_DOWN|DOWN) .*", text, re.M)) + code += "\n" + structure(text, "overshield_effect") + code += "\nstatic struct overshield_effect overshield_effects[OVERSHIELD_EFFECT_MAXIMUM];\n" + code += "\n".join(re.findall(r"static real_rgb_color const overshield_effect_(?:outer_)?rgb = .*?;", text)) + code += r""" +static boolean overshield_effects_initialized; +#define OVERSHIELD_EFFECT_MODELS 8 +static struct {long model_index;} overshield_effect_models[OVERSHIELD_EFFECT_MODELS]; +static short overshield_effect_next_model; +struct unit_datum {struct {real shield_vitality; unsigned long damage_flags;} object;}; +static struct unit_datum unit; +static struct unit_datum *unit_try_and_get(long index) {return index == 7 ? &unit : NULL;} +static struct {real game_time_sec;} global_frame_parameters; +""" + code += "\n" + function(text, "overshield_effect_reset") + code += "\n" + function(text, "overshield_effect_layer_color") + code += "\n" + function(text, "overshield_effect_get") + code += "\n" + function(text, "overshield_effect_light_sample") + code += "\n" + function(text, "overshield_effect_find_values") + code += "\n" + function(text, "overshield_effect_draw") + code += "\n" + function(text, "overshield_effect_color") + code += r''' +int main(void) { + struct overshield_effect *effect = &overshield_effects[0]; + real own[4] = {0}, speed, softness, height, coverage; + real_rgb_color light; + real_rgb_color perpendicular = {.1f, .8f, .2f}, parallel = {.3f, .2f, .1f}; + real_rgb_color original_perpendicular = perpendicular, original_parallel = parallel; + real layers[] = {3.f, 2.0001f, 2.f, 1.0001f, 2.5f}; + int layer, arms; + effect->unit_index = 7; + effect->shield_vitality = 2.f; + effect->bottom = -1.f; effect->top = 1.f; effect->progress = .5f; + CHECK(!overshield_effect_color(NULL, &perpendicular, ¶llel)); + CHECK(!overshield_effect_color(own, &perpendicular, ¶llel)); + CHECK(!memcmp(&perpendicular, &original_perpendicular, sizeof(perpendicular))); + CHECK(!memcmp(¶llel, &original_parallel, sizeof(parallel))); + CHECK(overshield_effect_draw(effect->body_values, &speed, &softness, &height)); + CHECK(near(speed, .3f) && near(softness, 1.f/.24f) && near(height, .12f)); + CHECK(overshield_effect_color(effect->body_values, &perpendicular, ¶llel)); + CHECK(near(perpendicular.red, .8f) && near(perpendicular.green, .306f/.992f*.8f)); + CHECK(near(perpendicular.blue, .455f/.992f*.8f)); + CHECK(near(parallel.red, .3f) && near(parallel.green, .306f/.992f*.3f)); + CHECK(near(parallel.blue, .455f/.992f*.3f)); + effect->arms_values = own; + for (layer = 0; layer < 5; layer++) { + effect->shield_vitality = layers[layer]; + for (arms = 0; arms < 2; arms++) { + perpendicular = original_perpendicular; parallel = original_parallel; + CHECK(overshield_effect_color(arms ? own : effect->body_values, &perpendicular, ¶llel)); + CHECK(near(layers[layer] > 2.f ? perpendicular.green : perpendicular.red, .8f)); + CHECK(near(layers[layer] > 2.f ? parallel.green : parallel.red, .3f)); + } + } + enabled = FALSE; + perpendicular = original_perpendicular; parallel = original_parallel; + CHECK(!overshield_effect_color(own, &perpendicular, ¶llel)); + CHECK(!overshield_effect_color(effect->body_values, &perpendicular, ¶llel)); + CHECK(!memcmp(&perpendicular, &original_perpendicular, sizeof(perpendicular))); + enabled = TRUE; + effect->arms_values = NULL; + CHECK(!overshield_effect_color(own, &perpendicular, ¶llel)); + effect->progress = 1.f; + CHECK(overshield_effect_draw(effect->body_values, &speed, &softness, &height)); + CHECK(softness == 0 && height == 0); + effect->unit_index = NONE; + CHECK(!overshield_effect_draw(effect->body_values, &speed, &softness, &height)); + effect = &overshield_effects[OVERSHIELD_EFFECT_MAXIMUM-1]; + effect->unit_index = 8; effect->shield_vitality = 3.f; effect->arms_values = own; + perpendicular = original_perpendicular; parallel = original_parallel; + CHECK(overshield_effect_color(own, &perpendicular, ¶llel)); + CHECK(near(perpendicular.green, .8f) && near(parallel.green, .3f)); + CHECK(overshield_effect_draw(own, &speed, &softness, &height)); + CHECK(near(speed, .3f) && softness == 0 && height == 0); + effect->unit_index = NONE; + CHECK(!overshield_effect_color(own, &perpendicular, ¶llel)); + global_frame_parameters.game_time_sec = 1.f; + unit.object.shield_vitality = 3.f; + effect = overshield_effect_get(7); CHECK(effect && effect->shield_vitality == 3.f); + CHECK(overshield_effect_light_sample(7, &light, &coverage) && light.green > light.red); + unit.object.shield_vitality = 2.f; + CHECK(overshield_effect_light_sample(7, &light, &coverage) && light.red > light.green); + CHECK(overshield_effect_get(7) == effect && effect->shield_vitality == 2.f); + unit.object.shield_vitality = 1.f; + CHECK(!overshield_effect_get(7)); + CHECK(!overshield_effect_color(effect->body_values, &perpendicular, ¶llel)); + unit.object.damage_flags = 1 << _object_shield_over_charging_bit; + CHECK(overshield_effect_get(7)); /* retain the existing charging rise */ + unit.object.shield_vitality = 2.1f; + CHECK(overshield_effect_get(7)->shield_vitality == 2.1f); + enabled = FALSE; CHECK(!overshield_effect_get(7)); + CHECK(!overshield_effect_color(effect->body_values, &perpendicular, ¶llel)); + enabled = TRUE; unit.object.damage_flags = 1 << _object_dead_bit; + CHECK(!overshield_effect_get(7)); + overshield_effect_models[0].model_index = 17; + overshield_effect_next_model = 5; + overshield_effect_reset(); + CHECK(overshield_effect_models[0].model_index == NONE && overshield_effect_next_model == 0); + CHECK(overshield_effects[0].unit_index == NONE && overshield_effects[0].arms_values == NULL); + return 0; +} +''' + source = tmp_path / "overshield.c" + source.write_text(code) + executable = tmp_path / ("overshield.exe" if sys.platform == "win32" else "overshield") + flags = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld"] if sys.platform == "win32" else [] + subprocess.run([compiler, "-std=gnu89", *flags, str(source), "-o", str(executable)], check=True) + subprocess.run([str(executable)], check=True, timeout=10) diff --git a/tools/test_p2p_shutdown.py b/tools/test_p2p_shutdown.py new file mode 100644 index 0000000000..2c50e2afd5 --- /dev/null +++ b/tools/test_p2p_shutdown.py @@ -0,0 +1,58 @@ +"""Actual P2P lifecycle code requests stop and waits for workers within upstream bounds.""" +from pathlib import Path +import re +import subprocess +import pytest +from harness import constant, function +from test_mcc_identity import compile_tool + +ROOT = Path(__file__).resolve().parents[1] +NAMES = ["upnp_thread", "p2p_shutdown", "update_upnp", "p2p_thread", "p2p_initialize"] + + +def build(tmp_path, mutation=None): + source = (ROOT / "port/linux/src/p2p.c").read_text() + if mutation: + before, after = mutation + assert before in source + source = source.replace(before, after, 1) + code = (ROOT / "tools/tests/p2p_shutdown.c").read_text() + code = code.replace("/* ACTUAL INITIALIZER */", re.search(r"\} p2p = (\{[^;]+\});", source)[1]) + code = "\n".join(f"#define {name} {constant(source,name)}" for name in ("P2P_STOP_WAIT","UPNP_RELEASE_WAIT")) + "\n" + code + code = code.replace("/* ACTUAL FUNCTIONS */", "\n".join(function(source, name) for name in NAMES)) + path = tmp_path / "shutdown.c" + path.write_text(code) + return compile_tool(tmp_path, [path]) + + +@pytest.fixture(scope="module") +def binary(tmp_path_factory): + return build(tmp_path_factory.mktemp("p2p_shutdown")) + + +@pytest.mark.parametrize("case", ["poll", "flow", "upnp", "renew", "upnp_fail", "start_fail", "retry_start", "hook_fail", "offline"]) +def test_workers_end_before_cleanup(binary, case): + subprocess.run([str(binary), case], check=True, capture_output=True, timeout=10) + + +@pytest.mark.parametrize("mutation,case", [ + (("WaitForSingleObject(p2p.thread, P2P_STOP_WAIT);", "/* detached: no wait */"), "poll"), + (("WaitForSingleObject(p2p.upnp_thread, UPNP_RELEASE_WAIT);", "/* detached: no wait */"), "upnp"), + (("if (p2p.stopping)\n\t\t\tbreak;", "/* process one more pass after stop */"), "poll"), +]) +def test_regressions_reject_detached_or_post_stop_work(tmp_path, mutation, case): + changed = build(tmp_path, mutation) + result = subprocess.run([str(changed), case], capture_output=True, timeout=10) + assert result.returncode != 0 + + +@pytest.mark.parametrize("case", ["before", "discovery", "scan", "address", "retry", "permanent", "success", "normal"]) +def test_upnp_cancellation_between_owned_requests(tmp_path, case): + source = (ROOT / "port/linux/src/posix_upnp.c").read_text() + names = ["posix_upnp_cancel", "upnp_cancelled", "swap_short", "upnp_remove_left_forwardings", + "upnp_find_router", "upnp_add", "posix_upnp_forward_udp", "posix_upnp_stop_forwarding_udp"] + code = (ROOT / "tools/tests/p2p_upnp_cancel.c").read_text() + path = tmp_path / "upnp.c" + path.write_text(code.replace("/* ACTUAL FUNCTIONS */", "\n".join(function(source, n) for n in names))) + binary = compile_tool(tmp_path, [path]) + subprocess.run([str(binary), case], check=True, capture_output=True, timeout=10) diff --git a/tools/test_pause_art.py b/tools/test_pause_art.py new file mode 100644 index 0000000000..ae41dfdc89 --- /dev/null +++ b/tools/test_pause_art.py @@ -0,0 +1,53 @@ +"""Check the shipped pause artwork at its logical widget coordinates.""" +from pathlib import Path +import json +import xml.etree.ElementTree as ET + +from PIL import Image +import pytest + +ROOT = Path(__file__).resolve().parents[1] +MENUS = ROOT / 'port/assets/menus' + + +@pytest.mark.parametrize('piece', ['left', 'center', 'right']) +@pytest.mark.parametrize('frame,height', [(0, 194), (1, 229), (2, 195)]) +def test_button_strip(piece, frame, height): + image = Image.open(MENUS / f'ce/port/pause/pausebox_{piece}__{frame}.png').convert('RGBA') + scale = image.height // 256 + x = image.width // 2 + # Stock Xbox footer alpha is 191/255, with no blue body underneath. + assert image.getpixel((x, (height - 15) * scale)) == (0, 0, 0, 191) + assert_campaign_gradient(image, 2, height - 29, piece) + assert image.getpixel((x, (height + 1) * scale))[3] == 0 + assert image.getpixel((x, (height - 28) * scale))[:3] == (40, 150, 255) + + +@pytest.mark.parametrize('piece', ['left', 'center', 'right']) +def test_objective_header(piece): + name = f'ce/port/pause/objectives_{piece}__0.png' + image = Image.open(MENUS / name).convert('RGBA') + scale = image.height // 256 + x = image.width // 2 + assert image.getpixel((x, 15 * scale)) == (0, 0, 0, 255) + assert image.getpixel((x, 28 * scale))[:3] == (40, 150, 255) + assert_campaign_gradient(image, 29, 192, piece) + assert image.getpixel((x, 196 * scale))[3] == 0 + if piece != 'center': + assert image.getpixel((0 if piece == 'left' else image.width - 1, 0))[3] == 0 + definitions = ET.parse(MENUS / 'ce/bitmaps.xml').getroot() + bitmap = definitions.find(f"bitmap[@name='pause/objectives_{piece}']") + assert [frame.get('png') for frame in bitmap] == [name] + assert name in json.loads((MENUS / 'menus.json').read_text())['files'] + + +def assert_campaign_gradient(image, top, bottom, piece): + scale = image.height // 256 + x = image.width // 2 + x = image.width - 1 if piece == "left" else 0 if piece == "right" else x + samples = [image.getpixel((x, y * scale)) for y in range(top, bottom + 1)] + assert samples[0] == pytest.approx((10, 38, 73, 191), abs=2) + assert samples[-1] == pytest.approx((5, 13, 28, 191), abs=2) + assert all(pixel[3] == 191 for pixel in samples) + for a, b in zip(samples, samples[1:]): + assert all(b[channel] <= a[channel] for channel in range(3)) diff --git a/tools/test_pause_campaign_context.py b/tools/test_pause_campaign_context.py new file mode 100644 index 0000000000..913e574fdf --- /dev/null +++ b/tools/test_pause_campaign_context.py @@ -0,0 +1,55 @@ +"""Campaign pause eligibility uses the same Settings patch on network peers.""" +from pathlib import Path +import shutil +import subprocess +import pytest +from harness import function + + +def test_campaign_pause_contexts(tmp_path): + clang = shutil.which('clang') + if not clang: + pytest.skip('clang is needed') + root = Path(__file__).resolve().parents[1] + source = (root / 'port/linux/game/menu_tags.c').read_text() + code = r''' +#include +#include +typedef int boolean; +#define NONE -1 +#define UI_WIDGET_DEFINITION_TAG 0 +#define MULTIPLAYER_COLLECTION "multiplayer" +#define CAMPAIGN_PAUSE_SCREEN "campaign" +#define _game_connection_local 0 +static int multiplayer, campaign, connection, network, cooperative; +static int tag_loaded(int group, char const *name) { + return (!strcmp(name, MULTIPLAYER_COLLECTION) ? multiplayer : campaign) ? 1 : NONE; +} +static int game_connection(void) { return connection; } +static int network_game_is_active(void) { return network; } +static int game_is_cooperative(void) { return cooperative; } +''' + code += function(source, 'full_screen_campaign_map') + code += r''' +int main(void) { + campaign=1; + assert(full_screen_campaign_map()); + cooperative=1; + assert(!full_screen_campaign_map()); + for(connection=1;connection<=2;connection++) { + assert(full_screen_campaign_map()); + network=1; + assert(full_screen_campaign_map()); + network=0; + } + multiplayer=1; + assert(!full_screen_campaign_map()); + multiplayer=0;campaign=0; + assert(!full_screen_campaign_map()); + return 0; +} +''' + src, exe = tmp_path / 'pause.c', tmp_path / 'pause.exe' + src.write_text(code) + subprocess.run([clang, '-m32', '-std=gnu89', str(src), '-o', str(exe)], check=True, capture_output=True) + subprocess.run([str(exe)], check=True) diff --git a/tools/test_player_notes.py b/tools/test_player_notes.py new file mode 100644 index 0000000000..790d6869b8 --- /dev/null +++ b/tools/test_player_notes.py @@ -0,0 +1,605 @@ +"""Exercise the note collector against actual temporary Git histories.""" + +import json +from pathlib import Path +import subprocess +import sys +import xml.etree.ElementTree as ET + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import player_notes + + +class Repository: + def __init__(self, root): + self.root = root + root.mkdir() + self.git("init", "-b", "main") + self.git("config", "user.name", "Notes test") + self.git("config", "user.email", "notes@example.invalid") + self.baseline = self.commit("Initial tree") + self.catchup = root / "catchup.json" + self.manifest() + + def git(self, *args): + return subprocess.run(["git", *args], cwd=self.root, check=True, + stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.decode().strip() + + def commit(self, message): + subprocess.run(["git", "commit", "--allow-empty", "-F", "-"], cwd=self.root, + input=message.encode("utf-8"), check=True, + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + return self.git("rev-parse", "HEAD") + + def manifest(self, notes=None, baseline=None): + self.catchup.write_text(json.dumps({"schema_version": 1, + "baseline": baseline or self.baseline, + "notes": notes or []}), encoding="utf-8") + + def collect(self, **kwargs): + return player_notes.collect(self.root, catchup=self.catchup, **kwargs) + + +@pytest.fixture +def repo(tmp_path): + return Repository(tmp_path / "repo") + + +def texts(data): + return [note for entry in data["entries"] for note in entry["notes"]] + + +def test_body_annotations_and_explicit_none(repo): + first = repo.commit("Internal subject\n\nPlayer-Note: Added controller navigation.\nPlayer-Note: Fixed map loading.") + repo.commit("No user facing effect\n\nPlayer-Note: none") + repo.commit("A very exciting but unannotated subject") + data, markdown, warnings = repo.collect() + assert data["schema_version"] == 2 + assert data["head"] == repo.git("rev-parse", "HEAD") + assert data["entries"][0]["commit"] == data["head"] + assert data["entries"][0]["build"] is None + assert texts(data) == ["Added controller navigation.", "Fixed map loading."] + assert markdown == "- Added controller navigation.\n- Fixed map loading.\n" + assert warnings == [] + + +def test_empty_history_and_no_subject_fallback(repo): + repo.commit("Player-visible sounding subject with no annotation") + data, markdown, _ = repo.collect() + assert data["entries"][0]["notes"] == [] + assert markdown == "No player-facing notes were recorded for this build.\n" + assert repo.collect(head=repo.baseline)[0]["entries"][0]["notes"] == [] + + +def test_published_category_correction_is_commit_scoped(repo, monkeypatch): + correction = player_notes.HISTORICAL_NOTE_PREFIXES[ + "4f3eec76a1165a111bff83047b064a55c156f3bc"] + sha = repo.commit("Published merge\n\nPlayer-Note: [Android] Open Cheats directly.\n" + "Player-Note: [Android] Hosts can use cheats online.") + monkeypatch.setattr(player_notes, "HISTORICAL_NOTE_PREFIXES", {sha: correction}) + data, _, _ = repo.collect() + assert texts(data) == ["Open Cheats directly.", "Hosts can use cheats online."] + assert data["entries"][0]["categories"] == ["ANDROID", "ANDROID"] + later = repo.commit("New invalid note\n\nPlayer-Note: [Android] A different change.") + with pytest.raises(player_notes.NotesError, match=later): + repo.collect() + + +def test_historical_prefix_correction_keeps_note_validation(repo, monkeypatch): + sha = repo.commit("Malformed text\n\nPlayer-Note: [Android] Bad|menu text.") + monkeypatch.setattr(player_notes, "HISTORICAL_NOTE_PREFIXES", + {sha: ("Player-Note: [Android] ", "Player-Note: [ANDROID] ")}) + with pytest.raises(player_notes.NotesError, match="without backslashes or menu pipes"): + repo.collect() + + +def test_published_withdrawal_omits_only_its_original_note(repo, monkeypatch): + original = repo.commit("Optimization\n\nPlayer-Note: Reduced CPU work.") + kept = repo.commit("Resource fix\n\nPlayer-Note: Fixed resource discovery.") + withdrawal = repo.commit("Withdraw the unfinished optimization") + monkeypatch.setattr(player_notes, "HISTORICAL_NOTE_WITHDRAWALS", + {withdrawal: original}, raising=False) + assert texts(repo.collect()[0]) == ["Fixed resource discovery."] + # Testing/history without the withdrawal still describes its own contents. + assert texts(repo.collect(head=kept)[0]) == ["Reduced CPU work.", "Fixed resource discovery."] + # A later reviewed restoration can author the same note again. + repo.commit("Restore the completed optimization\n\nPlayer-Note: Reduced CPU work.") + assert texts(repo.collect()[0]) == ["Fixed resource discovery.", "Reduced CPU work."] + + +def test_prose_mentioning_annotation_syntax_is_not_an_annotation(repo): + repo.commit("Document Player-Note usage\n\nPlayer-Note approach is authored, not inferred.\n" + "Write Player-Note: short text in the body.\n" + " Player-Note: an indented documentation example.") + assert repo.collect()[0]["entries"][0]["notes"] == [] + + +def test_release_requires_notes_for_unannotated_upstream_merge(repo): + repo.git("checkout", "-b", "upstream") + repo.commit("Add an upstream feature without our annotation convention") + repo.git("checkout", "main") + repo.commit("Maintenance\n\nPlayer-Note: none") + repo.git("merge", "--no-ff", "upstream", "-m", "Merge upstream") + with pytest.raises(player_notes.NotesError, match="new commits have no release notes"): + repo.collect(base=repo.baseline, build_number=2, require_notes=True) + merge = repo.git("rev-parse", "HEAD") + repo.manifest([{"commit": merge, "text": "Added local Slayer bots."}]) + assert texts(repo.collect(base=repo.baseline, build_number=2, + require_notes=True)[0]) == ["Added local Slayer bots."] + + +def test_release_tip_can_explicitly_review_internal_only_range(repo): + repo.commit("Internal refactor without an annotation") + repo.commit("Release internal maintenance\n\nPlayer-Note: none") + assert texts(repo.collect(build_number=2, require_notes=True)[0]) == [] + + +def test_empty_release_range_and_explicit_omissions_are_allowed(repo): + tip = repo.commit("Maintenance\n\nPlayer-Note: none") + assert texts(repo.collect(base=tip, build_number=2, require_notes=True)[0]) == [] + assert texts(repo.collect(base=repo.baseline, build_number=2, + require_notes=True)[0]) == [] + + +def test_old_duplicate_note_cannot_satisfy_release_check(repo): + base = repo.commit("Old feature\n\nPlayer-Note: Added bots.") + repo.commit("Unreviewed integration\n\nPlayer-Note: Added bots.") + with pytest.raises(player_notes.NotesError, match="new commits have no release notes"): + repo.collect(base=base, build_number=2, require_notes=True) + + +def test_all_merged_commits_group_once_and_keep_chronological_order(repo): + repo.git("checkout", "-b", "upstream") + upstream = repo.commit("Upstream work\n\nPlayer-Note: Improved upstream controls.") + repo.git("checkout", "-b", "testing") + testing = repo.commit("Tested work\n\nPlayer-Note: Added tested maps.") + repo.git("checkout", "main") + old = repo.commit("Local work\n\nPlayer-Note: Improved local controls.") + repo.git("merge", "--no-ff", "testing", "-m", "Merge testing\n\nPlayer-Note: Improved integration.") + merge = repo.git("rev-parse", "HEAD") + repo.git("merge", "upstream") + data, markdown, _ = repo.collect() + assert [entry["commit"] for entry in data["entries"]] == [merge] + assert data["entries"][0]["notes"] == ["Improved local controls.", "Improved upstream controls.", "Added tested maps.", "Improved integration."] + assert markdown.count("Improved upstream controls.") == 1 + assert upstream not in [entry["commit"] for entry in data["entries"]] + assert testing not in [entry["commit"] for entry in data["entries"]] + + +def test_duplicate_notes_belong_to_earliest_introduction(repo): + first = repo.commit("First\n\nPlayer-Note: Improved controls.") + repo.commit("Second\n\nPlayer-Note: improved controls\nPlayer-Note: Added maps.") + data, markdown, _ = repo.collect(base=first) + assert texts(data) == ["Added maps."] + assert markdown == "- Added maps.\n" + + +def test_later_merge_does_not_repeat_already_introduced_ancestry(repo): + repo.git("checkout", "-b", "upstream") + repo.commit("Upstream\n\nPlayer-Note: Improved upstream controls.") + repo.git("checkout", "-b", "testing") + repo.commit("Testing\n\nPlayer-Note: Added tested maps.") + repo.git("checkout", "main") + repo.git("merge", "--no-ff", "upstream", "-m", "Merge upstream") + previous_release = repo.git("rev-parse", "HEAD") + repo.git("merge", "--no-ff", "testing", "-m", "Merge testing") + data, markdown, _ = repo.collect(base=previous_release) + assert texts(data) == ["Added tested maps."] + assert markdown == "- Added tested maps.\n" + + +def test_release_range_includes_prior_commits_not_only_head(repo): + base = repo.commit("Old\n\nPlayer-Note: Old controls.") + repo.commit("First\n\nPlayer-Note: New controls.") + repo.commit("Second\n\nPlayer-Note: New maps.") + repo.commit("Packaging only") + _, markdown, _ = repo.collect(base=base) + assert markdown == "- New controls.\n- New maps.\n" + + +def test_catchup_only_applies_to_included_commits_and_keeps_order(repo): + first = repo.commit("Unannotated historic change") + repo.manifest([{"commit": repo.baseline, "text": "Excluded baseline note."}, + {"commit": first, "text": "First catch-up highlight."}, + {"commit": first, "text": "Second catch-up highlight."}]) + assert texts(repo.collect()[0]) == ["First catch-up highlight.", "Second catch-up highlight."] + assert repo.collect(head=repo.baseline)[0]["entries"][0]["notes"] == [] + + +def test_explicit_none_omits_catchup_for_that_commit(repo): + commit = repo.commit("Omit\n\nPlayer-Note: none") + repo.manifest([{"commit": commit, "text": "Old catch-up highlight."}]) + assert texts(repo.collect()[0]) == [] + + +def test_preview_combines_history_without_mislabeling_as_release(repo): + repo.commit("First\n\nPlayer-Note: First highlight.") + head = repo.commit("Second\n\nPlayer-Note: Second highlight.") + data, _, _ = repo.collect(preview=True) + assert len(data["entries"]) == 1 + assert data["entries"][0]["build"] is None + assert data["entries"][0]["commit"] == head + assert texts(data) == ["First highlight.", "Second highlight."] + + +def test_release_number_groups_all_changes_since_previous_success(repo): + for index in range(10): + repo.commit(f"Change {index}\n\nPlayer-Note: Highlight {index}.") + data, markdown, warnings = repo.collect(build_number=431) + assert len(data["entries"]) == 1 + assert data["entries"][0]["build"] == 431 + assert texts(data) == [f"Highlight {index}." for index in range(10)] + assert len(markdown.splitlines()) == 10 + assert warnings == [] + + +def test_no_per_entry_truncation_and_excessive_total_fails(repo, monkeypatch): + repo.commit("Many\n\n" + "\n".join(f"Player-Note: Highlight {i}." for i in range(30))) + assert len(texts(repo.collect()[0])) == 30 + monkeypatch.setattr(player_notes, "MAX_NOTES", 29) + with pytest.raises(player_notes.NotesError, match="none were silently discarded"): + repo.collect() + + +@pytest.mark.parametrize("annotation", [ + "Player-Note:", "Player-Note: ", "Player-Note: " + "x" * 101, + "Player-Note: New | menus", "Player-Note: New\\nmenus", + "Player-Note: New\tmenus", "Player-Note: New\rmenus", + "Player-Note: New\x1bmenus", "Player-Note: Caf\u00e9 controls.", + "player-note: New menus.", + "Player-Note: none\nPlayer-Note: Actual change.", +]) +def test_invalid_annotations_fail_actionably(repo, annotation): + sha = repo.commit("Change\n\n" + annotation) + with pytest.raises(player_notes.NotesError, match=sha): + repo.collect() + + +@pytest.mark.parametrize("option", ["head", "base"]) +@pytest.mark.parametrize("value", ["--all", "HEAD~1", "-h", "abc", "HEAD; echo unsafe"]) +def test_revision_options_are_full_shas_not_options_or_expressions(repo, option, value): + with pytest.raises(player_notes.NotesError, match="must be a full"): + repo.collect(**{option: value}) + + +def test_base_must_be_ancestor(repo): + repo.git("checkout", "-b", "side") + unrelated = repo.commit("Side") + repo.git("checkout", "main") + repo.commit("Main") + with pytest.raises(player_notes.NotesError, match="base .*not an ancestor"): + repo.collect(base=unrelated) + + +def test_missing_baseline_and_nonancestor_baseline_fail(repo): + repo.manifest(baseline="1" * 40) + with pytest.raises(player_notes.NotesError, match="catch-up baseline .*fetch complete history"): + repo.collect() + repo.git("checkout", "-b", "side") + unrelated = repo.commit("Side") + repo.git("checkout", "main") + repo.commit("Main") + repo.manifest(baseline=unrelated) + with pytest.raises(player_notes.NotesError, match="baseline .*not an ancestor"): + repo.collect() + + +@pytest.mark.parametrize("entry", [ + {"commit": "2" * 40, "text": "Missing commit."}, + {"commit": "--all", "text": "Hostile option."}, + {"commit": None, "text": "Invalid SHA."}, +]) +def test_catchup_references_must_exist_even_when_not_included(repo, entry): + repo.manifest([entry]) + with pytest.raises(player_notes.NotesError): + repo.collect() + + +@pytest.mark.parametrize("text", [None, "", "none", "bad|menu", "bad\\nmenu", "bad\u00a0menu", "x" * 101]) +def test_catchup_text_is_validated(repo, text): + repo.manifest([{"commit": repo.baseline, "text": text}]) + with pytest.raises(player_notes.NotesError, match="catch-up note 1"): + repo.collect() + + +def test_missing_and_malformed_manifest(repo): + repo.catchup.unlink() + with pytest.raises(player_notes.NotesError, match="cannot read catch-up manifest"): + repo.collect() + repo.catchup.write_text('{"schema_version": 2}') + with pytest.raises(player_notes.NotesError, match="schema_version 1"): + repo.collect() + + +def test_shallow_history_requires_complete_checkout(repo): + head = repo.commit("Change") + # Git's real shallow boundary avoids spawning a transport shell on Windows. + (repo.root / ".git/shallow").write_text(head + "\n", encoding="ascii") + with pytest.raises(player_notes.NotesError, match="fetch-depth: 0"): + repo.collect() + + +def test_output_is_deterministic_atomic_and_cli_reports_older_history(repo, tmp_path, monkeypatch, capsys): + repo.commit("Change\n\nPlayer-Note: Actual highlight.") + output = tmp_path / "output" + monkeypatch.setattr(player_notes, "ROOT", repo.root) + args = ["--catchup", str(repo.catchup), "--output", str(output)] + assert player_notes.main(args) == 0 + first = {path.name: path.read_bytes() for path in output.iterdir()} + assert player_notes.main(args) == 0 + assert {path.name: path.read_bytes() for path in output.iterdir()} == first + assert sorted(first) == ["changelog.json", "notes.md"] + monkeypatch.setattr(player_notes, "MAX_ENTRIES", 0) + assert player_notes.main(args) == 0 + assert "omitted 1 older changelog entries" in capsys.readouterr().err + + +def archive(repo, tmp_path, data): + path = tmp_path / "previous.json" + path.write_text(json.dumps(data), encoding="utf-8") + return path + + +def test_published_archive_preserves_exact_builds_and_release_boundaries(repo, tmp_path): + first = repo.commit("First\n\nPlayer-Note: First released highlight.") + first_data, _, _ = repo.collect(build_number=431) + previous = archive(repo, tmp_path, first_data) + repo.commit("Failed build\n\nPlayer-Note: Highlight from a failed build.") + head = repo.commit("Successful build\n\nPlayer-Note: Highlight from a successful build.") + data, markdown, _ = repo.collect(build_number=433, base=first, previous=previous) + assert [entry["build"] for entry in data["entries"]] == [433, 431] + assert data["entries"][1] == first_data["entries"][0] + assert data["entries"][0]["commit"] == head + assert markdown == "- Highlight from a failed build.\n- Highlight from a successful build.\n" + + +def test_git_releases_carry_exact_build_numbers_into_menu_pages(repo, tmp_path): + import changelog_menu + + base = repo.commit("Published change\n\nPlayer-Note: First released highlight.") + published, markdown, _ = repo.collect(build_number=12) + output = tmp_path / "published" + player_notes.write_outputs(output, published, markdown) + repo.commit("Next change\n\nPlayer-Note: [INTERFACE] Next released highlight.\n" + "Player-Note: [QUALITY OF LIFE] Added shortcuts.\n" + "Player-Note: [INTERFACE] Clearer labels.") + current, markdown, _ = repo.collect(build_number=13, base=base, + previous=output / "changelog.json") + menu = ET.fromstring("" + "\n".join(changelog_menu.widget_lines(current)) + "") + roots = [widget for widget in menu.findall("widget") + if "no_history" in widget.get("flags", "").split()] + assert len(roots) == 2 + headings = [widget.get("text") for widget in menu.findall("widget") + if widget.get("name", "").endswith("/heading")] + assert headings == ["BUILD 13", "BUILD 12"] + prefix = changelog_menu.BASE + "/build_1" + heading_table = menu.find(f"strings[@name='{prefix}/headings']") + body_table = menu.find(f"strings[@name='{prefix}/lines']") + assert [node.get("text") for node in heading_table if node.get("text")] == ["INTERFACE", "QUALITY OF LIFE"] + assert [node.get("text") for node in body_table if node.get("text")] == [ + "- Next released highlight.", "- Clearer labels.", "- Added shortcuts."] + assert len(heading_table) == len(body_table) + blue_rows = [widget for widget in menu.findall("widget") + if widget.get("name", "").startswith(prefix + "/heading_row_")] + assert blue_rows and all(widget.get("color") == "#FF2896FF" for widget in blue_rows) + old_heading_table = menu.find(f"strings[@name='{changelog_menu.BASE}/build_2/headings']") + assert [node.get("text") for node in old_heading_table if node.get("text")] == ["GENERAL"] + assert markdown == "- Next released highlight.\n- Added shortcuts.\n- Clearer labels.\n" + + +def test_no_change_release_and_same_sha_new_build_have_pages(repo, tmp_path): + head = repo.commit("Internal maintenance") + first_data, _, _ = repo.collect(build_number=5) + previous = archive(repo, tmp_path, first_data) + data, markdown, _ = repo.collect(build_number=6, base=head, previous=previous) + assert [entry["build"] for entry in data["entries"]] == [6, 5] + assert all(entry["commit"] == head and entry["notes"] == [] for entry in data["entries"]) + assert markdown == "No player-facing notes were recorded for this build.\n" + + +def test_rollout_without_archive_does_not_invent_prior_build_numbers(repo): + base = repo.commit("Old change\n\nPlayer-Note: Old highlight.") + repo.commit("New change\n\nPlayer-Note: Current highlight.") + data, _, _ = repo.collect(build_number=72, base=base) + assert len(data["entries"]) == 1 + assert data["entries"][0]["build"] == 72 + assert texts(data) == ["Current highlight."] + + +def test_preview_can_show_published_history_and_respects_base(repo, tmp_path): + base = repo.commit("Old\n\nPlayer-Note: Published highlight.") + previous = archive(repo, tmp_path, repo.collect(build_number=8)[0]) + repo.commit("New\n\nPlayer-Note: Preview highlight.") + data, markdown, _ = repo.collect(preview=True, base=base, previous=previous) + assert [entry["build"] for entry in data["entries"]] == [None, 8] + assert data["entries"][0]["notes"] == ["Preview highlight."] + assert markdown == "- Preview highlight.\n" + + +def test_history_window_drops_only_older_published_builds(repo, tmp_path): + previous = None + base = None + for build in range(1, 10): + repo.commit(f"Release {build}\n\nPlayer-Note: Highlight {build}.") + data, _, warnings = repo.collect(build_number=build, base=base, previous=previous) + base = data["head"] + previous = archive(repo, tmp_path, data) + assert [entry["build"] for entry in data["entries"]] == list(range(9, 1, -1)) + assert warnings == ["omitted 1 older changelog entries (keeping newest 8)"] + + +@pytest.mark.parametrize("build", [0, -1, True, "3", 1.5]) +def test_invalid_current_build_number_fails(repo, build): + with pytest.raises(player_notes.NotesError, match="positive integer"): + repo.collect(build_number=build) + + +def test_preview_and_numbered_release_are_mutually_exclusive(repo): + with pytest.raises(player_notes.NotesError, match="cannot accompany"): + repo.collect(build_number=3, preview=True) + + +def test_explicit_categories_keep_note_text_and_uncategorized_compatibility(repo): + repo.commit("Mixed notes\n\nPlayer-Note: [INTERFACE] Improved menus.\n" + "Player-Note: A plain older-style note.\n" + "Player-Note: [QUALITY OF LIFE] Added controller shortcuts.") + data, markdown, _ = repo.collect(build_number=12) + entry = data["entries"][0] + assert entry["categories"] == ["INTERFACE", "", "QUALITY OF LIFE"] + assert entry["notes"] == ["Improved menus.", "A plain older-style note.", "Added controller shortcuts."] + assert markdown == "- Improved menus.\n- A plain older-style note.\n- Added controller shortcuts.\n" + + +def test_category_prefix_does_not_reduce_note_text_limit(repo): + repo.commit("Note\n\nPlayer-Note: [QUALITY OF LIFE] " + "x" * 100) + assert len(texts(repo.collect()[0])[0]) == 100 + + +@pytest.mark.parametrize("annotation", [ + "Player-Note: [interface] Improved menus.", "Player-Note: [] Improved menus.", + "Player-Note: [TOO MANY SPACES] Improved menus.", "Player-Note: [BAD|MENU] Improved menus.", + "Player-Note: [BAD\\MENU] Improved menus.", "Player-Note: [A" + "B" * 24 + "] Improved menus.", + "Player-Note: [INTERFACE]", "Player-Note: [INTERFACE]none", + "Player-Note: [INTERFACE] none", "Player-Note: [INTERFACE] " + "x" * 101, +]) +def test_invalid_explicit_category_fails_actionably(repo, annotation): + sha = repo.commit("Invalid category\n\n" + annotation) + with pytest.raises(player_notes.NotesError, match=sha): + repo.collect() + + +def test_catchup_categories_are_explicit_and_never_inferred(repo): + commit = repo.commit("Old change") + repo.manifest([{"commit": commit, "text": "Improved menus.", "category": "INTERFACE"}, + {"commit": commit, "text": "Fixed multiplayer sounds."}]) + entry = repo.collect()[0]["entries"][0] + assert entry["categories"] == ["INTERFACE", ""] + + +@pytest.mark.parametrize("category", [None, "interface", "BAD|MENU", "BAD\\MENU", "BAD\nMENU", "X" * 25]) +def test_unsafe_catchup_category_fails(repo, category): + repo.manifest([{"commit": repo.baseline, "text": "Improved menus.", "category": category}]) + with pytest.raises(player_notes.NotesError, match="category must"): + repo.collect() + + +def test_categories_survive_archives_without_changing_old_uncategorized_entries(repo, tmp_path): + base = repo.commit("First\n\nPlayer-Note: Old highlight.") + old = repo.collect(build_number=12)[0] + previous = archive(repo, tmp_path, old) + head = repo.commit("Second\n\nPlayer-Note: [GRAPHICS] Improved lights.") + new, _, _ = repo.collect(build_number=13, base=base, previous=previous) + assert new["entries"][1] == old["entries"][0] + assert "categories" not in new["entries"][1] + previous = archive(repo, tmp_path, new) + newest, _, _ = repo.collect(build_number=14, base=head, previous=previous) + assert newest["entries"][1] == new["entries"][0] + assert newest["entries"][1]["categories"] == ["GRAPHICS"] + + +@pytest.mark.parametrize("categories", [None, "INTERFACE", [], ["INTERFACE", "GRAPHICS"], + [None], ["lowercase"], ["BAD|MENU"], ["X" * 25]]) +def test_prior_archive_category_metadata_is_validated(repo, tmp_path, categories): + base = repo.commit("First\n\nPlayer-Note: Old highlight.") + data = repo.collect(build_number=12)[0] + data["entries"][0]["categories"] = categories + with pytest.raises(player_notes.NotesError, match="categor"): + repo.collect(build_number=13, base=base, previous=archive(repo, tmp_path, data)) + + +def test_duplicate_text_keeps_earliest_category(repo): + base = repo.commit("First\n\nPlayer-Note: [QUALITY OF LIFE] Added shortcuts.") + repo.commit("Second\n\nPlayer-Note: [INTERFACE] Added shortcuts.") + assert repo.collect()[0]["entries"][0]["categories"] == ["QUALITY OF LIFE"] + current = repo.collect(base=base)[0]["entries"][0] + assert current["notes"] == [] + assert "categories" not in current + + +def test_current_build_rejects_signed_integer_overflow(repo): + assert repo.collect(build_number=2147483647)[0]["entries"][0]["build"] == 2147483647 + with pytest.raises(player_notes.NotesError, match="at most 2147483647"): + repo.collect(build_number=2147483648) + + +def test_prior_build_rejects_signed_integer_overflow(repo, tmp_path): + base = repo.commit("Published build") + data = repo.collect(build_number=2147483647)[0] + previous = archive(repo, tmp_path, data) + assert repo.collect(base=base, previous=previous)[0]["entries"][1]["build"] == 2147483647 + data["entries"][0]["build"] = 2147483648 + with pytest.raises(player_notes.NotesError, match="at most 2147483647"): + repo.collect(base=base, previous=archive(repo, tmp_path, data)) + + +@pytest.mark.parametrize("field,value,match", [ + ("build", None, "positive integer"), ("build", 0, "positive integer"), + ("build", True, "positive integer"), ("build", 3, "must decrease"), + ("date", "2026-02-30", "YYYY-MM-DD"), ("date", "20261018", "YYYY-MM-DD"), + ("date", None, "YYYY-MM-DD"), ("commit", "--all", "full 40-character"), + ("notes", ["bad|menu"], "printable ASCII"), ("notes", "text", "must be a list"), +]) +def test_prior_archive_entries_are_validated(repo, tmp_path, field, value, match): + base = repo.commit("Old\n\nPlayer-Note: Published highlight.") + data = repo.collect(build_number=2)[0] + data["entries"][0][field] = value + with pytest.raises(player_notes.NotesError, match=match): + repo.collect(build_number=3, base=base, previous=archive(repo, tmp_path, data)) + + +def test_archive_head_and_newest_entry_match_base(repo, tmp_path): + first = repo.commit("First") + data = repo.collect(build_number=1)[0] + second = repo.commit("Second") + with pytest.raises(player_notes.NotesError, match="head must equal --base"): + repo.collect(build_number=2, base=second, previous=archive(repo, tmp_path, data)) + data["head"] = second + with pytest.raises(player_notes.NotesError, match="newest entry commit must equal"): + repo.collect(build_number=2, base=second, previous=archive(repo, tmp_path, data)) + assert first != second + + +def test_archive_requires_base_and_unique_builds(repo, tmp_path): + base = repo.commit("First") + data = repo.collect(build_number=1)[0] + previous = archive(repo, tmp_path, data) + with pytest.raises(player_notes.NotesError, match="requires --base"): + repo.collect(build_number=2, previous=previous) + data["entries"] *= 2 + with pytest.raises(player_notes.NotesError, match="unique positive integer"): + repo.collect(build_number=2, base=base, previous=archive(repo, tmp_path, data)) + + +def test_archive_ancestry_and_schema_cannot_be_fabricated(repo, tmp_path): + repo.git("checkout", "-b", "side") + side = repo.commit("Side") + repo.git("checkout", "main") + base = repo.commit("Main") + data = repo.collect(build_number=2)[0] + data["entries"].append(dict(data["entries"][0], build=1, commit=side)) + with pytest.raises(player_notes.NotesError, match="not an ancestor"): + repo.collect(build_number=3, base=base, previous=archive(repo, tmp_path, data)) + data["schema_version"] = 1 + with pytest.raises(player_notes.NotesError, match="expected schema_version 2"): + repo.collect(build_number=3, base=base, previous=archive(repo, tmp_path, data)) + + +def test_supplied_missing_archive_fails_instead_of_inventing_history(repo, tmp_path): + with pytest.raises(player_notes.NotesError, match="cannot read previous changelog archive"): + repo.collect(build_number=3, base=repo.baseline, previous=tmp_path / "missing.json") + + +def test_validation_failure_does_not_replace_prior_outputs(repo, tmp_path, monkeypatch): + output = tmp_path / "output" + output.mkdir() + original = output / "changelog.json" + original.write_text("preserved") + repo.commit("Invalid\n\nPlayer-Note:") + monkeypatch.setattr(player_notes, "ROOT", repo.root) + with pytest.raises(SystemExit) as exc: + player_notes.main(["--catchup", str(repo.catchup), "--output", str(output)]) + assert exc.value.code == 1 + assert original.read_text() == "preserved" + assert not (output / "notes.md").exists() diff --git a/tools/test_render_stutter.py b/tools/test_render_stutter.py new file mode 100644 index 0000000000..fb591ff07f --- /dev/null +++ b/tools/test_render_stutter.py @@ -0,0 +1,111 @@ +"""Real translator variants and the independent omission experiment.""" +import os +from pathlib import Path +import re +import shutil +import subprocess +import pytest +from harness import enum_with, function, structure +from render_stutter_build import omit_honeycomb +from render_stutter_run import compare_player_traces, summarize + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.mark.parametrize('platform', ['desktop', 'android', 'web']) +@pytest.mark.parametrize('omit', [False, True]) +def test_honeycomb_translation(tmp_path, platform, omit): + cc = shutil.which('clang') + if not cc: + pytest.skip('clang required') + header = (ROOT/'port/linux/src/xgpu.h').read_text() + pdb = (ROOT/'port/include/xdk/xdk_pdb.h').read_text() + code = '#include \n#include \n#include \n#include \n#include \n' + code += 'typedef unsigned long DWORD;typedef int BOOL;\n#define TRUE 1\n#define FALSE 0\nstatic BOOL xgpu_reversed_depth;\n' + if platform != 'desktop': code += '#define HALO_GLES 1\n' + if platform == 'android': code += '#define HALO_ANDROID 1\n' + if platform == 'web': code += '#define HALO_WEB 1\n' + code += 'static struct {const char *shading_language;} xgpu_capabilities={"300 es"};\n' + code += '\n'.join('#define '+name+' '+value for name,value in re.findall(r'\b(D3D\w+)\s*=\s*(0x[\da-fA-F]+|\d+)\s*,',pdb))+'\n' + code += '\n'.join(structure(header,name) for name in ['xgpu_text','nv2a_vertex_lighting','nv2a_pixel_shader_key'])+'\n' + code += 'void xgpu_text_append(struct xgpu_text *,char const *,...);\n' + code += re.search(r'^#define XGPU_VERTEX_CONSTANT_BIAS .*$',header,re.M).group()+'\n' + code += enum_with(header,'_xgpu_sampler_none')+'\n' + code += header[header.index('#ifdef HALO_GLES\n/* ES samplers'):header.index('/* ---------- textures */')] + code += 'static char const *debug_expression="";\nstatic char const *config_string(char const *s){(void)s;return debug_expression;}\nstatic int config_boolean(char const *s){(void)s;return 0;}\n' + code += (ROOT/'port/linux/src/shield_honeycomb_gl.h').read_text() + code += function((ROOT/'port/linux/src/mcc_environment_shader_gl.c').read_text(),'mcc_environment_shader_emit') + for name in ['xgpu_text','plasma_model_shader','nv2a_psh']: + source=(ROOT/f'port/linux/src/{name}.c').read_text() + if omit and name=='nv2a_psh': source=omit_honeycomb(source) + code += re.sub(r'^#include.*$', '', source, flags=re.M)+'\n' + code += r''' +int main(void) { + struct nv2a_pixel_shader_key key={0}; + char *plain=nv2a_pixel_shader_to_glsl(&key),*shield,*again; + assert(!strstr(plain,"shield_honeycomb_surface") && !strstr(plain,"shield_hex")); + key.shield_honeycomb=1;shield=nv2a_pixel_shader_to_glsl(&key); + assert((strstr(shield,"result = shield_honeycomb_surface(result)")!=NULL)==EXPECT_SURFACE); + key.shield_honeycomb=0;again=nv2a_pixel_shader_to_glsl(&key); + assert(!strcmp(plain,again)); + free(plain);free(shield);free(again); + /* A dead r0.a write must produce the same desktop source as discard. + * The GLES source stays unchanged; later inputs/mux/final reads stay live. */ + memset(&key,0,sizeof(key)); + key.combiner_state[D3DRS_PSCOMBINERCOUNT]=8; + key.combiner_state[D3DRS_PSFINALCOMBINERINPUTSABCD]=0x08000000; + key.combiner_state[D3DRS_PSFINALCOMBINERINPUTSEFG]=0x00001800; + plain=nv2a_pixel_shader_to_glsl(&key); + key.combiner_state[D3DRS_PSALPHAINPUTS3]=0x1c140000; + key.combiner_state[D3DRS_PSALPHAOUTPUTS3]=0xc00; + again=nv2a_pixel_shader_to_glsl(&key); +#ifndef HALO_GLES + assert(!strcmp(plain,again)); + { + unsigned test; + for(test=0;test<7;test++) { + struct nv2a_pixel_shader_key live=key; + if(test==0)live.combiner_state[D3DRS_PSRGBINPUTS4]=0x1c000000; + if(test==1)live.combiner_state[D3DRS_PSALPHAINPUTS4]=0x001c0000; + if(test==2)live.combiner_state[D3DRS_PSRGBOUTPUTS4]=0x4000; + if(test==3)live.combiner_state[D3DRS_PSALPHAOUTPUTS4]=0x4000; + if(test==4)live.combiner_state[D3DRS_PSFINALCOMBINERINPUTSEFG]=0x00001c00; + if(test==5)live.combiner_state[D3DRS_PSFINALCOMBINERINPUTSABCD]=live.combiner_state[D3DRS_PSFINALCOMBINERINPUTSEFG]=0; + if(test==6)live.combiner_state[D3DRS_PSFINALCOMBINERINPUTSABCD]=0x001c0000; + discard_dead_r0_alpha(live.combiner_state); + assert(live.combiner_state[D3DRS_PSALPHAOUTPUTS3]==0xc00); + } + key.combiner_state[D3DRS_PSALPHAOUTPUTS3]=0xd00; + discard_dead_r0_alpha(key.combiner_state); + assert(key.combiner_state[D3DRS_PSALPHAOUTPUTS3]==0xd00); + } +#else + assert(strcmp(plain,again)); +#endif + free(plain);free(again); + key.combiner_state[D3DRS_PSALPHAOUTPUTS3]=0xc00; + debug_expression="r0.a";again=nv2a_pixel_shader_to_glsl(&key); + assert(strstr(again,"r0.a = aSUM;"));free(again);return 0; +} +''' + path=tmp_path/'translation.c';path.write_text(code) + exe=tmp_path/('translation.exe' if os.name=='nt' else 'translation') + flags=['--target=i686-pc-windows-msvc','-fuse-ld=lld','-D_CRT_SECURE_NO_WARNINGS'] if os.name=='nt' else ['-m32'] + result=subprocess.run([cc,*flags,'-std=gnu89',f'-DEXPECT_SURFACE={int(not omit)}',str(path),'-o',str(exe)],capture_output=True,text=True) + assert result.returncode==0,result.stderr + subprocess.run([str(exe)],check=True) + + +def test_settled_window_does_not_hide_long_frames(): + rows=[dict(ns=ns,tick=tick,playing=1,link_ns=0,link_calls=0) + for ns,tick in [(0,599),(8_000_000,600),(108_000_000,601),(116_000_000,1201)]] + report=summarize(rows) + assert report['frames']==2 and report['worst_ms']==100 and report['over50']==1 + + +def test_player_trace_comparison_preserves_gameplay_fields(): + log='network test: tick 30 player 0: (1 2 3) h1/1 m65 | items 4\n' + assert compare_player_traces(log, log.replace('m65', 'm113'))['matched'] + assert not compare_player_traces(log, log.replace('(1 2 3)', '(1 2 4)'))['matched'] + assert not compare_player_traces(log, log.replace('tick 30', 'tick 60'))['matched'] + assert not compare_player_traces('', '')['matched'] diff --git a/tools/test_render_target_binding.py b/tools/test_render_target_binding.py new file mode 100644 index 0000000000..b83b326c19 --- /dev/null +++ b/tools/test_render_target_binding.py @@ -0,0 +1,163 @@ +"""Lazy render-target allocation must preserve already selected texture inputs.""" +import os +from pathlib import Path +import shutil +import subprocess + +import pytest +from harness import function + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.fixture(scope="module") +def target_tool(tmp_path_factory): + compiler = shutil.which("clang") + if compiler is None: + pytest.skip("clang is required") + directory = tmp_path_factory.mktemp("render-target-binding") + source = (ROOT / "port/linux/src/d3d8_gl.c").read_text() + (directory / "under_test.inc").write_text("\n".join( + function(source, name) for name in + ["render_target_bucket", "render_target_remember", "render_target_storage", "render_target_get"])) + (directory / "target.c").write_text(r''' +#include +#include +#include +typedef int BOOL, GLint, GLsizei; +typedef unsigned int GLuint, GLenum; +typedef unsigned long DWORD; +#define TRUE 1 +#define FALSE 0 +#define SCREEN_HEIGHT 480 +#define SECONDARY_TARGET_WIDTH 320 +#define SECONDARY_TARGET_HEIGHT 240 +#define RENDER_TARGET_BUCKET_COUNT 256 +#define RECENT_RENDER_TARGET_COUNT 4 +enum { GL_TEXTURE_2D=1, GL_TEXTURE_BINDING_2D, GL_TEXTURE_MAX_LEVEL, + GL_DEPTH24_STENCIL8, GL_DEPTH32F_STENCIL8, GL_RGBA16F, GL_RGBA8, + GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, GL_FLOAT_32_UNSIGNED_INT_24_8_REV, + GL_RGBA, GL_HALF_FLOAT, GL_BGRA, GL_UNSIGNED_BYTE }; +enum render_target_kind { _render_target_plain, _render_target_screen, _render_target_shadow_map }; +typedef struct { DWORD Data, Format, Size; unsigned long width,height; BOOL depth; } D3DSurface; +struct xgpu_render_target { + unsigned long data,width,height,gl_width,gl_height; + BOOL depth; float scale[2]; GLuint texture; GLenum format; +}; +struct render_target_entry { + struct render_target_entry *next,*next_in_bucket; + struct xgpu_render_target target; + unsigned long last_rendered; BOOL screen_buffer; enum render_target_kind kind; +}; +static struct render_target_entry *render_targets; +static struct render_target_entry *render_target_buckets[RENDER_TARGET_BUCKET_COUNT]; +static struct { DWORD data,format,size; long screen_width; float scale[2]; + struct render_target_entry *entry; } recent_render_targets[RECENT_RENDER_TARGET_COUNT]; +static unsigned long recent_render_target_next; +static float screen_scale[2]={1,1}; +static struct { D3DSurface back_buffer,depth_buffer; } device; +static struct { int active; } hdr; +static int xgpu_reversed_depth; +static unsigned active_unit=3, bindings[4]={81,82,83,99}; +static unsigned next_texture=1000, creates,storage_calls,queries,binds,invalidations; +static unsigned stored_texture; +static GLenum stored_format; +static long halo_screen_width(void) { return 640; } +static int halo_shadow_map_scale(void) { return 1; } +static int surface_is_shadow_map(const D3DSurface *surface) { (void)surface; return 0; } +static void surface_dimensions(const D3DSurface *surface,unsigned long *width,unsigned long *height,BOOL *depth) +{ *width=surface->width;*height=surface->height;*depth=surface->depth; } +static void glGetIntegerv(GLenum name,GLint *value) +{ assert(name==GL_TEXTURE_BINDING_2D);queries++;*value=(GLint)bindings[active_unit]; } +static void glGenTextures(int count,GLuint *texture) +{ assert(count==1);creates++;*texture=next_texture++; } +static void glBindTexture(GLenum target,GLuint texture) +{ assert(target==GL_TEXTURE_2D);binds++;bindings[active_unit]=texture; } +static void glTexParameteri(GLenum target,GLenum name,GLint value) +{ assert(target==GL_TEXTURE_2D && name==GL_TEXTURE_MAX_LEVEL && value==0); } +static void glTexImage2D(GLenum target,int level,GLenum format,GLsizei width,GLsizei height, + int border,GLenum channels,GLenum type,const void *data) +{ + assert(target==GL_TEXTURE_2D && !level && width==128 && height==128 && !border && !data); + assert(bindings[active_unit]>=1000); + assert((format==GL_RGBA8 && channels==GL_BGRA && type==GL_UNSIGNED_BYTE) || + (format==GL_DEPTH24_STENCIL8 && channels==GL_DEPTH_STENCIL && type==GL_UNSIGNED_INT_24_8)); + stored_texture=bindings[active_unit];stored_format=format;storage_calls++; +} +static void xgpu_gl_state_invalidate(void) { invalidations++; } +static void *device_record_new(size_t size) {return calloc(1,size);} +#include "under_test.inc" + +static D3DSurface surface(unsigned long data,int depth) +{ D3DSurface s={0};s.Data=data;s.Format=depth?2:1;s.Size=7;s.width=s.height=128;s.depth=depth;return s; } +static void created(int depth,unsigned input,unsigned unit) +{ + D3DSurface s=surface(0x1000,depth); + struct render_target_entry *entry; + unsigned original[4], before_unit; + active_unit=unit;bindings[unit]=input;before_unit=active_unit; + memcpy(original,bindings,sizeof(bindings)); + entry=render_target_get(&s); + assert(entry && creates==1 && storage_calls==1 && invalidations==1); + assert(entry->target.texture==stored_texture && stored_format==(depth?GL_DEPTH24_STENCIL8:GL_RGBA8)); + /* Sampling input must survive allocating a distinct output image. The + * real failure sampled the new FBO attachment instead (WebGL feedback). */ + assert(active_unit==before_unit && !memcmp(original,bindings,sizeof(bindings))); + assert(bindings[unit]!=entry->target.texture); + assert(queries==1 && binds==2); +} +static void cached(int recent) +{ + D3DSurface s=surface(0x2000,0); + struct render_target_entry entry; + memset(&entry,0,sizeof(entry));entry.target.data=s.Data;entry.target.width=entry.target.height=128; + entry.target.scale[0]=entry.target.scale[1]=1;entry.target.texture=99; + if(recent)render_target_remember(&s,640,&entry);else *render_target_bucket(s.Data)=&entry; + /* Intentional feedback is left for the existing feedback-copy path: + * lookup itself neither substitutes the input nor queries GL state. */ + assert(render_target_get(&s)==&entry); + assert(!queries && !binds && !creates && !storage_calls && bindings[3]==99); +} +int main(int argc,char **argv) +{ + struct render_target_entry *entry,*next; + assert(argc==2); + if(!strcmp(argv[1],"color"))created(0,99,3); + else if(!strcmp(argv[1],"depth"))created(1,99,3); + else if(!strcmp(argv[1],"unbound"))created(0,0,3); + else if(!strcmp(argv[1],"unit-zero"))created(0,81,0); + else if(!strcmp(argv[1],"recent"))cached(1); + else if(!strcmp(argv[1],"bucket"))cached(0); + else if(!strcmp(argv[1],"absent")) { + D3DSurface s=surface(0,0); + assert(!render_target_get(NULL) && !render_target_get(&s)); + assert(!queries && !binds && !creates); + } else if(!strcmp(argv[1],"color-depth")) { + D3DSurface color=surface(0x3000,0),depth=surface(0x4000,1); + struct render_target_entry *c=render_target_get(&color),*d=render_target_get(&depth); + assert(c!=d && creates==2 && storage_calls==2 && queries==2 && binds==4); + assert(bindings[3]==99 && bindings[0]==81 && active_unit==3); + } else if(!strcmp(argv[1],"explicit-bind")) { + D3DSurface s=surface(0x5000,0); + entry=render_target_get(&s); + assert(bindings[3]==99); + glBindTexture(GL_TEXTURE_2D,entry->target.texture); + assert(bindings[3]==entry->target.texture); + } else return 2; + for(entry=render_targets;entry;entry=next) { next=entry->next;free(entry); } + return 0; +} +''') + binary = directory / ("target.exe" if os.name == "nt" else "target") + command = [compiler, "-m32", "-std=gnu89", "-O1", "-Wall", "-Werror", + "-Wno-unused-function", str(directory / "target.c"), "-o", str(binary)] + if os.name == "nt": + command.append("-fuse-ld=lld") + subprocess.run(command, check=True, capture_output=True, text=True) + return binary + + +@pytest.mark.parametrize("case", ["color", "depth", "unbound", "unit-zero", "recent", + "bucket", "absent", "color-depth", "explicit-bind"]) +def test_target_allocation_preserves_sample_binding(target_tool, case): + subprocess.run([str(target_tool), case], check=True, capture_output=True, timeout=10) diff --git a/tools/test_reversed_depth.py b/tools/test_reversed_depth.py new file mode 100644 index 0000000000..9b867e14e4 --- /dev/null +++ b/tools/test_reversed_depth.py @@ -0,0 +1,243 @@ +"""Depth-state regression and optional real GPU checks (HALO_TEST_GPU=1). + +The shader emitter and bias calculations come from the production sources. +GPU checks need GLFW, PyOpenGL and a hidden desktop OpenGL 4.5 context. +""" +import ctypes +import os +import re +import subprocess + +import pytest + +from harness import build, read +from harness.tests.test_plasma_model_shader import shader_source + + +@pytest.fixture(scope='module') +def emitter(): + return build('plasma_model_shader', (('under_test.inc', shader_source('desktop')),)) + + +def emit(emitter, *args): + return subprocess.check_output([emitter, *map(str, args)], text=True) + + +def test_fixed_function_depth_mode(emitter): + normal = emit(emitter, 'fixed', 0) + reversed_shader = emit(emitter, 'fixed', 1) + assert 'depth_bias * gl_Position.w' not in normal + assert 'gl_Position.w - gl_Position.z + depth_bias * gl_Position.w' in reversed_shader + + +def test_desktop_default(): + config = read('port/linux/src/port_config.c') + assert re.search(r'"display.reversed_depth",\s*_config_boolean,\s*"true",' + r'\s*"HALO_REVERSED_DEPTH",\s*_environment_value,\s*_platform_desktop', config) + + +def test_bias_units_and_slope(tmp_path): + renderer = read('port/linux/src/d3d8_gl.c') + bias = re.search(r'converted->depth_bias = .*?;', renderer, re.S).group() + start = renderer.index('offset[0] = dword_to_float(rs[D3DRS_POLYGONOFFSETZSLOPESCALE])') + stop = renderer.index('if (memcmp(gl_state.polygon_offset', start) + slope = renderer[start:stop] + source = r''' +#include +#include +typedef unsigned int DWORD; +enum { D3DRS_SOLIDOFFSETENABLE, D3DRS_POLYGONOFFSETZOFFSET, D3DRS_POLYGONOFFSETZSLOPESCALE }; +static float dword_to_float(DWORD word) { float value; memcpy(&value, &word, 4); return value; } +static DWORD bits(float value) { DWORD word; memcpy(&word, &value, 4); return word; } +int main(void) +{ + struct { float viewport_scale[4]; } device; + struct { float depth_bias; } result, *converted = &result; + DWORD D3D__RenderState[3], *rs = D3D__RenderState; + float ranges[] = {1.0f, 0.1f, 0.75f, 0.0f}; + float scales[] = {1.0f, 1.5f, 2.25f, 4.0f}; + float offset[2], target_scale[2]; + int xgpu_reversed_depth, enabled, range, scale; + rs[D3DRS_POLYGONOFFSETZOFFSET] = bits(-8.0f); + rs[D3DRS_POLYGONOFFSETZSLOPESCALE] = bits(-1.0f); + for (xgpu_reversed_depth = 0; xgpu_reversed_depth < 2; xgpu_reversed_depth++) + for (enabled = 0; enabled < 2; enabled++) + for (range = 0; range < 4; range++) + for (scale = 0; scale < 4; scale++) + { + rs[D3DRS_SOLIDOFFSETENABLE] = enabled; + device.viewport_scale[2] = 16777215.0f * ranges[range]; + target_scale[0] = 1.0f; + target_scale[1] = scales[scale]; +''' + bias + '\n' + slope + r''' + printf("%d %d %.9g %.9g %.9g %.9g %.9g\n", xgpu_reversed_depth, enabled, + ranges[range], scales[scale], converted->depth_bias, offset[0], offset[1]); + } + return 0; +} +''' + path = tmp_path/'depth.c' + path.write_text(source) + binary = tmp_path/('depth.exe' if os.name == 'nt' else 'depth') + subprocess.run(['clang', '-m32', '-std=gnu89', '-Wall', '-Werror', str(path), '-o', str(binary)], check=True) + for line in subprocess.check_output([binary], text=True).splitlines(): + reversed_depth, enabled, span, scale, bias_value, slope_value, units = map(float, line.split()) + expected = 8/16777215 if reversed_depth and enabled and span else 0 + assert bias_value*span == pytest.approx(expected, rel=2e-7, abs=1e-14) + assert slope_value == (scale if reversed_depth else -scale) + assert units == (0 if reversed_depth else -8) + + +@pytest.fixture(scope='module') +def gpu(): + if os.environ.get('HALO_TEST_GPU') != '1': + pytest.skip('Set HALO_TEST_GPU=1 to run hidden OpenGL checks') + import glfw + from OpenGL import GL + assert glfw.init(), 'GLFW initialization failed' + window = None + try: + glfw.window_hint(glfw.VISIBLE, glfw.FALSE) + glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) + glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 5) + glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) + window = glfw.create_window(16, 16, 'Depth regression', None, None) + assert window, 'OpenGL 4.5 context unavailable' + glfw.make_context_current(window) + print('GPU:', GL.glGetString(GL.GL_RENDERER).decode()) + yield GL + finally: + if window: + glfw.destroy_window(window) + glfw.terminate() + + +def test_gpu_stock_shaders(emitter, gpu): + from OpenGL.GL.shaders import compileShader + for reversed_depth in (0, 1): + for enabled in (0, 1): + for index in range(67): + for packed in (0, 1): + shader = compileShader(emit(emitter, 'translated', reversed_depth, index, enabled, packed), + gpu.GL_VERTEX_SHADER) + gpu.glDeleteShader(shader) + + +def test_gpu_projection_precision(emitter, gpu): + """The real projection program must separate distant, closely spaced surfaces.""" + from OpenGL.GL.shaders import compileShader + gl = gpu + shader = compileShader(emit(emitter, 'translated', 1, 0, 0, 0), gl.GL_VERTEX_SHADER) + program = gl.glCreateProgram() + buffer = gl.glGenBuffers(1) + vao = gl.glGenVertexArrays(1) + try: + gl.glAttachShader(program, shader) + names = (ctypes.c_char_p*1)(b'gl_Position') + gl.glTransformFeedbackVaryings(program, 1, + ctypes.cast(names, ctypes.POINTER(ctypes.POINTER(ctypes.c_char))), gl.GL_INTERLEAVED_ATTRIBS) + gl.glLinkProgram(program) + assert gl.glGetProgramiv(program, gl.GL_LINK_STATUS), gl.glGetProgramInfoLog(program) + gl.glUseProgram(program) + gl.glBindVertexArray(vao) + gl.glBindBuffer(gl.GL_TRANSFORM_FEEDBACK_BUFFER, buffer) + gl.glBufferData(gl.GL_TRANSFORM_FEEDBACK_BUFFER, 16, None, gl.GL_STREAM_READ) + gl.glBindBufferBase(gl.GL_TRANSFORM_FEEDBACK_BUFFER, 0, buffer) + gl.glEnable(gl.GL_RASTERIZER_DISCARD) + near, far = 0.0625, 1024 + a = ctypes.c_float(far/(far-near)).value + b = ctypes.c_float(-near*far/(far-near)).value + for name, value in {'c[0]': (1,0,0,0), 'c[1]': (0,1,0,0), + 'c[2]': (0,0,a,b), 'c[3]': (0,0,1,0), 'c[58]': (1,1,1,0), + 'c[59]': (-0.5,-0.5,0,0), 'viewport_scale': (1,1,1,0)}.items(): + gl.glUniform4f(gl.glGetUniformLocation(program, name), *value) + gl.glUniform1f(gl.glGetUniformLocation(program, 'point_size'), 1) + for distance in (near, 1, 10, 100, 500, 1000): + depths = [] + for z in (distance, distance+0.0016): + gl.glVertexAttrib4f(0, 0, 0, z, 1) + gl.glBeginTransformFeedback(gl.GL_POINTS) + gl.glDrawArrays(gl.GL_POINTS, 0, 1) + gl.glEndTransformFeedback() + position = (ctypes.c_float*4)() + gl.glGetBufferSubData(gl.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 16, position) + actual = position[2]/position[3] + expected = ((1-a)*ctypes.c_float(z).value-b)/ctypes.c_float(z).value + assert actual == pytest.approx(expected, rel=2e-6, abs=1e-12) + depths.append(actual) + assert depths[0] > depths[1], (distance, depths) + assert gl.glGetError() == gl.GL_NO_ERROR + finally: + gl.glDisable(gl.GL_RASTERIZER_DISCARD) + gl.glBindBufferBase(gl.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0) + gl.glDeleteBuffers(1, [buffer]) + gl.glDeleteVertexArrays(1, [vao]) + gl.glDeleteProgram(program) + gl.glDeleteShader(shader) + + +@pytest.mark.parametrize('reversed_depth', [False, True]) +@pytest.mark.parametrize('samples', [0, 4]) +def test_gpu_fixed_bias_and_resolve(emitter, gpu, reversed_depth, samples): + from OpenGL.GL.shaders import compileProgram, compileShader + gl = gpu + vertex = compileShader(emit(emitter, 'fixed', int(reversed_depth)), gl.GL_VERTEX_SHADER) + fragment = compileShader('#version 450 core\nout vec4 color; void main(){color=vec4(1);}', gl.GL_FRAGMENT_SHADER) + program = compileProgram(vertex, fragment) + gl.glDeleteShader(vertex) + gl.glDeleteShader(fragment) + buffers, framebuffers = [], [] + vao = gl.glGenVertexArrays(1) + vbo = gl.glGenBuffers(1) + try: + for count in (samples, 0): + fbo = gl.glGenFramebuffers(1) + framebuffers.append(fbo) + gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, fbo) + for attachment, format_ in ((gl.GL_COLOR_ATTACHMENT0, gl.GL_RGBA8), + (gl.GL_DEPTH_STENCIL_ATTACHMENT, gl.GL_DEPTH32F_STENCIL8 if reversed_depth else gl.GL_DEPTH24_STENCIL8)): + renderbuffer = gl.glGenRenderbuffers(1) + buffers.append(renderbuffer) + gl.glBindRenderbuffer(gl.GL_RENDERBUFFER, renderbuffer) + gl.glRenderbufferStorageMultisample(gl.GL_RENDERBUFFER, count, format_, 16, 16) + gl.glFramebufferRenderbuffer(gl.GL_FRAMEBUFFER, attachment, gl.GL_RENDERBUFFER, renderbuffer) + assert gl.glCheckFramebufferStatus(gl.GL_FRAMEBUFFER) == gl.GL_FRAMEBUFFER_COMPLETE + gl.glClipControl(gl.GL_UPPER_LEFT, gl.GL_ZERO_TO_ONE) + gl.glViewport(0, 0, 16, 16) + gl.glEnable(gl.GL_DEPTH_TEST) + gl.glDepthFunc(gl.GL_GREATER if reversed_depth else gl.GL_LESS) + gl.glClearDepth(0 if reversed_depth else 1) + gl.glUseProgram(program) + gl.glBindVertexArray(vao) + gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo) + gl.glEnableVertexAttribArray(0) + gl.glVertexAttribPointer(0, 4, gl.GL_FLOAT, False, 0, None) + location = gl.glGetUniformLocation(program, 'depth_bias') + for span in (1.0, 0.1): + gl.glDepthRange(1-span if reversed_depth else 0, 1 if reversed_depth else span) + for forward in (0.1, 0.9, 0.9999): + vertices = (ctypes.c_float*12)(-1, -1, forward, 1, 3, -1, forward, 1, -1, 3, forward, 1) + gl.glBufferData(gl.GL_ARRAY_BUFFER, ctypes.sizeof(vertices), vertices, gl.GL_STATIC_DRAW) + # Draw with bias, then remove it. A stale uniform must not survive. + for units in (8, 0): + gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, framebuffers[0]) + gl.glClear(gl.GL_DEPTH_BUFFER_BIT | gl.GL_COLOR_BUFFER_BIT) + gl.glUniform1f(location, units/(16777215*span)) + gl.glDrawArrays(gl.GL_TRIANGLES, 0, 3) + gl.glBindFramebuffer(gl.GL_READ_FRAMEBUFFER, framebuffers[0]) + gl.glBindFramebuffer(gl.GL_DRAW_FRAMEBUFFER, framebuffers[1]) + gl.glBlitFramebuffer(0, 0, 16, 16, 0, 0, 16, 16, gl.GL_DEPTH_BUFFER_BIT, gl.GL_NEAREST) + gl.glBindFramebuffer(gl.GL_READ_FRAMEBUFFER, framebuffers[1]) + actual = ctypes.c_float() + gl.glReadPixels(8, 8, 1, 1, gl.GL_DEPTH_COMPONENT, gl.GL_FLOAT, ctypes.byref(actual)) + stored_forward = ctypes.c_float(forward).value + expected = 1-stored_forward*span+units/16777215 if reversed_depth else stored_forward*span + assert actual.value == pytest.approx(expected, abs=1.2e-7) + assert gl.glGetError() == gl.GL_NO_ERROR + finally: + gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0) + gl.glDeleteFramebuffers(len(framebuffers), framebuffers) + gl.glDeleteRenderbuffers(len(buffers), buffers) + gl.glDeleteBuffers(1, [vbo]) + gl.glDeleteVertexArrays(1, [vao]) + gl.glDeleteProgram(program) diff --git a/tools/test_scripted_player_pose.py b/tools/test_scripted_player_pose.py new file mode 100644 index 0000000000..31de744c1d --- /dev/null +++ b/tools/test_scripted_player_pose.py @@ -0,0 +1,236 @@ +"""Host scripted unit state through the production compact wire codec. + +The body, desired facing and current aim intentionally differ, as in the +late-join cinematic capture. Ordinary input must not acquire pose correction. +""" +from pathlib import Path +import subprocess + +import pytest +from harness import constant, enum_with, function, structure +from test_hud_button_style import run_c + +ROOT = Path(__file__).resolve().parents[1] + + +def generated(): + source = (ROOT/'port/linux/game/network_distributed.c').read_text() + header = (ROOT/'port/linux/game/network_distributed.h').read_text() + types = enum_with((ROOT/'source/game/players.h').read_text(), 'NUMBER_OF_PLAYER_POWERUPS,') + types += '\n'.join(enum_with(source, token) for token in ( + '_distributed_unit_alive_bit =', '_distributed_unit_camouflaged_bit =', + '_distributed_unit_part_riding_bit =', '_distributed_pose_facing,')) + types += structure(header, 'distributed_vector') + types += structure((ROOT/'port/linux/game/vehicle_riding.h').read_text(), 'vehicle_riding_deck') + types += structure(source, 'distributed_unit_state') + types += enum_with(source, 'DISTRIBUTED_UNIT_STATE_MINIMUM_SIZE =') + history = constant((ROOT/'source/game/player_queues_new.h').read_text(), 'DISTRIBUTED_INPUT_HISTORY') + routines = '\n'.join(function(source, name) for name in ( + 'distributed_vector_pack', 'distributed_vector_unpack', 'distributed_unit_vector_unpack', + 'distributed_put', 'distributed_take', 'distributed_deck_put', 'distributed_deck_take', 'distributed_scripted_pose_from_unit', + 'distributed_scripted_pose_valid', 'distributed_scripted_pose_apply', + 'distributed_unit_state_write', 'distributed_unit_state_read', 'distributed_handle_predictions')) + return r''' +#include +#include +#include +typedef unsigned char byte; +typedef unsigned short word; +typedef int boolean; +typedef float real; +typedef struct {real i,j,k;} real_vector3d; +typedef struct {real x,y,z;} real_point3d; +#define TRUE 1 +#define FALSE 0 +#define NONE -1 +#define NO_PLAYER 255 +#define FLAG(b) (1u<<(b)) +#define TEST_FLAG(v,b) ((v)&FLAG(b)) +#define SET_FLAG(v,b,on) ((v)=(on)?(v)|FLAG(b):(v)&~FLAG(b)) +#define csmemcpy memcpy +#define csmemset memset +#define DISTRIBUTED_UNIT_SCALE 32767.f +#define DISTRIBUTED_VELOCITY_SCALE 1024.f +#define vehicle_riding_deck_vehicle_named(...) 0 +#define vehicle_riding_deck_valid(...) 0 +#define vehicle_riding_deck_values_valid(...) 0 +#define biped_riding_vehicle_node_count(...) 0 +#define DISTRIBUTED_INPUT_HISTORY HISTORY_COUNT +enum {_game_connection_local, _game_connection_network_server, _game_connection_network_client}; +enum {_unit_suspended_bit=24}; +static int connection,enabled; +static int game_connection(void) {return connection;} +static int player_input_enabled(void) {return enabled;} +struct unit_datum {struct { + unsigned flags; + real_vector3d desired_facing_vector,desired_aiming_vector,desired_looking_vector; + real_vector3d aiming_vector,looking_vector; +} unit;}; +'''.replace('HISTORY_COUNT', str(history)) + types + r''' +#define MAXIMUM_TRACKED_PLAYERS 2 +static struct {boolean valid;long time;struct distributed_unit_state state;} distributed_predictions[2]; +static boolean distributed_machine_has_player(long machine,short player) {return machine==4 && player==0;} +''' + routines + r''' +static void near_vector(real_vector3d a,real_vector3d b) { + assert(fabs(a.i-b.i)<.0001 && fabs(a.j-b.j)<.0001 && fabs(a.k-b.k)<.0001); +} +int main(void) { + struct unit_datum host,client,unchanged; + struct distributed_unit_state sent,received,ordinary; + byte packet[512],bad[512]; + byte const ordinary_wire[11]={0,1,0,42,0,0,0,0,0,0,0}; + byte bounded[DISTRIBUTED_UNIT_STATE_MAXIMUM_SIZE+1]; + word count,plain; + int i,suspended; + memset(&host,0,sizeof(host)); + host.unit.desired_facing_vector.i=-1; + host.unit.desired_aiming_vector.j=1; + host.unit.desired_looking_vector.k=-1; + host.unit.aiming_vector.i=1; + host.unit.looking_vector.j=-1; + for(suspended=0;suspended<2;suspended++) { + memset(&sent,0,sizeof(sent));sent.flags=FLAG(_distributed_unit_alive_bit); + sent.unit_index=42;sent.vehicle_index=NONE;sent.killing_player_index=NO_PLAYER; + sent.forward.i=32767; /* Body direction does not supply the pose. */ + ordinary=sent;plain=distributed_unit_state_write(&ordinary,FALSE,packet); + assert(plain==sizeof(ordinary_wire) && !memcmp(packet,ordinary_wire,plain)); + connection=_game_connection_network_server;enabled=suspended; + host.unit.flags=suspended?FLAG(_unit_suspended_bit):0; + distributed_scripted_pose_from_unit(&host,&sent); + assert(sent.scripted_pose); + count=distributed_unit_state_write(&sent,FALSE,packet); + assert(count==plain+30+(suspended?2:0)); + assert(distributed_unit_state_read(packet,packet+count,&received)==count); + memset(&client,0,sizeof(client));client.unit.flags=1; + distributed_scripted_pose_apply(&client,&received); + near_vector(client.unit.desired_facing_vector,host.unit.desired_facing_vector); + near_vector(client.unit.desired_aiming_vector,host.unit.desired_aiming_vector); + near_vector(client.unit.desired_looking_vector,host.unit.desired_looking_vector); + near_vector(client.unit.aiming_vector,host.unit.aiming_vector); + near_vector(client.unit.looking_vector,host.unit.looking_vector); + assert(client.unit.flags==(1u|host.unit.flags)); + for(i=0;iscripted_pose)\n\t\treturn;', 'return;'), + ('&unit->unit.aiming_vector);', '&unit->unit.desired_aiming_vector);'), + ('state.scripted_pose ||', ''), + ('TEST_FLAG(state.unit_flags, _distributed_unit_suspended_bit) ||', ''), +]) +def test_regression_detects_missing_or_conflated_pose(tmp_path, before, after): + code = generated() + assert before in code + with pytest.raises(subprocess.CalledProcessError): + run_c(tmp_path, code.replace(before, after), link_math=True) + + +def test_pose_is_captured_and_applied_on_existing_unit_state_path(): + source = (ROOT/'port/linux/game/network_distributed.c').read_text() + capture = function(source, 'distributed_state_from_player') + apply = function(source, 'distributed_handle_unit_state') + assert 'distributed_scripted_pose_from_unit(unit, state);' in capture + assert apply.index('network_player_attach_unit(') < apply.index('distributed_scripted_pose_apply(') + + +def test_turn_in_place_reconciles_only_scripted_orientation(tmp_path): + source = (ROOT/'port/linux/game/network_distributed.c').read_text() + body = function(source, 'distributed_apply_state') + run_c(tmp_path, r''' +#include +#include +#include +typedef int boolean; +typedef float real; +typedef struct {real i,j,k;} real_vector3d; +typedef struct {real x,y,z;} real_point3d; +struct distributed_unit_state {real_vector3d velocity,forward,up;int scripted_pose;}; +struct object_datum {struct {real_point3d position;real_vector3d translational_velocity;} object;}; +#define _network_vehicle_write_state 0 +static struct object_datum object; +static struct {int corrections;} distributed_statistics; +static int reconciles; +#define FALSE 0 +#define TRUE 1 +#define DISTRIBUTED_VELOCITY_SCALE 1024 +#define DISTRIBUTED_UNIT_SCALE 32767 +#define UNIT_WORLD_BOUND 32768 +static struct object_datum *object_get(long index) {assert(index==3);return &object;} +static void distributed_vector_unpack(real_vector3d const *a,real scale,real_vector3d *b) {*b=*a;} +static int distributed_point_valid(real_point3d const *p,real limit) {return p->xi==1 && b->k==1;} +static int network_objects_reconcile(long index,real_point3d const *p,real_vector3d const *f, + real_vector3d const *u,real_vector3d const *v,void *angular,real blend,int flags) { + assert(index==3 && f->i==1 && u->k==1);reconciles++;return 0; +} +''' + body + r''' +int main(void) { + struct distributed_unit_state state={{0,0,0},{1,0,0},{0,0,1},0}; + real_point3d p={0,0,0}; + assert(distributed_apply_state(3,&state,&p,NULL,1,1,0,0) && reconciles==0); + state.scripted_pose=1; + assert(distributed_apply_state(3,&state,&p,NULL,1,1,0,0) && reconciles==1); + state.forward.i=0; + assert(!distributed_apply_state(3,&state,&p,NULL,1,1,0,0) && reconciles==1); + state.forward.i=1;p.x=40000; + assert(!distributed_apply_state(3,&state,&p,NULL,1,1,0,0) && reconciles==1); + state.scripted_pose=0;p.x=2; + assert(distributed_apply_state(3,&state,&p,NULL,1,1,0,0) && reconciles==2); + return 0; +} +''', link_math=True) diff --git a/tools/test_shader_prepare.py b/tools/test_shader_prepare.py new file mode 100644 index 0000000000..dcfe0da5df --- /dev/null +++ b/tools/test_shader_prepare.py @@ -0,0 +1,37 @@ +"""Exercise real recipe parsing, map ownership, fallback and bounded recording.""" +from pathlib import Path +import re +import shutil +import subprocess +import sys +import pytest + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.fixture(scope='module') +def checker(tmp_path_factory): + compiler = shutil.which('clang') + if not compiler: + pytest.skip('clang required') + work = tmp_path_factory.mktemp('shader-prepare') + code = (ROOT/'port/linux/src/shader_prepare.h').read_text() + code += re.sub(r'^#include ["<](?:[^"\n]+\.h"|SDL3/SDL.h>)\s*$', '', + (ROOT/'port/linux/src/shader_prepare.c').read_text(), flags=re.M) + (work/'under_test.inc').write_text(code) + path = work/'check.c' + path.write_text((ROOT/'tools/fixtures/shader_prepare_check.c').read_text()) + binary = work/('check.exe' if sys.platform=='win32' else 'check') + command = [compiler, '-std=gnu99', '-O2', '-Wall', '-Wno-unused-function', '-Werror', str(path), '-o', str(binary)] + if sys.platform=='win32': + command[1:1] = ['--target=i686-pc-windows-msvc', '-fuse-ld=lld', '-D_CRT_SECURE_NO_WARNINGS'] + subprocess.run(command, check=True, capture_output=True, text=True) + return binary + + +@pytest.mark.parametrize('case', ['disabled','ownership','cached','failed','allocation','invalid','bounds','toggle', + 'malformed_length','malformed_hash','malformed_terminator','malformed_embedded_nul', + 'malformed_trailing','malformed_duplicate']) +def test_recipes(checker, tmp_path, case): + result = subprocess.run([str(checker), case], cwd=tmp_path, capture_output=True, text=True, timeout=10) + assert result.returncode == 0, result.stdout+result.stderr diff --git a/tools/test_shadow_setup.py b/tools/test_shadow_setup.py new file mode 100644 index 0000000000..a4c9160b97 --- /dev/null +++ b/tools/test_shadow_setup.py @@ -0,0 +1,117 @@ +"""A skipped shadow pass must not expose an uninitialized volume to rendering.""" +import os +from pathlib import Path +import shutil +import subprocess + +import pytest +from harness import enum_with, function + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.fixture(scope="module") +def shadow_tool(tmp_path_factory): + compiler = shutil.which("clang") + if compiler is None: + pytest.skip("clang is required") + directory = tmp_path_factory.mktemp("shadow-setup") + source = (ROOT / "source/rasterizer/xbox/rasterizer_xbox_shadows.c").read_text() + (directory / "under_test.inc").write_text( + enum_with(source, "_rasterizer_target_render_primary =") + "\n" + + function(source, "_rasterizer_environment_shadow_begin")) + (directory / "shadow.c").write_text(r''' +#include +#include +typedef int boolean; +typedef float real; +typedef struct { real i,j,k; } real_vector3d; +typedef struct { real x,y,z; } real_point3d; +typedef struct { real scale; real_vector3d forward,left,up; real_point3d position; } real_matrix4x3; +typedef struct { real red,green,blue; } real_rgb_color; +#define TRUE 1 +#define FALSE 0 +#define match_assert(file,line,condition) assert(condition) +#define csmemset memset +enum { D3DRS_CULLMODE, D3DCULL_CCW, D3DRS_COLORWRITEENABLE, + D3DCOLORWRITEENABLE_RED, D3DCOLORWRITEENABLE_GREEN, D3DCOLORWRITEENABLE_BLUE, + D3DRS_ALPHABLENDENABLE, D3DRS_ALPHATESTENABLE, D3DRS_ALPHAREF, + D3DRS_ZENABLE, D3DRS_ZBIAS, _rasterizer_statistics_mode_enabled }; +static int global_d3d_device=1, device_calls; +static struct { int rasterizer_target; } global_window_parameters; +static struct { int draw_environment_shadows, shadow_debug_enabled, statistics_mode; } rasterizer_debug_options; +static struct { int shadow_count; } rasterizer_frame_statistics; +static struct { int texture_modes,combiner_count,final_combiner_inputs_abcd,final_combiner_inputs_efg; } pixel_shader; +static real_matrix4x3 local_shadow_matrix; +static real_rgb_color local_shadow_color; +static real local_object_bounding_radius; +static int local_parameters, shadow_setup, shadow_used, shadow_restored; +#define IDirect3DDevice8_SetRenderState(...) (++device_calls) +#define IDirect3DDevice8_SetVertexShaderConstant(...) (++device_calls) +#define rasterizer_set_pixel_shader(...) (++device_calls) +#define rasterizer_set_target(...) (++device_calls) +#define rasterizer_set_stencil_mode(...) (++device_calls) +static real dot_product3d(real_vector3d const *a, real_vector3d const *b) +{ return a->i*b->i+a->j*b->j+a->k*b->k; } +#include "under_test.inc" + +static void skipped(int target, int enabled) +{ + real output=-123.0f; + global_window_parameters.rasterizer_target=target; + rasterizer_debug_options.draw_environment_shadows=enabled; + device_calls=0; + local_object_bounding_radius=-456.0f; + local_parameters=shadow_setup=shadow_used=shadow_restored=7; + rasterizer_frame_statistics.shadow_count=0; + /* The caller renders a shadow volume only after a successful begin. + * Ineligible passes must leave both its output and rasterizer state alone. */ + assert(!_rasterizer_environment_shadow_begin(0,NULL,NULL,6.5f,&output)); + assert(output==-123.0f && local_object_bounding_radius==-456.0f); + assert(local_parameters==7 && shadow_setup==7 && shadow_used==7 && shadow_restored==7); + assert(!device_calls && !rasterizer_frame_statistics.shadow_count); +} + +static void enabled(int output_present) +{ + real_matrix4x3 matrix={1,{1,0,0},{0,1,0},{0,0,1},{2,3,4}}; + real_rgb_color color={0.2f,0.3f,0.4f}; + real output=-123.0f; + global_window_parameters.rasterizer_target=0; + rasterizer_debug_options.draw_environment_shadows=1; + rasterizer_debug_options.statistics_mode=_rasterizer_statistics_mode_enabled; + device_calls=0; + rasterizer_frame_statistics.shadow_count=0; + assert(_rasterizer_environment_shadow_begin(0,&matrix,&color,6.5f,output_present?&output:NULL)); + assert(output==(output_present?6.5f:-123.0f)); + assert(local_object_bounding_radius==6.5f); + assert(!memcmp(&matrix,&local_shadow_matrix,sizeof(matrix))); + assert(!memcmp(&color,&local_shadow_color,sizeof(color))); + assert(!local_parameters && !shadow_setup && !shadow_used && !shadow_restored); + assert(device_calls && rasterizer_frame_statistics.shadow_count==1); +} + +int main(int argc,char **argv) +{ + assert(argc==2); + if (!strcmp(argv[1],"secondary")) skipped(1,1); + else if (!strcmp(argv[1],"disabled")) skipped(0,0); + else if (!strcmp(argv[1],"enabled")) { enabled(1); enabled(0); } + else if (!strcmp(argv[1],"transitions")) { + enabled(1); skipped(1,1); enabled(1); skipped(0,0); enabled(1); + } else return 2; + return 0; +} +''') + binary = directory / ("shadow.exe" if os.name == "nt" else "shadow") + command = [compiler, "-m32", "-std=gnu89", "-O1", "-Wall", "-Werror", + "-Wno-unused-but-set-variable", str(directory / "shadow.c"), "-o", str(binary)] + if os.name == "nt": + command.append("-fuse-ld=lld") + subprocess.run(command, check=True, capture_output=True, text=True) + return binary + + +@pytest.mark.parametrize("case", ["secondary", "disabled", "enabled", "transitions"]) +def test_shadow_setup_contract(shadow_tool, case): + subprocess.run([str(shadow_tool), case], check=True, capture_output=True, timeout=10) diff --git a/tools/test_shield_arcs.py b/tools/test_shield_arcs.py new file mode 100644 index 0000000000..c7037fd27e --- /dev/null +++ b/tools/test_shield_arcs.py @@ -0,0 +1,150 @@ +"""Exercise the real depleted-shield gates and private sprite asset lifecycle.""" +import os +from pathlib import Path +import re +import shutil +import struct +import subprocess + +import pytest +from harness import function, structure +from extract_shield_arcs import extract + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.fixture(scope="module") +def arcs_tool(tmp_path_factory): + cc = shutil.which("clang") + if not cc: + pytest.skip("clang required") + work = tmp_path_factory.mktemp("shield-arcs") + source = (ROOT / "port/linux/game/shield_arcs.inl").read_text() + source = source[:source.index("void shield_arcs_draw(")] + source = re.sub(r'^#include.*$', '', source, flags=re.M) + bitmap = (ROOT / "source/bitmaps/bitmap_group.h").read_text() + types = '\n'.join(structure(bitmap, n) for n in ["bitmap_data", "bitmap_group_sprite", "bitmap_group_sequence", "bitmap_group"]) + preamble = r''' +#include +#include +#include +#include +#include +#include +typedef int boolean; +typedef unsigned char byte; +typedef unsigned short word; +typedef float real; +typedef union { float n[4]; struct {float x0,x1,y0,y1;}; } real_rectangle2d; +typedef struct {float x,y;} real_point2d; +union point2d {short n[2];}; +struct tag_block {long count;void *address,*definition;}; +struct tag_data {long size;char pad[16];}; +#define NONE (-1) +#define TRUE 1 +#define FALSE 0 +#define TEST_FLAG(value,bit) ((value)&(1U<<(bit))) +enum {_object_type_biped=0,_object_dead_bit=0,_object_shield_depleted_bit=1}; +struct object_datum {struct {short type;unsigned damage_flags;float shield_vitality;short shield_stun_ticks;} object;}; +struct unit_datum {struct {short type;unsigned damage_flags;float shield_vitality;short shield_stun_ticks;} object;struct {long player_index;} unit;}; +static int enhanced=1,arms_enabled=1,creates,deletes,fail_texture; +static int shield_look_enabled(void) {return enhanced;} +int config_boolean(const char *name) {(void)name;return arms_enabled;} +void platform_log(const char *format,...) {(void)format;} +static const char *asset_path; +static FILE *asset_open(const char *path,const char *mode) {(void)path;return fopen(asset_path,mode);} +#define fopen asset_open +static void checked_free(void *p) {assert(p);free(p);} +#define free checked_free +''' + preamble += function((ROOT / "port/linux/game/shield_look.c").read_text(), "shield_look_player") + stubs = r''' +static int rasterizer_bitmap_new(struct bitmap_data *b) { + assert(b->flags==3);assert(b->mipmap_count==2);assert(b->pixels_size==172032); + if(fail_texture && creates==1)return 0; + b->hardware_format=(void*)1;creates++;return 1; +} +static void rasterizer_bitmap_changed(struct bitmap_data *b) {assert(b->base_address);} +static void rasterizer_bitmap_delete(struct bitmap_data *b) {assert(b->hardware_format);b->hardware_format=NULL;deletes++;} +static void *table; +static long table_count; +void *cache_files_tag_instances(long *count) {*count=table_count;return table;} +void cache_files_set_tag_instances(void *p,long count) {table=p;table_count=count;} +''' + main = r''' +int main(int argc,char **argv) { + struct unit_datum object={{0,2,0.f,30},{0}}; + struct shield_arcs_tag original[10]; + int i,expected; + assert(argc==3);asset_path=argv[2]; + assert(shield_arcs_active((struct object_datum *)&object,0));assert(shield_arcs_active((struct object_datum *)&object,1)); + object.unit.player_index=NONE;assert(!shield_arcs_active((struct object_datum *)&object,0));assert(!shield_arcs_active((struct object_datum *)&object,1)); + object.unit.player_index=17;assert(shield_arcs_active((struct object_datum *)&object,0)); + enhanced=0;assert(!shield_arcs_active((struct object_datum *)&object,0));enhanced=1; + arms_enabled=0;assert(!shield_arcs_active((struct object_datum *)&object,1));assert(shield_arcs_active((struct object_datum *)&object,0));arms_enabled=1; + assert(!shield_arcs_active(NULL,0)); + object.object.damage_flags=3;assert(!shield_arcs_active((struct object_datum *)&object,0)); + object.object.damage_flags=0;assert(!shield_arcs_active((struct object_datum *)&object,0));object.object.damage_flags=2; + object.object.shield_vitality=.01f;assert(!shield_arcs_active((struct object_datum *)&object,0));object.object.shield_vitality=0; + object.object.shield_stun_ticks=0;assert(!shield_arcs_active((struct object_datum *)&object,0));object.object.shield_stun_ticks=30; + object.object.type=1;assert(!shield_arcs_active((struct object_datum *)&object,0)); + assert(shield_arcs_random(123)==shield_arcs_random(123));assert(shield_arcs_random(123)!=shield_arcs_random(124)); + table=original;table_count=10;expected=!strcmp(argv[1],"valid");fail_texture=!strcmp(argv[1],"texture-failure"); + shield_arcs_unload(); /* safe before any lazy load */ + for(i=0;i<3;i++) { + creates=deletes=0; + assert(shield_arcs_load()==expected); + assert(shield_arcs_load()==expected); /* only one attempt per map */ + assert(table_count==(expected?11:10)); + if(expected) {assert(creates==2);assert(table!=original);assert(shield_arcs_table[10].address==&shield_arcs_bitmap_group);} + else assert(table==original); + shield_arcs_unload();assert(table==original);assert(table_count==10);assert(deletes==creates); + assert(!shield_arcs_asset && !shield_arcs_table && shield_arcs_index==NONE); + shield_arcs_unload(); + } + return 0; +} +''' + (work / "test.c").write_text(preamble + types + stubs + source + main) + output = work / ("test.exe" if os.name == "nt" else "test") + flags = ["-m32", "-std=gnu89", "-Werror", "-Wno-multichar"] + if os.name == "nt": + flags += ["--target=i686-pc-windows-msvc", "-fuse-ld=lld", "-D_CRT_SECURE_NO_WARNINGS"] + result = subprocess.run([cc, *flags, str(work / "test.c"), "-o", str(output)], capture_output=True, text=True) + assert result.returncode == 0, result.stdout + result.stderr + return output + + +def asset(): + sprite = struct.pack(" +typedef int boolean; +typedef float real; +#define FALSE 0 +#define TRUE 1 +#define NONE (-1) +#define SHIELD_GLOW_MAXIMUM 8 +static short host_choice = NONE; +static int local_glow, local_overshield; +static unsigned long changes; +static char const *intensity = "default"; +static short network_shield_effects(void) { return host_choice; } +static unsigned long config_changes(void) { return changes; } +static int config_boolean(char const *key) { + return !strcmp(key, "display.shield_glow") ? local_glow : local_overshield; +} +static char const *config_string(char const *key) { (void)key; return intensity; } +''' + code += enum_with(policy, "_shield_effects_stock") + code += structure(glow, "shield_glow") + code += "\nstatic struct shield_glow shield_glows[8];\n" + code += "static real shield_glow_time;\nstatic real shield_glow_scale = 1.f;\n" + code += "static boolean overshield_effects_initialized;\nstatic void overshield_effect_reset(void) {}\n" + code += function(glow, "shield_glow_reset") + code += function(glow, "shield_glow_enabled") + code += function(overshield, "overshield_effect_enabled") + code += r''' +int main(void) { + int choice, i; + if (shield_glow_enabled() || overshield_effect_enabled()) return 1; + local_glow = local_overshield = 1; intensity = "light_show"; changes++; + if (!shield_glow_enabled() || shield_glow_scale != 3.f || !overshield_effect_enabled()) return 2; + for (choice = 0; choice < NUMBER_OF_SHIELD_EFFECTS; choice++) { + host_choice = (short)choice; + if (shield_glow_enabled() != (choice != 0 && choice != 3)) return 3; + if (overshield_effect_enabled() != (choice >= 3)) return 4; + if (shield_glow_scale != ((choice == 2 || choice == 5) ? 3.f : 1.f)) return 5; + } + host_choice = NONE; + if (!shield_glow_enabled() || shield_glow_scale != 3.f || !overshield_effect_enabled()) return 6; + local_glow = local_overshield = 0; changes++; + if (shield_glow_enabled() || overshield_effect_enabled()) return 7; + memset(shield_glows, 0x55, sizeof(shield_glows)); shield_glow_time = 100; + shield_glow_reset(); shield_glow_reset(); + if (shield_glow_time) return 8; + for (i = 0; i < 8; i++) + if (shield_glows[i].unit_index != NONE || shield_glows[i].light_index != NONE || shield_glows[i].connected) return 9; + return 0; +} +''' + source = tmp_path / "glow.c" + source.write_text(code) + exe = compile_tool(tmp_path, [source]) + result = subprocess.run([str(exe)], capture_output=True, text=True, timeout=10) + assert result.returncode == 0, result.stdout + result.stderr + + +def test_glow_lifetime_is_owned_by_map_lights(): + lights = (ROOT / "source/objects/object_lights.c").read_text() + for name in ("lights_initialize_for_new_map", "lights_dispose_from_old_map"): + assert "shield_glow_reset();" in function(lights, name) + assert "lights_initialize_for_new_map();" in function(lights, "lights_port_recover") diff --git a/tools/test_shield_honeycomb.py b/tools/test_shield_honeycomb.py new file mode 100644 index 0000000000..5fe20d06ab --- /dev/null +++ b/tools/test_shield_honeycomb.py @@ -0,0 +1,223 @@ +"""Draw-local honeycomb uniforms must preserve colours and clear between passes.""" +import os +import ast +from pathlib import Path +import re +import shutil +import subprocess + +import pytest +from harness import function + +ROOT = Path(__file__).resolve().parents[1] + + +def test_hex_links_are_continuous_across_cells(tmp_path): + """Execute the shipped pattern with fixed pixel derivatives, not a copy. + + A per-cell pulse makes opposite sides of the same link disagree. Sample + all six shared edges over time, including translated negative UVs. + """ + cc = shutil.which("clang++") + if not cc: + pytest.skip("clang++ required") + header = (ROOT / "port/linux/src/shield_honeycomb_gl.h").read_text() + glsl = "".join(ast.literal_eval(s) for s in re.findall(r'"(?:\\.|[^"\\])*"', header)) + pattern = glsl[glsl.index("float shield_hex("):glsl.index("vec4 shield_honeycomb_surface(")] + source = r""" +#include +#include +#include +using std::min; using std::max; +struct vec2 { + double x, y; + vec2(double a, double b): x(a), y(b) {} +}; +vec2 operator-(vec2 a, vec2 b) { return vec2(a.x-b.x,a.y-b.y); } +vec2 operator*(vec2 a, double b) { return vec2(a.x*b,a.y*b); } +vec2 mod(vec2 a, vec2 b) { return vec2(a.x-floor(a.x/b.x)*b.x,a.y-floor(a.y/b.y)*b.y); } +vec2 abs(vec2 a) { return vec2(fabs(a.x),fabs(a.y)); } +double dot(vec2 a, vec2 b) { return a.x*b.x+a.y*b.y; } +double length(vec2 a) { return sqrt(dot(a,a)); } +double footprint = 0.02; +vec2 dFdx(vec2) { return vec2(footprint,0); } +vec2 dFdy(vec2) { return vec2(0,footprint); } +double clamp(double x, double a, double b) { return min(max(x,a),b); } +double smoothstep(double a, double b, double x) { + double t = clamp((x-a)/(b-a),0.,1.); return t*t*(3.-2.*t); +} +double mix(double a, double b, double t) { return a+(b-a)*t; } +""" + pattern.replace("float", "double") + r""" +int main() { + const double pi = 3.141592653589793; + for (int tile=-3; tile<=3; ++tile) { + for (int edge=0; edge<6; ++edge) { + double angle=edge*pi/3.; + vec2 normal(cos(angle),sin(angle)); + double lowest=10., highest=0.; + for (int time=0; time<200; ++time) { + vec2 inside(normal.x*(0.8660254-0.00001)+tile*1.7320508, + normal.y*(0.8660254-0.00001)); + vec2 outside(normal.x*(0.8660254+0.00001)+tile*1.7320508, + normal.y*(0.8660254+0.00001)); + double a=shield_hex(inside,time*0.07), b=shield_hex(outside,time*0.07); + assert(std::isfinite(a) && std::isfinite(b)); + assert(fabs(a-b)<0.001); + assert(a>0.2); // Links dim without disappearing between pulses. + lowest=min(lowest,a); highest=max(highest,a); + } + assert(highest>lowest*2.); // The pulse remains visibly distinct. + } + } + footprint=2.; // Unresolved cells converge instead of sparkling as UVs move. + double average=shield_hex(vec2(0.,0.),0.); + for (int i=0; i<100; ++i) + assert(fabs(shield_hex(vec2(i*0.137,-i*0.193),i*0.31)-average)<0.00001); +} +""" + path = tmp_path / "links.cpp" + path.write_text(source) + exe = tmp_path / ("links.exe" if os.name == "nt" else "links") + subprocess.run([cc, "-std=c++17", str(path), "-o", str(exe)], check=True) + subprocess.run([str(exe)], check=True) + + +def test_draw_uniform_lifetime(tmp_path): + cc = shutil.which("clang") + if not cc: + pytest.skip("clang required") + renderer = (ROOT / "port/linux/src/d3d8_gl.c").read_text() + source = """ +#include +#include +static float shield_honeycomb_value[3][4]; +""" + function(renderer, "d3d8_gl_set_shield_honeycomb") + """ +int main(void) { + float difference[4] = {.1f, -.2f, .3f, 0.f}; + float parallel[4] = {.5f, .6f, .7f, .47f}; + float saved[4]; + memcpy(saved, parallel, sizeof(saved)); + assert(shield_honeycomb_value[0][3] == 0.f); + assert(shield_honeycomb_value[0][0] == 0.f); + d3d8_gl_set_shield_honeycomb(18.f, 12.f, difference, parallel, 0.f); + assert(shield_honeycomb_value[0][3] == 18.f); + assert(!memcmp(shield_honeycomb_value[1], difference, 3 * sizeof(float))); + assert(shield_honeycomb_value[1][3] == 12.f); + assert(!memcmp(shield_honeycomb_value[2], saved, sizeof(saved))); + assert(!memcmp(parallel, saved, sizeof(saved))); + d3d8_gl_set_shield_honeycomb(0.f, 0.f, NULL, NULL, 0.f); + assert(shield_honeycomb_value[0][3] == 0.f); + assert(shield_honeycomb_value[0][0] == 0.f); + parallel[0] = 0.f; parallel[1] = 1.f; parallel[2] = 0.f; + d3d8_gl_set_shield_honeycomb(45.f, 13.f, difference, parallel, 1.f); + assert(!memcmp(shield_honeycomb_value[2], parallel, sizeof(parallel))); + assert(shield_honeycomb_value[0][3] == 45.f); + assert(shield_honeycomb_value[0][0] == 1.f); + d3d8_gl_set_shield_honeycomb(0.f, 0.f, NULL, NULL, 0.f); + assert(shield_honeycomb_value[0][3] == 0.f); + assert(shield_honeycomb_value[0][0] == 0.f); + return 0; +} +""" + path = tmp_path / "uniforms.c" + path.write_text(source) + exe = tmp_path / ("uniforms.exe" if os.name == "nt" else "uniforms") + subprocess.run([cc, "-std=gnu89", "-Wall", "-Werror", str(path), "-o", str(exe)], check=True) + subprocess.run([str(exe)], check=True) + + +def test_classic_composite_keeps_resolved_color(tmp_path): + """Execute the surface composition with varying plasma, grid and colours.""" + cc = shutil.which("clang++") + if not cc: + pytest.skip("clang++ required") + header = (ROOT / "port/linux/src/shield_honeycomb_gl.h").read_text() + glsl = "".join(ast.literal_eval(s) for s in re.findall(r'"(?:\\.|[^"\\])*"', header)) + surface = glsl[glsl.index("vec4 shield_honeycomb_surface("):] + surface = surface.replace(".rgb", ".rgb()") + source = r""" +#include +#include +#include +using std::min; using std::max; +struct vec2 { float x,y; vec2 operator*(float f) { return {x*f,y*f}; } }; +struct vec3 { float x,y,z; + vec3 operator+(vec3 b) { return {x+b.x,y+b.y,z+b.z}; } + vec3 operator*(float f) { return {x*f,y*f,z*f}; } +}; +vec3 clamp(vec3 c,float lo,float hi) { return {min(max(c.x,lo),hi),min(max(c.y,lo),hi),min(max(c.z,lo),hi)}; } +struct vec4 { float x,y,z; union {float w; float a;}; + vec4(): x(0),y(0),z(0),w(0) {} + vec4(vec3 c,float alpha): x(c.x),y(c.y),z(c.z),w(alpha) {} + vec3 rgb() { return {x,y,z}; } +}; +vec4 shield_honeycomb[3],xD0,xD1; +vec2 shield_uv; +float grid; +float shield_hex(vec2,float) { return grid; } +""" + surface + r""" +int main() { + xD0.a=1.f; shield_honeycomb[2].a=.5f; + for(int c=0;c<6;c++) for(int a=0;a<10;a++) { + vec4 original({c*.13f,1.f-c*.11f,c*.07f},a*.07f); + shield_honeycomb[0].w=0.f; + vec4 off=shield_honeycomb_surface(original); + assert(off.x==original.x && off.y==original.y && off.z==original.z && off.a==original.a); + shield_honeycomb[0].w=87.5f; shield_honeycomb[0].x=1.f; + grid=.2f; vec4 dim=shield_honeycomb_surface(original); + grid=.9f; vec4 bright=shield_honeycomb_surface(original); + assert(dim.x==original.x && dim.y==original.y && dim.z==original.z); + assert(bright.x==original.x && bright.y==original.y && bright.z==original.z); + assert(bright.a>dim.a && dim.a>=original.a*.65f); + assert(fabs(bright.a-(original.a*.65f+.5f*grid*.65f))<.00001f); + xD1=vec4({0.f,.6f,1.f},.5f); + shield_honeycomb[0].x=3.f; + // Keep the grid fixed: only the real plasma changes over time. + vec4 dark({0.f,0.f,0.f},original.a); + vec4 lit({0.f,.48f,.8f},original.a); + grid=0.f; vec4 low_base=shield_honeycomb_surface(dark); + vec4 high_base=shield_honeycomb_surface(lit); + grid=.9f; vec4 low=shield_honeycomb_surface(dark); + vec4 high=shield_honeycomb_surface(lit); + assert(low.z>low_base.z); // A faint continuous link in dark gaps. + assert(high.z-high_base.z > 10.f*(low.z-low_base.z)); + assert(high.a==original.a && low.a==original.a); + assert(low.x==0.f && fabs(low.y/low.z-.6f)<.00001f); + assert(high.x==0.f && fabs(high.y/high.z-.6f)<.00001f); + // Classic white highlights must light the links too, as on arms. + vec4 highlight({.8f,.8f,.8f},original.a); + vec4 white=shield_honeycomb_surface(highlight); + assert(white.x>.45f*.8f); // Palette red is zero, but plasma has a highlight. + xD1=vec4({1.f,0.f,0.f},.5f); + vec4 red=shield_honeycomb_surface(vec4({.8f,0.f,0.f},original.a)); + assert(fabs(red.x-high.z)<.00001f && red.y==0.f && red.z==0.f); + shield_honeycomb[0].x=1.f; + vec4 arms_again=shield_honeycomb_surface(original); + assert(arms_again.x==bright.x && arms_again.y==bright.y && arms_again.z==bright.z && arms_again.a==bright.a); + } + shield_honeycomb[0].x=1.f; xD0.a=0.f; + assert(shield_honeycomb_surface(vec4({1.f,1.f,1.f},0.f)).a==0.f); +} +""" + path = tmp_path / "composite.cpp" + path.write_text(source) + exe = tmp_path / ("composite.exe" if os.name == "nt" else "composite") + # GLSL literals are floats; preserve that when compiling the actual formula. + source = re.sub(r"(?shader);") + submit = draw.index("rasterizer_transparent_geometry_group_draw__internal(", start) + clear = draw.index("d3d8_gl_set_shield_honeycomb(0.f", submit) + assert draw.index("overshield_effect_color(") < start < submit < clear + assert "color_constants[1], color_constants[2]" in draw[start:submit] + assert "D3DCULL_CCW" in draw[start:submit] + assert "D3DCULL_NONE" in draw[submit:clear] + glsl = (ROOT / "port/linux/src/shield_honeycomb_gl.h").read_text() + assert "if (shield_honeycomb[0].w == 0.0) return original;" in glsl diff --git a/tools/test_shield_look.py b/tools/test_shield_look.py new file mode 100644 index 0000000000..73ca09af65 --- /dev/null +++ b/tools/test_shield_look.py @@ -0,0 +1,273 @@ +"""Compile the actual shield-look module against a small 32-bit fake map. + +SHIELD_LOOK_CC can name a portable compiler wrapper. Optional reference checks +use SHIELD_LOOK_REFERENCE_MAP and SHIELD_LOOK_STOCK_MAP, never bundled assets. +""" +import os +from pathlib import Path +import re +import shutil +import struct +import subprocess +import sys +import xml.etree.ElementTree as ET +import zlib + +import pytest + +from harness import function, structure + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.fixture(scope="module") +def shield_tool(tmp_path_factory): + cc = os.environ.get("SHIELD_LOOK_CC") or shutil.which("clang") + if not cc: + pytest.skip("a 32-bit C compiler is required") + work = tmp_path_factory.mktemp("shield-look") + source = (ROOT / "port/linux/game/shield_look.c").read_text() + source = re.sub(r'^#include "[^"\n]+"\s*$', '', source, flags=re.M) + # Stub successful cache discovery separately from the real bitmap reader. + source = source.replace("static boolean shield_look_stock_noise(", "static boolean shield_look_read_noise(") + source = source.replace("shield_look_stock_noise(index)", "(index == 3 ? noise_matches : 1)") + shader_header = (ROOT / "source/shaders/shader_definitions.h").read_text() + object_header = (ROOT / "source/objects/object_definitions.h").read_text() + structs = "\n".join(structure(shader_header, n) for n in + ("shader_radiosity_properties", "shader_physics_properties", "shader_base", "shader")) + structs += "\n" + structure(object_header, "object_function_definition") + (work / "real_types.inc").write_text(structs) + overshield = (ROOT / "port/linux/game/overshield_effect.c").read_text() + source += "\n" + structure(overshield, "overshield_effect_plasma") + source += "\n" + function(overshield, "overshield_effect_intensity_source") + (work / "under_test.inc").write_text(source) + output = work / ("shield.exe" if os.name == "nt" else "shield") + flags = ["-m32", "-std=gnu89", "-Wall", "-Werror", "-Wno-unused-function", "-Wno-multichar"] + if os.name == "nt" and not os.environ.get("SHIELD_LOOK_CC"): + flags += ["--target=i686-pc-windows-msvc", "-fuse-ld=lld", "-D_CRT_SECURE_NO_WARNINGS"] + command = [cc, *flags, "-I", str(work), str(ROOT / "tools/harness/tests/shield_look.c"), "-o", str(output)] + result = subprocess.run(command, capture_output=True, text=True) + assert result.returncode == 0, result.stdout + result.stderr + return output + + +@pytest.mark.parametrize("case", ["colors", "classic", "invalid-setting", "profiles", "authored-shader", "authored-noise", + "authored-function", "authored-channel", "authored-nonplasma", "authored-environment", "authored-hands", "authored-body", "authored-decal", "missing", "no-noise", "split", + "toggle", "outer", "arms-off", "reload", "capacity", "malformed-noise"]) +@pytest.mark.parametrize("look", ["enhanced", "enhanced2"]) +def test_shield_look(shield_tool, case, look): + run = subprocess.run([str(shield_tool), case, look], capture_output=True, text=True, timeout=15) + assert run.returncode == 0, run.stdout + run.stderr + + +def test_menu_and_default(): + sys.path.insert(0, str(ROOT / "tools")) + import port_settings + spec = port_settings.SCREENS["video_settings/fov_viewmodels"] + row = next(row for row in spec["rows"] if row[1] == "display.shield_look") + assert row[2] == [("DEFAULT", "classic"), ("CLASSIC WITH SPRINKLES", "classic_with_sprinkles"), ("MARK VI", "enhanced"), ("INFINITE HONEYCOMB", "classic_honeycomb2")] + assert "video_settings/shield_look" not in port_settings.SCREENS + assert not list((ROOT / "port/assets/menus/ce").glob("*.shield_look.xml")) + assert "video_settings.shield_look.xml" not in (ROOT / "port/assets/menus/menus.json").read_text() + config = (ROOT / "port/linux/src/port_config.c").read_text() + assert re.search(r'"display.shield_look", _config_string, "\\"classic\\"", "HALO_SHIELD_LOOK"', config) + for name, lines in port_settings.settings_files().items(): + if "video_settings" in name: + assert (ROOT / "port/assets/menus/ce" / name).read_text() == "\n".join(lines) + if name.endswith(".video_settings.xml"): + widgets = {w.attrib["name"]: w for w in ET.fromstring("\n".join(lines)).findall("widget")} + options = next(w for key, w in widgets.items() if key.endswith("/options_menu")) + help_top = int(next(w for key, w in widgets.items() if key.endswith("/help")).attrib["top"]) + for child in options.findall("child"): + if "/op_" in child.attrib["widget"]: + row = widgets[child.attrib["widget"]] + assert int(child.attrib["y"]) + int(row.attrib["height"]) <= help_top + + +def test_shared_hooks(): + source = (ROOT / "source/interface/first_person_weapons.c").read_text() + draw = function(source, "first_person_weapon_draw") + weapon, hands = [m.start() for m in re.finditer(r'\brender_model\(', draw)] + assert weapon < draw.index("viewmodel_shield_apply(") < draw.index("shield_look_arms(") < hands + cache = (ROOT / "source/cache/cache_files.c").read_text() + assert "shield_look_reset();" in function(cache, "scenario_tags_load") + assert "shield_look_reset();" in function(cache, "scenario_tags_unload") + models = (ROOT / "source/models/models.c").read_text() + assert "shield_look_skip_shell(object_index, model, shader," in function(models, "render_model_parts") + plasma = (ROOT / "source/rasterizer/xbox/rasterizer_xbox_plasma_energy.c").read_text() + draw = function(plasma, "rasterizer_plasma_energy_draw") + assert draw.index("shield_look_colors(") < draw.index("overshield_effect_color(") + objects = (ROOT / "source/render/render_objects.c").read_text() + assert "shield_look_body(object_index, model_effect.modifier_shader)" in objects + + +def map_tags(path): + data = path.read_bytes() + version = struct.unpack_from("> level + bits = 5 - level + for z in range(width): + for y in range(width): + for x in range(width): + swizzled = sum(((axis >> bit) & 1) << (3 * bit + dimension) + for dimension, axis in enumerate((x, y, z)) for bit in range(bits)) + linear = (z * width + y) * width + x + luminance, alpha = xbox[(position + swizzled) * 2:(position + swizzled) * 2 + 2] + rgba = cmt_pixels[(position + linear) * 4:(position + linear) * 4 + 4] + assert rgba == bytes((luminance, luminance, luminance, alpha)) + packed[(position + swizzled) * 4:(position + swizzled) * 4 + 4] = rgba + position += width ** 3 + assert position == 37449 + shader_path = tmp_path / "shader.bin" + pixels_path = tmp_path / "noise.bin" + shader_path.write_bytes(tags[shader_offset:shader_offset + 0x14C]) + # The real feature reader accepts CE's linear pixels and the same pixels + # in the hardware layout produced by the existing MCC adapter. + for layout, pixels in (("ce", cmt_pixels), ("mcc", packed)): + pixels_path.write_bytes(pixels) + result = subprocess.run([str(shield_tool), "reference", str(shader_path), str(pixels_path), layout], + capture_output=True, text=True, timeout=15) + assert result.returncode == 0, result.stdout + result.stderr + + +def test_sprinkles(shield_tool): + run = subprocess.run([str(shield_tool), "sprinkles"], capture_output=True, text=True, timeout=15) + assert run.returncode == 0, run.stdout + run.stderr + + +def test_sprinkles_stock_surface(shield_tool): + path = os.environ.get("SHIELD_LOOK_STOCK_MAP") + if not path: + pytest.skip("set SHIELD_LOOK_STOCK_MAP for the classic surface comparison") + _, tags, entries, _ = map_tags(Path(path)) + at = next(e[2] for e in entries if e[1] == r"characters\cyborg\shaders\shield hit") + stock = bytearray(tags[at:at + 0x14C]) + body, arms = bytearray(stock), bytearray(stock) + struct.pack_into(" +#include +#include +typedef float real; +typedef int boolean; +#define TRUE 1 +#define FALSE 0 +#define MAX(a,b) ((a)>(b)?(a):(b)) +#define MIN(a,b) ((a)<(b)?(a):(b)) +#define PIN(x,a,b) MAX(a,MIN(x,b)) +#define TEST_FLAG(x,b) ((x)&(1U<<(b))) +enum {_object_type_biped=0,_object_dead_bit=0,_object_shield_depleted_bit=1,_object_shield_over_charging_bit=2,_object_shield_charging_bit=3}; +struct object_datum {struct {int type;unsigned damage_flags;int shield_stun_ticks;float shield_vitality;} object;}; +struct unit_datum {struct {int type;unsigned damage_flags;int shield_stun_ticks;float shield_vitality;} object;struct {long player_index;} unit;}; +#define NONE (-1) +struct shader {int id;}; +struct shield_look_plasma {struct shader shader;real offset_amount;}; +struct {struct shield_look_plasma body,arms;boolean sprinkles;} shield_looks[2]; +static short shield_look_count=2; +struct render_model_effect {struct shader *modifier_shader;struct {real const *values;} modifier_animation;}; +struct {real game_time_sec;} global_frame_parameters; +static struct unit_datum objects[140]; +static int enhanced=1,arms=1; +static unsigned long changes=1; +static real body_values[140][4],arm_values[2][4]; +static struct object_datum *object_try_and_get(long n) {return n>=0 && n<140?(struct object_datum *)&objects[n]:NULL;} +static int shield_look_enabled(void) {return enhanced;} +unsigned long config_changes(void) {return changes;} +int config_boolean(char const *name) {(void)name;return arms;} +static real viewmodel_shield_offset_amount(real const *values,real amount) { + return values==arm_values[0] || values==arm_values[1]?MIN(amount,.004f):amount; +} +''' + preamble += function((ROOT / "port/linux/game/shield_look.c").read_text(), "shield_look_player") + main = r''' +static struct render_model_effect prepare(long n,real level,real time,int side) { + struct render_model_effect e; + objects[n].object.shield_vitality=level; + global_frame_parameters.game_time_sec=time; + e.modifier_shader=side?&shield_looks[0].arms.shader:&shield_looks[0].body.shader; + e.modifier_animation.values=side?arm_values[side-1]:body_values[n]; + shield_recharge_prepare(n,&e,side!=0);return e; +} +static void draw(struct render_model_effect *e,real *intensity,real *offset) { + shield_recharge_draw(e->modifier_shader,e->modifier_animation.values,intensity,offset); +} +int main(int argc,char **argv) { + struct render_model_effect e,a,b; + struct shield_look_plasma original; + real i,o,low,high; + int n; + assert(argc==2); + for(n=0;n<140;n++)objects[n].object.damage_flags=8; + shield_looks[0].body.offset_amount=.0125f;shield_looks[0].arms.offset_amount=.03f; + original=shield_looks[0].body;shield_recharge_reset(); + e=prepare(0,.01f,1.f,0);i=o=0;draw(&e,&i,&o);assert(i>0 && i<.1f);low=o; + e=prepare(0,.5f,1.5f,0);i=o=0;draw(&e,&i,&o);assert(i>.2f && i<.5f);assert(o>low);low=o; + e=prepare(0,.999f,2.f,0);i=o=0;draw(&e,&i,&o);assert(o>low && o<.0145f);high=o; + e=prepare(0,1.f,2.01f,0);i=o=0;draw(&e,&i,&o);assert(o>=high); + e=prepare(0,1.f,2.26f,0);i=o=0;draw(&e,&i,&o);assert(o>0 && o0 && ienhanced_i && i<=enhanced_i*1.75f); + assert(o==enhanced_o); + shield_looks[0].sprinkles=0;e=prepare(0,1.f,t,0);i=o=0;draw(&e,&i,&o); + assert(i==enhanced_i && o==enhanced_o); + shield_looks[0].sprinkles=1; + } + e=prepare(0,1.f,4.61f,0);i=.123f;o=.002f;draw(&e,&i,&o);assert(i==.123f && o==.002f); + assert(!shield_recharge_visible(e.modifier_shader,e.modifier_animation.values)); + shield_recharge_reset();a=prepare(0,.5f,5.f,1);i=o=0;draw(&a,&i,&o);assert(o<=.004f); + arms=0;changes++;assert(!shield_recharge_visible(a.modifier_shader,a.modifier_animation.values));return 0; + } + else if(!strcmp(argv[1],"arms")) { + a=prepare(0,.5f,3.f,1);b=prepare(1,.8f,3.f,2); + i=o=0;draw(&a,&i,&o);assert(o>0 && o<=.004f);low=o; + i=o=0;draw(&b,&i,&o);assert(o>low && o<=.004f); + arms=0;changes++;a=prepare(0,.5f,3.1f,1);assert(!shield_recharge_visible(a.modifier_shader,a.modifier_animation.values)); + e=prepare(0,.5f,3.1f,0);assert(shield_recharge_visible(e.modifier_shader,e.modifier_animation.values));return 0; + } + else if(!strcmp(argv[1],"respawn")) { + a=prepare(0,.5f,3.f,1);b=prepare(1,1.f,3.f,1); + assert(!shield_recharge_visible(a.modifier_shader,a.modifier_animation.values));return 0; + } + else if(!strcmp(argv[1],"time")) { + global_frame_parameters.game_time_sec=3.1f;assert(!shield_recharge_visible(e.modifier_shader,e.modifier_animation.values)); + e=prepare(0,1.f,5.f,0);assert(!shield_recharge_visible(e.modifier_shader,e.modifier_animation.values)); + e=prepare(0,.5f,6.f,0);e=prepare(0,1.f,1.f,0);assert(!shield_recharge_visible(e.modifier_shader,e.modifier_animation.values));return 0; + } + else if(!strcmp(argv[1],"capacity")) { + shield_recharge_reset();for(n=0;n<140;n++)e=prepare(n,.5f,3.f,0); + assert(!shield_recharge_visible(e.modifier_shader,e.modifier_animation.values));return 0; + } + else if(!strcmp(argv[1],"unrelated")) { + e.modifier_shader=&shield_looks[1].body.shader;i=.123f;o=.004f;draw(&e,&i,&o);assert(i==.123f && o==.004f);return 0; + } + else assert(!strcmp(argv[1],"full")); + if(!strcmp(argv[1],"reset")) {assert(!shield_recharge_visible(e.modifier_shader,e.modifier_animation.values));return 0;} + e=prepare(0,!strcmp(argv[1],"full")?1.5f:.5f,3.1f,0); + assert(!shield_recharge_visible(e.modifier_shader,e.modifier_animation.values)); + i=.123f;o=.004f;draw(&e,&i,&o);assert(i==.123f && o==.004f); + return 0; +} +''' + (work/'test.c').write_text(preamble+source+main) + output=work/('test.exe' if os.name=='nt' else 'test') + flags=['-m32','-std=gnu89','-Werror'] + if os.name=='nt': flags+=['--target=i686-pc-windows-msvc','-fuse-ld=lld','-D_CRT_SECURE_NO_WARNINGS'] + result=subprocess.run([cc,*flags,str(work/'test.c'),'-o',str(output)],capture_output=True,text=True) + assert result.returncode==0,result.stdout+result.stderr + return output + +@pytest.mark.parametrize('case',['damage','ai','dead','depleted','overcharging','not-charging','classic','reset','arms','respawn','time','capacity','unrelated','full','sprinkles']) +def test_recharge(recharge_tool,case): + result=subprocess.run([str(recharge_tool),case],capture_output=True,text=True) + assert result.returncode==0,result.stdout+result.stderr diff --git a/tools/test_steam_workshop.py b/tools/test_steam_workshop.py new file mode 100644 index 0000000000..2824d359da --- /dev/null +++ b/tools/test_steam_workshop.py @@ -0,0 +1,793 @@ +"""The Steam Workshop catalog (port/linux/src/steam_workshop.c): the item and map json, the library list, and a scan +of a made-up Steam folder through the real directory code.""" +import json +import os +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest +from harness import function + +ROOT = Path(__file__).resolve().parents[1] +SRC = ROOT / "port/linux/src" + +DRIVER = r''' +#include "steam_workshop.h" +#include "mcc_manifest.h" +#include +#include +#include +#include +static int test_enabled = -1; +int config_boolean(const char *name) { + if(!strcmp(name,"game.mcc_campaigns")) return getenv("TEST_MCC_CAMPAIGNS") != NULL; + if(test_enabled >= 0) return test_enabled; + const char *value=getenv("TEST_WORKSHOP_ENABLED");(void)name; + return !value || strcmp(value,"0"); +} +const char *config_string(const char *name) +{ + const char *value = !strcmp(name, "paths.steam") ? getenv("TEST_STEAM_SETTING") : NULL; + return value ? value : ""; +} +static char *slurp(const char *path, int *length) +{ + FILE *file = fopen(path, "rb"); + char *text = malloc(1 << 20); + + if (!file) return NULL; + *length = (int)fread(text, 1, (1 << 20) - 1, file); + text[*length] = 0; + fclose(file); + return text; +} +int main(int argc, char **argv) +{ + int length, index; + char *text; + + if (argc == 3 && !strcmp(argv[1], "item")) + { + static struct steam_workshop_item_text item; + + text = slurp(argv[2], &length); + printf("ok=%d\n", steam_workshop_read_item(text, length, &item)); + printf("title=%s\nhalo1=%d\nmaps=%d\n", item.title, item.halo1, item.map_count); + for (index = 0; index < item.map_count; index++) + printf("json=%s\n", item.map_json[index]); + } + else if (argc == 3 && !strcmp(argv[1], "map")) + { + struct steam_workshop_map_text map; + + text = slurp(argv[2], &length); + printf("ok=%d\nname=%s\ntitle=%s\nthumbnail=%s\n", steam_workshop_read_map(text, length, &map), map.name, + map.title, map.thumbnail); + } + else if (argc == 3 && !strcmp(argv[1], "vdf")) + { + static char paths[8][STEAM_WORKSHOP_PATH_SIZE]; + int count; + + text = slurp(argv[2], &length); + count = steam_workshop_read_libraries(text, length, paths, 8); + printf("count=%d\n", count); + for (index = 0; index < count; index++) + printf("path=%s\n", paths[index]); + } + else if (argc == 2 && !strcmp(argv[1], "scan")) + { + char folder[512] = {0}, title[64] = {0}; + + printf("count=%d\n", steam_workshop_scan()); + for (index = 0; index < steam_workshop_count(); index++) + { + const struct steam_workshop_map *map = steam_workshop_map(index); + + printf("map=%s|%s|%s|%s|%s|%s\n", map->item_id, map->item_title, map->name, map->title, map->path, + map->preview); + } + printf("again=%d\n", steam_workshop_count()); + printf("folder=%d %s\n", steam_workshop_package_folder("111", folder, sizeof(folder)), folder); + printf("none=%d\n", steam_workshop_package_folder("999", folder, sizeof(folder))); + printf("title=%d %s\n", steam_workshop_item_title("222", title, sizeof(title)), title); + printf("small=%d\n", steam_workshop_package_folder("111", folder, 8)); + } + else if (argc == 2 && !strcmp(argv[1], "toggle")) + { + printf("initial=%d\n", steam_workshop_count()); + test_enabled = 0; + printf("disabled=%d\n", steam_workshop_count()); + printf("stale=%d\n", steam_workshop_map(0) != NULL); + test_enabled = 1; + printf("enabled=%d\n", steam_workshop_count()); + printf("rescan=%d\n", steam_workshop_scan()); + } + else if (argc == 3 && !strcmp(argv[1], "linux-roots")) + { + char paths[11][STEAM_WORKSHOP_PATH_SIZE]; + int maximum = atoi(argv[2]), count, guard = 1; + unsigned byte; + if (maximum < 0 || maximum > 10) return 2; + memset(paths, 'Z', sizeof(paths)); + count = linux_roots(paths, maximum); + printf("count=%d\n", count); + for (index = 0; index < count; index++) printf("root=%s\n", paths[index]); + for (byte = maximum * STEAM_WORKSHOP_PATH_SIZE; byte < sizeof(paths); byte++) + if (((char *)paths)[byte] != 'Z') guard = 0; + printf("guard=%d\n", guard); + } + else if (argc == 4 && !strcmp(argv[1], "resource")) + { + char path[1025]; + unsigned size = (unsigned)atoi(argv[3]), index; + int result, guard = 1; + if (size > 1024) return 2; + memset(path, 'Z', sizeof(path)); + result = steam_workshop_resource_path(argv[2], getenv("TEST_DATA_ROOT"), path, size); + for (index = size; index < sizeof(path); index++) if (path[index] != 'Z') guard = 0; + printf("result=%d\nguard=%d\n", result, guard); + } + else if (argc == 3 && !strcmp(argv[1], "translate")) + { + char path[1024]; + platform_translate_path(argv[2], path, sizeof(path)); + printf("path=%s\n", path); + } + else if (argc == 3 && (!strcmp(argv[1], "manifest") || !strcmp(argv[1], "manifest-level"))) + { + static struct mcc_manifest campaign; + char reason[128]; + int result = !strcmp(argv[1], "manifest") ? mcc_manifest_load(argv[2], &campaign, reason) : + mcc_manifest_for_level(argv[2], &campaign, reason); + printf("result=%d\nreason=%s\ncount=%d\ntitle=%s\n", result, reason, campaign.count, campaign.title); + for(index=0;index +#include +#include +#include +static LSTATUS WINAPI test_registry(HKEY key, LPCSTR subkey, LPCSTR value, DWORD flags, + LPDWORD type, PVOID data, LPDWORD size) +{ + const char *path; + DWORD needed; + assert(!getenv("TEST_REGISTRY_MUST_NOT_READ")); + assert(!strcmp(subkey, "Software\\Valve\\Steam")); + assert(type == NULL && (flags & RRF_RT_REG_SZ)); + if (key == HKEY_CURRENT_USER) { + assert(!strcmp(value, "SteamPath") && flags == RRF_RT_REG_SZ); + path = getenv("TEST_STEAM_REG_USER"); + } else { + assert(key == HKEY_LOCAL_MACHINE && !strcmp(value, "InstallPath")); + assert(flags == (RRF_RT_REG_SZ | RRF_SUBKEY_WOW6432KEY) || + flags == (RRF_RT_REG_SZ | RRF_SUBKEY_WOW6464KEY)); + path = getenv(flags & RRF_SUBKEY_WOW6432KEY ? "TEST_STEAM_REG_32" : "TEST_STEAM_REG_64"); + } + if (!path) return ERROR_FILE_NOT_FOUND; + if (!strcmp(path, "!denied")) return ERROR_ACCESS_DENIED; + if (!strcmp(path, "!type")) return ERROR_UNSUPPORTED_TYPE; + needed = (DWORD)strlen(path) + 1; + if (needed > *size) return ERROR_MORE_DATA; + memcpy(data, path, needed); + *size = needed; + return ERROR_SUCCESS; +} +#define RegGetValueA test_registry +''' + + +def build_tool(work, *, mock_registry=True): + compiler = os.environ.get("CC") or shutil.which("clang") or shutil.which("gcc") + if not compiler: + pytest.skip("a C compiler is needed") + native = (SRC / "xbox_files.c").read_text() + translation = r''' +#include "posix.h" +typedef int BOOL; +#define TRUE 1 +#define FALSE 0 +static char const *platform_data_root(void) {return getenv("TEST_DATA_ROOT");} +static char const *platform_save_root(void) {return platform_data_root();} +static char const *platform_custom_edition_root(void) {return "";} +static void make_directories(char const *path) {(void)path;} +''' + for name in ("trim_separators", "names_match", "translate_workshop", "translate_elsewhere", "platform_translate_path"): + translation += function(native, name) + "\n" + # Exercise the actual Linux candidate builder on every host. Linux scans + # below additionally use the full implementation with real symlinks/files. + discovery = (SRC / "steam_workshop.c").read_text() + for name in ("linux_root", "linux_roots"): + translation += function(discovery, name) + "\n" + (work / "driver.c").write_text(DRIVER.replace("int main(", translation + "\nint main(")) + exe = work / ("driver.exe" if sys.platform == "win32" else "driver") + windows = sys.platform == "win32" + flags = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld", "-D_CRT_SECURE_NO_WARNINGS"] if windows else [] + registry = ROOT / "port/windows/src/win32_steam_workshop.c" + if windows and mock_registry: + # Mock only the registry API: production discovery and filesystem code + # still run, without scanning the developer's installed Steam packages. + wrapper = work / "registry.c" + wrapper.write_text(WINDOWS_REGISTRY + '\n#include "%s"\n' % registry.as_posix()) + registry = wrapper + files = ROOT / "port/windows/src/win32_files.c" if windows else SRC / "posix_files.c" + result = subprocess.run([compiler, *flags, "-std=gnu11", "-Wall", "-Wextra", "-Werror", "-I", str(SRC), str(work / "driver.c"), + str(SRC / "steam_workshop.c"), str(files), str(SRC / "server_json.c"), + str(SRC / "mcc_manifest.c"), + *([str(registry)] if windows else []), + *(["-ladvapi32"] if windows and not mock_registry else []), + "-o", str(exe)], capture_output=True, text=True) + assert result.returncode == 0, result.stderr + return exe + + +@pytest.fixture(scope="module") +def tool(tmp_path_factory): + return build_tool(tmp_path_factory.mktemp("steam-workshop")) + + +def run(tool, *args, home=None, setting="", enabled=True, data_root=None, hints=None): + env = dict(os.environ, HOME=str(home or "/nonexistent"), TEST_STEAM_SETTING=setting, + TEST_WORKSHOP_ENABLED=str(int(enabled)), TEST_DATA_ROOT=str(data_root or "/nonexistent"), + XDG_DATA_HOME="", STEAM_COMPAT_CLIENT_INSTALL_PATH="") + env.update(hints or {}) + result = subprocess.run([str(tool), *map(str, args)], capture_output=True, text=True, timeout=20, env=env) + assert result.returncode == 0, result.stderr + fields, lists = {}, {} + for line in result.stdout.splitlines(): + key, value = line.split("=", 1) + lists.setdefault(key, []).append(value) + fields[key] = value + return fields, lists + + +def item_json(**changes): + document = {"Engine": "Halo1", "Title": {"Neutral": "Pro Edition"}, + "GameModContents": {"MultiplayerMaps": ["maps\\beaver.json", "maps\\derelict.json"]}} + document.update(changes) + return json.dumps(document) + + +def test_item_text(tool, tmp_path): + path = tmp_path / "ModInfo.json" + path.write_text(item_json()) + fields, lists = run(tool, "item", path) + assert fields["ok"] == "1" and fields["title"] == "Pro Edition" and fields["halo1"] == "1" + assert lists["json"] == ["maps/beaver.json", "maps/derelict.json"] + # another engine reads, flagged: the scan skips it + path.write_text(item_json(Engine="Halo2")) + assert run(tool, "item", path)[0]["halo1"] == "0" + # no maps (a campaign-only item) is fine and empty + path.write_text(json.dumps({"Engine": "Halo1", "Title": {"Neutral": "Campaign"}})) + fields, _ = run(tool, "item", path) + assert fields["ok"] == "1" and fields["maps"] == "0" + + +@pytest.mark.parametrize("bad", ["..\\\\x.json", "../x.json", "/etc/passwd", "C:\\\\x.json", "a\\u0001.json", ""]) +def test_item_refuses_paths_that_leave_the_item(tool, tmp_path, bad): + path = tmp_path / "ModInfo.json" + path.write_text(item_json(GameModContents={"MultiplayerMaps": [json.loads('"' + bad + '"')]})) + assert run(tool, "item", path)[0]["ok"] == "0" + + +@pytest.mark.parametrize("text", ["", "[]", "not json", '{"Engine":', "{" * 40 + "}" * 40, '"text"']) +def test_item_refuses_what_is_not_an_object(tool, tmp_path, text): + path = tmp_path / "ModInfo.json" + path.write_text(text) + assert run(tool, "item", path)[0]["ok"] == "0" + + +def test_item_too_large_or_too_many_maps(tool, tmp_path): + path = tmp_path / "ModInfo.json" + path.write_text(item_json(Padding="x" * (300 * 1024))) + assert run(tool, "item", path)[0]["ok"] == "0" + path.write_text(item_json(GameModContents={"MultiplayerMaps": ["maps\\m%d.json" % n for n in range(1025)]})) + assert run(tool, "item", path)[0]["ok"] == "0" + result = subprocess.run([str(tool), "item", str(path)], capture_output=True, text=True, check=True) + assert "Pro Edition" in result.stderr and "1025 entries" in result.stderr and "limit is 1024" in result.stderr + + +@pytest.mark.parametrize("count", [64, 65, 75, 1024]) +def test_item_accepts_collections_up_to_catalog_capacity(tool, tmp_path, count): + path = tmp_path / "ModInfo.json" + names = [f"multiplayer/{n}.json" for n in range(count)] + path.write_text(item_json(GameModContents={"MultiplayerMaps": names})) + fields, lists = run(tool, "item", path) + assert fields["ok"] == "1" and int(fields["maps"]) == count + assert lists["json"] == names + + +@pytest.mark.parametrize("bad", ["../outside.json", "C:/outside.json", "x" * 128, 7]) +def test_large_item_validates_every_path(tool, tmp_path, bad): + path = tmp_path / "ModInfo.json" + names = [f"maps/{n}.json" for n in range(74)] + [bad] + path.write_text(item_json(GameModContents={"MultiplayerMaps": names})) + fields, _ = run(tool, "item", path) + assert fields["ok"] == "0" and fields["maps"] == "0" + + +@pytest.mark.parametrize("item_id,prefix", [("111", "alpha"), ("987654321", "unrelated")]) +def test_scan_large_collection(tool, tmp_path, item_id, prefix): + maps = [(f"{prefix}{n}", f"Authored title {n}") for n in range(75)] + make_item(tmp_path, item_id, maps=maps) + fields, lists = run(tool, "scan", setting=str(tmp_path)) + assert fields["count"] == fields["again"] == "75" + assert [(parts[2], parts[3]) for parts in (row.split("|") for row in lists["map"])] == maps + assert run(tool, "scan", setting=str(tmp_path), enabled=False)[0]["count"] == "0" + assert run(tool, "toggle", setting=str(tmp_path))[0] == { + "initial": "75", "disabled": "0", "stale": "0", "enabled": "75", "rescan": "75"} + + +def test_scan_keeps_global_catalog_bound(tool, tmp_path): + make_item(tmp_path, "111", maps=[(f"first{n}", f"First {n}") for n in range(600)], preview=False) + make_item(tmp_path, "222", maps=[(f"second{n}", f"Second {n}") for n in range(600)], preview=False) + fields, lists = run(tool, "scan", setting=str(tmp_path)) + assert fields["count"] == "1024" + assert len(lists["map"]) == 1024 + assert len({tuple(row.split("|")[i] for i in (0, 2)) for row in lists["map"]}) == 1024 + + +def test_map_text(tool, tmp_path): + path = tmp_path / "map.json" + path.write_text(json.dumps({"ScenarioFile": "maps\\pat_beavercreek.map", "Title": {"Neutral": "Better Creek"}, + "Images": {"Thumbnail": "images\\creek.png"}})) + fields, _ = run(tool, "map", path) + assert (fields["ok"], fields["name"], fields["title"], fields["thumbnail"]) == ( + "1", "pat_beavercreek", "Better Creek", "images/creek.png") + # the preview must stay inside the item + path.write_text(json.dumps({"ScenarioFile": "x", "Images": {"Thumbnail": "..\\..\\secret.png"}})) + fields, _ = run(tool, "map", path) + assert fields["ok"] == "1" and fields["thumbnail"] == "" and fields["title"] == "" + for scenario in ("", "..", "a:b", "tab\tname", "n" * 80): + path.write_text(json.dumps({"ScenarioFile": scenario})) + assert run(tool, "map", path)[0]["ok"] == "0", scenario + path.write_text(json.dumps({"Title": {"Neutral": "no scenario"}})) + assert run(tool, "map", path)[0]["ok"] == "0" + + +def test_library_list(tool, tmp_path): + path = tmp_path / "libraryfolders.vdf" + path.write_text('"libraryfolders"\n{\n\t"0"\n\t{\n\t\t"path"\t\t"/opt/user/.local/share/Steam"\n' + '\t\t"label"\t\t""\n\t}\n\t"1"\n\t{\n\t\t"path"\t\t"D:\\\\SteamLibrary"\n\t}\n' + '\t"2"\n\t{\n\t\t"path"\t\t"/with \\"quote\\""\n\t\t"path"\t\t"\n\t\t"path"\t\t""\n\t}\n}\n') + fields, lists = run(tool, "vdf", path) + assert lists["path"] == ["/opt/user/.local/share/Steam", "D:\\SteamLibrary", '/with "quote"'] + + +def make_map(folder, name): + folder.mkdir(parents=True, exist_ok=True) + (folder / (name + ".map")).write_bytes(b"head" + bytes(100)) + + +def make_item(library, item_id, title="Item", engine="Halo1", maps=(("beaver", "Better Creek"),), manifest="ModInfo.json", + preview=True): + folder = library / "steamapps/workshop/content/976730" / item_id + folder.mkdir(parents=True) + names = [] + for name, map_title in maps: + # (the folder's spelling differs from the manifest's: names are found case-blind) + (folder / "Maps").mkdir(exist_ok=True) + (folder / "Maps" / (name + ".json")).write_text(json.dumps({ + "ScenarioFile": "maps\\" + name, "Title": {"Neutral": map_title}, + "Images": {"Thumbnail": "Images\\" + name + ".PNG"}})) + make_map(folder / "Maps", name.upper() if name == "shouting" else name) + if preview: + (folder / "images").mkdir(exist_ok=True) + (folder / "images" / (name + ".png")).write_bytes(b"png") + names.append("maps\\" + name + ".json") + (folder / manifest).write_text(item_json(Engine=engine, Title={"Neutral": title}, + GameModContents={"MultiplayerMaps": names})) + return folder + + +def test_scan(tool, tmp_path): + home = tmp_path / "home" + steam = home / ".local/share/Steam" + other = tmp_path / "library two" + # both usual links lead to the one Steam folder: each item once + (home / ".steam").mkdir(parents=True) + if sys.platform != "win32": + (home / ".steam/steam").symlink_to(steam) + (home / ".steam/root").symlink_to(steam) + (steam / "steamapps").mkdir(parents=True) + (steam / "steamapps/libraryfolders.vdf").write_text( + '"libraryfolders"\n{\n"0"\n{\n"path"\t"%s"\n}\n"1"\n{\n"path"\t"%s"\n}\n}\n' % (steam.as_posix(), other.as_posix())) + make_item(steam, "111", "Pro Edition", maps=(("beaver", "Better Creek"), ("shouting", "Loud"))) + folder = make_item(other, "222", "Social Pack", manifest="modinfo.JSON") + make_item(other, "333", engine="Halo2") + make_item(other, "444", maps=()) # a campaign-only item + make_item(other, "555") # this one is also in the first library: + make_item(steam, "555", "Seen First") # the first wins + make_item(other, "notanid") + make_item(other, "666", maps=(("gone", "No File"),)) + for leftover in (other / "steamapps/workshop/content/976730/666/Maps").glob("gone.map"): + leftover.unlink() + # a manifest naming a json outside the item refuses the item + outside = make_item(other, "777") + (outside / "ModInfo.json").write_text(item_json(GameModContents={"MultiplayerMaps": ["..\\\\111\\\\maps\\\\beaver.json"]})) + fields, lists = run(tool, "scan", home=home, setting=str(steam) if sys.platform == "win32" else "") + rows = [row.split("|") for row in lists["map"]] + assert sorted((r[0], r[2]) for r in rows) == [("111", "SHOUTING"), ("111", "beaver"), ("222", "beaver"), + ("555", "beaver")] + assert fields["count"] == "4" and fields["again"] == "4" + by_id = {(r[0], r[2]): r for r in rows} + # the file as it is spelled on disk (SHOUTING.map for a json that says shouting), real paths, a found preview + # (found through the first link to Steam's folder) + assert by_id[("111", "SHOUTING")][4].endswith("/steamapps/workshop/content/976730/111/Maps/SHOUTING.map") + assert by_id[("111", "beaver")][5].endswith("/steamapps/workshop/content/976730/111/images/beaver.png") + assert by_id[("555", "beaver")][1] == "Seen First" + assert fields["folder"].startswith("1 ") and fields["folder"].endswith("/976730/111/Maps") + assert fields["none"] == "0" and fields["small"] == "0" + assert fields["title"] == "1 Social Pack" + assert folder.exists() + + +def test_setting_names_a_steam_folder(tool, tmp_path): + steam = tmp_path / "Elsewhere" + make_item(steam, "888", "From the setting", preview=False) + fields, lists = run(tool, "scan", setting=str(steam)) + assert fields["count"] == "1" + row = lists["map"][0].split("|") + assert row[:4] == ["888", "From the setting", "beaver", "Better Creek"] and row[5] == "" + # no Steam at all: an empty catalog, no error + assert run(tool, "scan", home=tmp_path / "nothing")[0]["count"] == "0" + + +@pytest.mark.parametrize("maximum", [0, 1, 2, 7, 8, 10]) +def test_linux_root_candidates_are_bounded_and_ordered(tool, maximum): + fields, rows = run(tool, "linux-roots", maximum, home="/home/player", hints={ + "XDG_DATA_HOME": "/custom user data", "STEAM_COMPAT_CLIENT_INSTALL_PATH": "/games/Steam"}) + expected = ["/games/Steam", "/custom user data/Steam", "/home/player/.steam/steam", + "/home/player/.steam/root", "/home/player/.local/share/Steam", + "/home/player/.steam/debian-installation", + "/home/player/.var/app/com.valvesoftware.Steam/.local/share/Steam", + "/home/player/snap/steam/common/.local/share/Steam"] + assert rows.get("root", []) == expected[:maximum] + assert fields["count"] == str(min(maximum, len(expected))) and fields["guard"] == "1" + + +@pytest.mark.parametrize("bad", ["", "relative/path", "~/Steam", "$HOME/Steam", "/bad\npath", "/" + "x" * 511]) +def test_linux_invalid_hints_keep_home_fallbacks(tool, bad): + _, rows = run(tool, "linux-roots", 10, home="/home/player", hints={ + "XDG_DATA_HOME": bad, "STEAM_COMPAT_CLIENT_INSTALL_PATH": bad}) + assert len(rows["root"]) == 6 + assert all(path.startswith("/home/player/") for path in rows["root"]) + + +def test_linux_hints_work_without_home_and_do_not_truncate(tool): + _, rows = run(tool, "linux-roots", 10, hints={"HOME": "", "XDG_DATA_HOME": "/data", + "STEAM_COMPAT_CLIENT_INSTALL_PATH": "/" + "x" * 510}) + assert rows["root"] == ["/" + "x" * 510, "/data/Steam"] + # XDG suffix must also fit; an invalid HOME must not become a relative scan. + fields, rows = run(tool, "linux-roots", 10, hints={"HOME": "relative", + "XDG_DATA_HOME": "/" + "x" * 505}) + assert fields["count"] == "0" and "root" not in rows + + +@pytest.mark.skipif(sys.platform != "linux", reason="Native Linux filesystem discovery") +@pytest.mark.parametrize("source", ["xdg", "client", "debian", "flatpak", "snap", "relocated-link"]) +def test_linux_nonstandard_installations_and_libraries(tool, tmp_path, source): + home, steam, library = tmp_path / "home", tmp_path / "relocated Steam", tmp_path / "other library" + hints = {} + if source == "xdg": + steam = tmp_path / "custom data/Steam" + hints["XDG_DATA_HOME"] = str(steam.parent) + elif source == "client": + hints["STEAM_COMPAT_CLIENT_INSTALL_PATH"] = str(steam) + elif source == "relocated-link": + (home / ".steam").mkdir(parents=True) + (home / ".steam/root").symlink_to(steam) + (home / ".steam/steam").symlink_to(steam) + else: + steam = home / {"debian": ".steam/debian-installation", + "flatpak": ".var/app/com.valvesoftware.Steam/.local/share/Steam", + "snap": "snap/steam/common/.local/share/Steam"}[source] + make_item(steam, "111", "Automatic") + make_item(library, "222", "Secondary library") + (steam / "steamapps/libraryfolders.vdf").write_text( + '"libraryfolders" { "0" { "path" "%s" } "1" { "path" "%s" } }' + % (steam.as_posix(), library.as_posix())) + fields, rows = run(tool, "scan", home=home, hints=hints) + assert fields["count"] == "2" + assert [row.split("|")[1] for row in rows["map"]] == ["Automatic", "Secondary library"] + assert run(tool, "scan", home=home, hints=hints, enabled=False)[0]["count"] == "0" + manual = tmp_path / "manual" + make_item(manual, "111", "Manual wins") + _, rows = run(tool, "scan", home=home, hints=hints, setting=str(manual)) + assert [row.split("|")[1] for row in rows["map"]] == ["Manual wins", "Secondary library"] + + +@pytest.mark.skipif(sys.platform != "linux", reason="Native Linux filesystem discovery") +def test_linux_all_candidates_fit_with_manual_override(tool, tmp_path): + home, manual, client, xdg = (tmp_path / name for name in ("home", "manual", "client", "data")) + roots = [manual, client, xdg / "Steam", home / ".steam/steam", home / ".steam/root", + home / ".local/share/Steam", home / ".steam/debian-installation", + home / ".var/app/com.valvesoftware.Steam/.local/share/Steam", + home / "snap/steam/common/.local/share/Steam"] + for index, root in enumerate(roots): + make_item(root, str(100 + index), str(index)) + fields, rows = run(tool, "scan", home=home, setting=str(manual), hints={ + "XDG_DATA_HOME": str(xdg), "STEAM_COMPAT_CLIENT_INSTALL_PATH": str(client)}) + assert fields["count"] == "9" + assert [row.split("|")[1] for row in rows["map"]] == list(map(str, range(9))) + + +@pytest.mark.skipif(sys.platform != "linux", reason="Native Linux filesystem discovery") +def test_linux_stale_hints_and_broken_symlinks_keep_fallbacks(tool, tmp_path): + home = tmp_path / "home" + (home / ".steam").mkdir(parents=True) + (home / ".steam/root").symlink_to(tmp_path / "missing") + (home / ".steam/steam").symlink_to(home / ".steam/steam") + make_item(home / ".local/share/Steam", "111", "Fallback") + not_a_directory = tmp_path / "not a directory" + not_a_directory.write_text("not Steam") + fields, rows = run(tool, "scan", home=home, hints={ + "XDG_DATA_HOME": str(not_a_directory), "STEAM_COMPAT_CLIENT_INSTALL_PATH": str(tmp_path / "missing")}) + assert fields["count"] == "1" and rows["map"][0].split("|")[1] == "Fallback" + + +@pytest.mark.skipif(sys.platform != "win32", reason="Windows registry discovery") +@pytest.mark.parametrize("key", ["USER", "32", "64"]) +def test_windows_registry_installation_and_library(tool, tmp_path, monkeypatch, key): + steam, library = tmp_path / "Custom Steam", tmp_path / "Other Drive Library" + make_item(steam, "111", "Registered installation") + make_item(library, "222", "Registered library") + (steam / "steamapps/libraryfolders.vdf").write_text( + '"libraryfolders" { "0" { "path" "%s" } }' % library.as_posix()) + monkeypatch.setenv("TEST_STEAM_REG_" + key, str(steam)) + fields, rows = run(tool, "scan") + assert fields["count"] == "2" + assert [row.split("|")[1] for row in rows["map"]] == ["Registered installation", "Registered library"] + # A disabled feature must not even query the registry. + monkeypatch.setenv("TEST_REGISTRY_MUST_NOT_READ", "1") + assert run(tool, "scan", enabled=False)[0]["count"] == "0" + + +@pytest.mark.skipif(sys.platform != "win32", reason="Windows registry discovery") +def test_windows_manual_root_precedes_registry_and_registry_precedes_defaults(tool, tmp_path, monkeypatch): + manual, registered, defaults = (tmp_path / name for name in ("manual", "registered", "defaults")) + make_item(manual, "111", "Manual wins") + make_item(registered, "111", "Registry wins") + make_item(defaults / "Steam", "111", "Default loses") + for key in ("USER", "32", "64"): + monkeypatch.setenv("TEST_STEAM_REG_" + key, str(registered)) + monkeypatch.setenv("ProgramFiles(x86)", str(defaults)) + for setting, title in ((str(manual), "Manual wins"), ("", "Registry wins")): + fields, rows = run(tool, "scan", setting=setting) + assert fields["count"] == "1" + assert rows["map"][0].split("|")[1] == title + + +@pytest.mark.skipif(sys.platform != "win32", reason="Windows registry discovery") +@pytest.mark.parametrize("bad", ["", "!denied", "!type", "x" * 512, "Z:/missing-steam-installation"]) +def test_windows_bad_registry_value_keeps_fallbacks(tool, tmp_path, monkeypatch, bad): + make_item(tmp_path / "Steam", "111", "Fallback") + monkeypatch.setenv("ProgramFiles(x86)", str(tmp_path)) + for key in ("USER", "32", "64"): + monkeypatch.setenv("TEST_STEAM_REG_" + key, bad) + fields, rows = run(tool, "scan") + assert fields["count"] == "1" + assert rows["map"][0].split("|")[1] == "Fallback" + + +def test_scan_keeps_short_map_names(tool, tmp_path): + make_item(tmp_path, "111", maps=(("a10", "One"), ("test", "Two"), ("longer", "Three"))) + _, rows = run(tool, "scan", setting=str(tmp_path)) + assert {row.split("|")[2] for row in rows["map"]} == {"a10", "test", "longer"} + assert run(tool, "scan", setting=str(tmp_path), enabled=False)[0]["count"] == "0" + + +def test_translation_keeps_local_override_and_legacy_roots(tool, tmp_path): + library, data = tmp_path / "steam", tmp_path / "data" + make_item(library, "111") + data.mkdir() + fields, _ = run(tool, "translate", "d:\\mcc_maps\\111\\beaver.map", setting=str(library), data_root=data) + assert fields["path"].replace("\\", "/").endswith("/111/Maps/beaver.map") + override = data / "MCC_MAPS/111" + override.mkdir(parents=True) + (override / "beaver.map").write_bytes(b"manual") + for prefix in ("d:\\", ""): + fields, _ = run(tool, "translate", prefix + "mcc_maps\\111\\beaver.map", setting=str(library), data_root=data) + assert Path(fields["path"]) == override / "beaver.map" + for folder in ("maps", "custom_maps"): + fields, _ = run(tool, "translate", "d:\\" + folder + "\\a10.map", setting=str(library), data_root=data) + assert Path(fields["path"]) == data / folder / "a10.map" + + +def make_campaign(folder, names=("z10", "a10")): + folder.mkdir(parents=True, exist_ok=True) + (folder / "campaign").mkdir(exist_ok=True) + (folder / "ModInfo.json").write_text(item_json(GameModContents={"HasCampaign": True})) + (folder / "CampaignInfo.json").write_text(json.dumps({"Title": {"Neutral": "Example campaign"}, + "CampaignMaps": [f"campaign/{name}.json" for name in names]})) + for name in names: + (folder / f"campaign/{name}.json").write_text(json.dumps({"ScenarioFile": f"levels/example/{name}", + "Title": {"Neutral": "Mission " + name}, "CampaignMapKind": "Default"})) + make_map(folder / "maps", name) + + +def test_campaign_discovery_and_explicit_order(tool, tmp_path, monkeypatch): + folder = tmp_path / "steamapps/workshop/content/976730/111" + make_campaign(folder) + assert run(tool, "scan", setting=str(tmp_path))[0]["count"] == "0" + monkeypatch.setenv("TEST_MCC_CAMPAIGNS", "1") + fields, rows = run(tool, "scan", setting=str(tmp_path)) + assert fields["count"] == "2" + assert [row.split("|")[2] for row in rows["map"]] == ["z10", "a10"] + fields, rows = run(tool, "manifest", folder) + assert fields["result"] == "1" and fields["title"] == "Example campaign" + assert rows["mission"] == ["z10|Mission z10", "a10|Mission a10"] + # Missing binaries do not change the authored sequence. + (folder / "maps/a10.map").unlink() + assert run(tool, "manifest", folder)[0]["count"] == "2" + + +def test_local_campaign_override_never_borrows_steam_metadata(tool, tmp_path, monkeypatch): + library, data = tmp_path / "steam", tmp_path / "data" + make_campaign(library / "steamapps/workshop/content/976730/111") + data.mkdir() + monkeypatch.setenv("TEST_MCC_CAMPAIGNS", "1") + args = dict(setting=str(library), data_root=data) + assert run(tool, "manifest-level", "mcc_maps\\111\\z10", **args)[0]["count"] == "2" + local = data / "MCC_MAPS/111" + local.mkdir(parents=True) + assert run(tool, "manifest-level", "mcc_maps\\111\\z10", **args)[0]["result"] == "0" + make_campaign(local, ("c10", "b10")) + fields, rows = run(tool, "manifest-level", "mcc_maps\\111\\c10", **args) + assert fields["result"] == "1" and rows["mission"][0] == "c10|Mission c10" + + +@pytest.mark.parametrize("fault", ["missing", "traversal", "duplicate_path", "duplicate_name", "kind", "engine", "disabled", "oversize", "too_many"]) +def test_campaign_manifest_refuses_partial_or_ambiguous_metadata(tool, tmp_path, fault): + make_campaign(tmp_path) + campaign = tmp_path / "CampaignInfo.json" + mission = tmp_path / "campaign/a10.json" + if fault == "missing": mission.unlink() + elif fault == "traversal": campaign.write_text(json.dumps({"CampaignMaps": ["../a10.json"]})) + elif fault == "duplicate_path": campaign.write_text(json.dumps({"CampaignMaps": ["campaign/a10.json", "CAMPAIGN/A10.JSON"]})) + elif fault == "duplicate_name": mission.write_text(json.dumps({"ScenarioFile": "z10"})) + elif fault == "kind": mission.write_text(json.dumps({"ScenarioFile": "a10", "CampaignMapKind": "Hub"})) + elif fault in ("engine", "disabled"): + (tmp_path / "ModInfo.json").write_text(item_json(Engine="Halo2" if fault == "engine" else "Halo1", + GameModContents={"HasCampaign": fault != "disabled"})) + elif fault == "oversize": mission.write_text(" " * (256 * 1024 + 1)) + elif fault == "too_many": campaign.write_text(json.dumps({"CampaignMaps": [f"campaign/{i}.json" for i in range(65)]})) + fields, _ = run(tool, "manifest", tmp_path) + assert fields["result"] == "-1" and fields["count"] == "0" and fields["reason"] + +@pytest.mark.parametrize("item_id", ["111", "982734"]) +@pytest.mark.parametrize("resource", ["bitmaps.map", "sounds.map"]) +def test_workshop_authored_resources_are_found_in_item_halo1_folder(tool, tmp_path, item_id, resource): + library, data = tmp_path / "steam", tmp_path / "data" + package = make_item(library, item_id) + data.mkdir() + authored = package / "HaLo1/MaPs" + authored.mkdir(parents=True) + target = authored / resource.upper() + target.write_bytes(b"authored resource") + fields, _ = run(tool, "translate", f"mcc_maps/{item_id}/{resource}", setting=str(library), data_root=data) + assert Path(fields["path"]) == target + fields, _ = run(tool, "translate", f"d:\\MCC_MAPS\\{item_id}\\{resource.upper()}", setting=str(library), data_root=data) + assert Path(fields["path"]) == target + # A local package never borrows the Workshop item's authored resources. + override = data / "MCC_MAPS" / item_id + override.mkdir(parents=True) + fields, _ = run(tool, "translate", f"mcc_maps/{item_id}/{resource}", setting=str(library), data_root=data) + assert Path(fields["path"]) == override / resource + override.rmdir() + # Beside-level overrides stay authoritative, including invalid files. + beside = package / "Maps" / resource + beside.write_bytes(b"invalid override") + fields, _ = run(tool, "translate", f"mcc_maps/{item_id}/{resource}", setting=str(library), data_root=data) + assert Path(fields["path"]) == beside + + +@pytest.mark.parametrize("group,subfolder,resource", [ + ("singleplayer", "", "bitmaps.map"), + ("multiplayer", "custom_edition", "bitmaps.map"), + ("multiplayer", "custom_edition", "sounds.map"), +]) +def test_workshop_shared_resources_use_mcc_installation(tool, tmp_path, group, subfolder, resource): + library, data = tmp_path / "steam", tmp_path / "data" + library.mkdir() + data.mkdir() + installed = library / "steamapps/common/Halo The Master Chief Collection/halo1/maps" / subfolder + installed.mkdir(parents=True) + target = installed / resource + target.write_bytes(b"MCC shared resource") + request = f"mcc_maps/_shared/{group}/{resource}" + fields, _ = run(tool, "translate", request, setting=str(library), data_root=data) + assert Path(fields["path"]) == target + # Explicit installed shared files win; disabling discovery restores local paths. + local = data / request + local.parent.mkdir(parents=True) + local.write_bytes(b"invalid override") + fields, _ = run(tool, "translate", request, setting=str(library), data_root=data) + assert Path(fields["path"]) == local + local.unlink() + fields, _ = run(tool, "translate", request, setting=str(library), data_root=data, enabled=False) + assert Path(fields["path"]) == local + + +@pytest.mark.parametrize("resource_request", ["111/loc.map", "111/sub/bitmaps.map", "111/../bitmaps.map", + "_shared/other/bitmaps.map", "_shared/singleplayer/../sounds.map", "x" * 128 + "/bitmaps.map"]) +def test_resource_discovery_rejects_other_names_and_paths(tool, tmp_path, resource_request): + make_item(tmp_path, "111") + fields, _ = run(tool, "resource", resource_request, "1024", setting=str(tmp_path), data_root=tmp_path) + assert fields == {"result": "0", "guard": "1"} + + +@pytest.mark.parametrize("size", [0, 1, 8, 32]) +def test_resource_discovery_does_not_truncate_host_paths(tool, tmp_path, size): + package = make_item(tmp_path, "111") + resources = package / "halo1/maps" + resources.mkdir(parents=True) + (resources / "bitmaps.map").write_bytes(b"authored") + fields, _ = run(tool, "resource", "111/bitmaps.map", str(size), setting=str(tmp_path), data_root=tmp_path) + assert fields == {"result": "0", "guard": "1"} + + +def test_shared_discovery_checks_other_steam_libraries_and_types_independently(tool, tmp_path): + steam, library, data = (tmp_path / part for part in ("steam", "library", "data")) + (steam / "steamapps").mkdir(parents=True) + data.mkdir() + (steam / "steamapps/libraryfolders.vdf").write_text( + '"libraryfolders" { "0" { "path" "%s" } }' % library.as_posix()) + shared = library / "steamapps/common/Halo The Master Chief Collection/halo1/maps/custom_edition" + shared.mkdir(parents=True) + (shared / "sounds.map").write_bytes(b"shared sounds") + package = make_item(steam, "111") + authored = package / "halo1/maps" + authored.mkdir(parents=True) + (authored / "bitmaps.map").write_bytes(b"authored bitmaps") + args = dict(setting=str(steam), data_root=data) + assert Path(run(tool, "translate", "mcc_maps/111/bitmaps.map", **args)[0]["path"]) == authored / "bitmaps.map" + assert Path(run(tool, "translate", "mcc_maps/_shared/multiplayer/sounds.map", **args)[0]["path"]) == shared / "sounds.map" + # Missing package resources are not borrowed from an unrelated Workshop item. + make_item(steam, "222") + assert Path(run(tool, "translate", "mcc_maps/222/bitmaps.map", **args)[0]["path"]) == package.parent / "222/Maps/bitmaps.map" + for folder in ("maps", "custom_maps"): + assert Path(run(tool, "translate", folder + "/sounds.map", **args)[0]["path"]) == data / folder / "sounds.map" + + +@pytest.mark.parametrize("kind", ["Default", "default", "DEFAULT", "dEfAuLt"]) +def test_campaign_kind_case_does_not_hide_other_missions(tool, tmp_path, monkeypatch, kind): + root = tmp_path / "steamapps/workshop/content/976730/111" + make_campaign(root) + path = root / "campaign/a10.json" + data = json.loads(path.read_text()); data["CampaignMapKind"] = kind + path.write_text(json.dumps(data)); original = path.read_bytes() + monkeypatch.setenv("TEST_MCC_CAMPAIGNS", "1") + fields, rows = run(tool, "manifest", root) + assert fields["result"] == "1" and fields["count"] == "2" + assert [row.split("|")[0] for row in rows["mission"]] == ["z10", "a10"] + fields, rows = run(tool, "scan", setting=str(tmp_path)) + assert fields["count"] == "2" + assert [row.split("|")[2] for row in rows["map"]] == ["z10", "a10"] + assert path.read_bytes() == original + monkeypatch.delenv("TEST_MCC_CAMPAIGNS") + assert run(tool, "scan", setting=str(tmp_path))[0]["count"] == "0" + + +@pytest.mark.parametrize("kind", ["Hub", "hub", "Flashback", "", " Default", "Default ", "Default/", 0, True, None, [], {}]) +def test_campaign_kind_refusal_is_reported(tool, tmp_path, kind): + root = tmp_path / "steamapps/workshop/content/976730/111" + make_campaign(root) + path = root / "campaign/a10.json" + data = json.loads(path.read_text()); data["CampaignMapKind"] = kind + path.write_text(json.dumps(data)) + fields, _ = run(tool, "manifest", root) + assert fields["result"] == "-1" and fields["count"] == "0" + env = dict(os.environ, TEST_STEAM_SETTING=str(tmp_path), TEST_MCC_CAMPAIGNS="1", HOME=str(tmp_path / "none"), + XDG_DATA_HOME="", STEAM_COMPAT_CLIENT_INSTALL_PATH="") + result = subprocess.run([str(tool), "scan"], env=env, capture_output=True, text=True, timeout=20) + assert result.returncode == 0 and "count=0" in result.stdout + assert "111" in result.stderr and "Unsupported campaign mission kind" in result.stderr diff --git a/tools/test_texture_names.py b/tools/test_texture_names.py new file mode 100644 index 0000000000..d697355d86 --- /dev/null +++ b/tools/test_texture_names.py @@ -0,0 +1,65 @@ +"""Real batched name allocation: uniqueness, ownership, failure and GLES fallback.""" +import os +from pathlib import Path +import shutil +import subprocess +import pytest + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.mark.parametrize('gles', [False, True]) +def test_texture_name_ownership(tmp_path, gles): + compiler = shutil.which('clang') + if not compiler: + pytest.skip('clang required') + code = r''' +#include +#include +typedef unsigned int GLuint; +typedef int GLsizei; +static unsigned next_name, calls, deleted, fail; +static unsigned char owned[4096], removed[4096]; +static void glGenTextures(int count,GLuint *names) { + int i;calls++; + for(i=0;i +#include +#include +#define TRUE 1 +#define NONE -1 +#define BITMAP_GROUP_TAG 1 +#define _error_silent 0 +struct bitmap_data {short width,height,depth,type,format,mipmap_count;unsigned flags;long pixels_size;}; +struct tag_iterator {int done;}; +struct bitmap_group {struct {long count;void *address;} bitmaps;}; +static struct bitmap_data bitmaps[4]; +static struct bitmap_group group; +static int enabled,mcc,server,null_renderer,loads,uploads,fail; +static unsigned long charged; +static long config_integer(char const *key) {(void)key;return enabled;} +static int config_boolean(char const *key) {assert(!strcmp(key,"debug.null_renderer"));return null_renderer;} +static int config_server_mode_enabled(void) {return server;} +static int mcc_cache_tags_loaded(void) {return mcc;} +static void tag_iterator_new(struct tag_iterator *it,long tag) {(void)tag;it->done=0;} +static long tag_iterator_next(struct tag_iterator *it) {return it->done++ ? NONE : 1;} +static struct bitmap_group *bitmap_group_get(long tag) {(void)tag;return &group;} +static unsigned long texture_prepare_charge(struct bitmap_data const *bitmap); +static void *_texture_cache_bitmap_get_hardware_format(struct bitmap_data *b,int block,int load) { + assert(block && load && b->format!=17);loads++;charged+=texture_prepare_charge(b);return fail?NULL:b; +} +static int render_prepare_texture(void const *p) {assert(p);uploads++;return 1;} +static void error(int severity,char const *fmt,...) {(void)severity;(void)fmt;} +''' + code += re.sub(r'^#include[^\n]*\n', '', (ROOT/'port/linux/game/texture_prepare.c').read_text(), flags=re.M) + code += r''' +int main(void) { + int i; + for(i=0;i<4;i++) {bitmaps[i].width=bitmaps[i].height=256;bitmaps[i].depth=1; + bitmaps[i].flags=128;bitmaps[i].format=11;bitmaps[i].pixels_size=262144;} + group.bitmaps.address=bitmaps;group.bitmaps.count=4; + texture_prepare_map();assert(!loads); + enabled=1;mcc=1;texture_prepare_map();assert(!loads);mcc=0; + server=1;texture_prepare_map();assert(!loads);server=0; + null_renderer=1;texture_prepare_map();assert(!loads);null_renderer=0; +#ifndef HALO_GLES + assert(texture_prepare_charge(&bitmaps[0])==262144); + bitmaps[0].width=1;bitmaps[0].height=1024;bitmaps[0].pixels_size=1024; + assert(texture_prepare_charge(&bitmaps[0])==65536);bitmaps[0]=bitmaps[1]; + bitmaps[0].type=2;assert(texture_prepare_charge(&bitmaps[0])==1572864);bitmaps[0].type=0; + bitmaps[0].mipmap_count=1;assert(texture_prepare_charge(&bitmaps[0])==327680);bitmaps[0].mipmap_count=0; + bitmaps[0].width=4096;bitmaps[0].height=4096;bitmaps[0].depth=512; + assert(!texture_prepare_charge(&bitmaps[0]));bitmaps[0]=bitmaps[1]; + bitmaps[1].format=17;bitmaps[2].flags=0;bitmaps[3].width=-1; + texture_prepare_map();assert(loads==1 && uploads==1 && charged==262144); + for(i=1;i<4;i++)bitmaps[i]=bitmaps[0]; + bitmaps[0].mipmap_count=1;loads=uploads=0;charged=0; + texture_prepare_map();assert(loads==3 && uploads==3 && charged<=1024*1024); + loads=uploads=0;charged=0;fail=1;texture_prepare_map();assert(loads==3 && !uploads && charged<=1024*1024); +#else + texture_prepare_map();assert(!loads && !uploads); +#endif + return 0; +} +''' + path = tmp_path/'prepare.c' + path.write_text(code) + binary = tmp_path/('prepare.exe' if os.name=='nt' else 'prepare') + flags = ['--target=i686-pc-windows-msvc', '-fuse-ld=lld'] if os.name=='nt' else ['-m32'] + if gles: flags += ['-DHALO_GLES=1'] + result = subprocess.run([compiler,*flags,'-std=gnu89',str(path),'-o',str(binary)],capture_output=True,text=True) + assert result.returncode==0,result.stderr + subprocess.run([str(binary)],check=True) diff --git a/tools/test_third_person.py b/tools/test_third_person.py new file mode 100644 index 0000000000..e6ff7608d9 --- /dev/null +++ b/tools/test_third_person.py @@ -0,0 +1,731 @@ +"""Exercise the actual shoulder camera in a fake world, without game assets.""" +import re +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.mark.parametrize("degrees", [0, 70, 120, 150]) +def test_real_fov_restoration(tmp_path, degrees): + from harness import function + compiler = shutil.which("clang") or shutil.which("cc") + if not compiler: + pytest.skip("a C compiler is required") + actual = (ROOT / "port/linux/game/view_fov.c").read_text() + code = r''' +#include +#include +typedef float real; +typedef int boolean; +#define TRUE 1 +#define NONE -1 +#define MAXIMUM_LOCAL_PLAYERS 4 +#define _pi 3.14159265358979323846f +#define PIN(v,a,b) fminf(fmaxf(v,a),b) +#define TEST_FLAG(v,b) ((v)&(1u<<(b))) +enum {_object_dead_bit=0,_director_perspective_first_person=0}; +struct unit_datum {struct {int parent_object_index;unsigned damage_flags;} object;struct {int current_weapon_index;} unit;int definition_index;}; +struct unit_definition {struct {real camera_field_of_view;} unit;}; +static struct unit_datum body={{NONE,0},{0},0}; +static struct unit_definition definition={{1.2f}}; +static int scripted,*director_camera_scripted=&scripted,active[4]; +static real reticle_scales[4],authored_vertical[4]; +static double setting=TEST_DEGREES; +static unsigned long config_changes(void){return 0;} +static double config_real(char const *n){(void)n;return setting;} +static int cinematic_in_progress(void){return 0;} +static int director_get_perspective(short p){return active[p]?1:0;} +static int director_inhibited_facing(short p){(void)p;return 0;} +static long player_control_get_unit_index(short p){return p;} +static struct unit_datum *unit_try_and_get(long p){(void)p;return &body;} +static struct unit_definition *unit_definition_get(long p){(void)p;return &definition;} +static long unit_inventory_get_weapon(long p,int slot){(void)p;(void)slot;return 1;} +static real weapon_get_field_of_view(long w,real f,int z){(void)w;(void)f;(void)z;return .3f;} +static real render_camera_get_adjusted_field_of_view_tangent(real f){return tanf(f/2);} +static int third_person_active(short p){return p>=0&&p<4&&active[p];} +''' + function(actual, "render_fov_adjust") + function(actual, "render_fov_vertical") + r''' +#define CHECK(c) do{if(!(c))return __LINE__;}while(0) +int main(void){ + real native=2*atanf(.75f*tanf(.6f)), scoped=2*atanf(.75f*tanf(.15f)); + real expected=setting?2*atanf(tanf(setting*_pi/360)*9/16):native; + real baseline=render_fov_vertical(0,native),scale=reticle_scales[0]; + CHECK(fabsf(baseline-expected)<.00001f); + active[0]=1;CHECK(render_fov_vertical(0,native)==native&&reticle_scales[0]==1); + CHECK(fabsf(render_fov_vertical(1,native)-baseline)<.00001f); + active[0]=0;CHECK(render_fov_vertical(0,native)==baseline&&reticle_scales[0]==scale); + if(setting==0||setting>=120)CHECK(render_fov_vertical(0,scoped)==scoped); + CHECK(render_fov_vertical(0,native)==baseline);return 0; +} +''' + source = tmp_path / "fov.c" + source.write_text(code.replace("TEST_DEGREES", str(degrees))) + exe = tmp_path / ("fov.exe" if sys.platform == "win32" else "fov") + flags = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld"] if sys.platform == "win32" else ["-lm"] + compiled = subprocess.run([compiler, str(source), *flags, "-o", str(exe)], capture_output=True, text=True) + assert compiled.returncode == 0, compiled.stderr + assert subprocess.run([str(exe)], timeout=10).returncode == 0 + + +def test_camera_reset_load_hooks(): + """Checkpoint/core loads bypass objects_initialize_for_new_map.""" + from harness import function + code = (ROOT / "source/saved games/game_state.c").read_text() + callbacks = re.search(r"after_load_procs\[\]\s*=\s*\{(.*?)\};", code, re.S).group(1) + assert re.search(r"\bthird_person_reset\s*,", callbacks) + for name in ("game_state_revert", "game_state_try_and_load_from_persistent_storage", "game_state_load_core"): + assert "game_state_call_after_load_procs();" in function(code, name) + objects = (ROOT / "source/objects/objects.c").read_text() + assert "third_person_reset();" in function(objects, "objects_initialize_for_new_map") + + +@pytest.mark.parametrize("fault", [None, "zoom", "collision", "shoulder", "reticle", "doorway", "return", "frame_rate", "stairs", "held_respawn"]) +def test_shoulder_camera(tmp_path, fault): + compiler = shutil.which("clang") or shutil.which("cc") + if not compiler: + pytest.skip("a C compiler is required") + code = (ROOT / "port/linux/game/third_person.c").read_text() + code = re.sub(r'^#include[^\n]*', '', code, flags=re.M) + if fault == "zoom": + code = code.replace("player_control_get_zoom_level(local_player_index) != NONE", "0") + elif fault == "collision": + code = code.replace("hard_fraction * length < (was_active ? 0.10f : 0.14f)", "0") + elif fault == "shoulder": + code = code.replace("+ state->side * right.", "- state->side * right.") + elif fault == "reticle": + code = code.replace("screen.x - center_x", "0") + elif fault == "doorway": + code = code.replace("state->clear_time >= 0.10f", "state->clear_time >= 0.0f") + elif fault == "return": + code = code.replace("smooth_camera ? MAX(0.0f, state->return_time - dt) : 0.0f", "0.0f") + elif fault == "frame_rate": + code = code.replace("(real)(1.0 - exp(-dt / seconds))", "dt / (seconds + dt)") + elif fault == "stairs": + code = code.replace("state->vertical_lag - vertical_step", "state->vertical_lag") + elif fault == "held_respawn": + code = code.replace("state->look_requires_release = (halo_keyboard_actions(local_player_index) & (1UL << HALO_KEYBOARD_FREE_LOOK)) != 0;", "state->look_requires_release = FALSE;") + stub = r''' +#include +#include +#include +typedef int boolean; +typedef float real; +typedef struct {real i,j,k;} real_vector3d; +typedef struct {real x,y,z;} real_point3d; +typedef struct {real x,y;} real_point2d; +typedef struct {real yaw,pitch;} real_euler_angles2d; +#define _pi 3.14159265358979323846f +#define DEGREES_TO_RADIANS(d) ((d)*_pi/180.0f) +#define HALO_KEYBOARD_FREE_LOOK 20 +static unsigned long held; +static unsigned long halo_keyboard_actions(short p){return p==0?held:0;} +static void euler_angles2d_from_vector3d(real_euler_angles2d *a,real_vector3d const *v){a->yaw=atan2f(v->j,v->i);a->pitch=asinf(v->k);} +static void vector3d_from_euler_angles2d(real_vector3d *v,real_euler_angles2d const *a){v->i=cosf(a->yaw)*cosf(a->pitch);v->j=sinf(a->yaw)*cosf(a->pitch);v->k=sinf(a->pitch);} +static void observer_up_from_forward(real_vector3d const *f,real_vector3d *u){real_euler_angles2d a;euler_angles2d_from_vector3d(&a,f);a.pitch+=_pi/2;vector3d_from_euler_angles2d(u,&a);} +typedef struct {short x,y;} point2d; +typedef struct {short x0,y0,x1,y1;} rectangle2d; +#define TRUE 1 +#define FALSE 0 +#define NONE -1 +#define MAXIMUM_LOCAL_PLAYERS 4 +#define FLAG(n) (1u<<(n)) +#define TEST_FLAG(v,n) ((v)&FLAG(n)) +#define MIN(a,b) ((a)<(b)?(a):(b)) +#define MAX(a,b) ((a)>(b)?(a):(b)) +#define PIN(v,a,b) MIN(MAX(v,a),b) +enum {_director_perspective_first_person, _object_dead_bit=0, +_collision_test_front_facing_surfaces_bit, _collision_test_back_facing_surfaces_bit, +_collision_test_structure_bit, _collision_test_objects_bit, +_collision_test_objects_sight_blocking_flags=64, _collision_test_for_projectiles_flags=1024}; +struct unit_datum { + struct {long parent_object_index; unsigned damage_flags;} object; + struct {int current_zoom_level, desired_zoom_level; real_vector3d aiming_vector;} unit; +}; +struct render_camera {real_point3d position; real_vector3d forward,up; rectangle2d window_bounds;real vertical_field_of_view;}; +struct collision_result {real t; real_point3d point;}; +static struct {short local_player_index; struct render_camera camera; int frustum;} render; +static struct unit_datum body={{NONE,0},{NONE,NONE,{1,0,0}}}; +static struct unit_datum second_body={{NONE,0},{NONE,NONE,{1,0,0}}}; +static int split_world, second_zoom=NONE; +static unsigned long changes; +static int enabled, cinematic, scripted, perspective, inhibited, zoom=NONE, unit_id=1; +static int third_person_enabled(void){return enabled;} +static int *director_camera_scripted=&scripted; +static real wall=1, prop=1, soft_wall=1; +static int smooth=1; +static real_point3d eye={0,0,0}; +static void third_person_muzzle_target(short p,real_point3d *t){(void)p;(void)t;} +static int on_screen=1,left_shoulder; +static double setting_distance=.85,setting_height=.12,setting_offset=.24; +static real frame_dt=1.0f/60; +static real main_get_seconds_elapsed(void){return frame_dt;} +double config_real(char const *name){ + if(strstr(name,"distance"))return setting_distance; + if(strstr(name,"height"))return setting_height; + return setting_offset; +} +static void vector_from_points3d(real_point3d const *a,real_point3d const *b,real_vector3d *v){v->i=b->x-a->x;v->j=b->y-a->y;v->k=b->z-a->z;} + +int config_boolean(char const *name){return strstr(name,"smooth")?smooth:(strstr(name,"left_shoulder")?left_shoulder:enabled);} +unsigned long config_changes(void){return changes;} +static int cinematic_in_progress(void){return cinematic;} +static int third_person_director_active(short p){(void)p;return perspective==0;} +static int director_inhibited_facing(short p){(void)p;return inhibited;} +static real player_control_get_field_of_view(short p){(void)p;return 1.2f;} +static real render_camera_get_adjusted_field_of_view_tangent(real f){return tanf(f*.5f);} +static real arctangent(real a,real b){return atan2f(a,b);} +static int player_control_get_zoom_level(short p){return split_world&&p==1?second_zoom:zoom;} +static long player_control_get_unit_index(short p){return split_world&&p==1?22:unit_id;} +static struct unit_datum *unit_try_and_get(long i){return i==22?&second_body:&body;} +static struct unit_datum *unit_get(long i){return unit_try_and_get(i);} +static void unit_get_camera_position(long i,real_point3d *p){(void)i;*p=eye;} +static void cross_product3d(real_vector3d const *a,real_vector3d const *b,real_vector3d *v){ + v->i=a->j*b->k-a->k*b->j;v->j=a->k*b->i-a->i*b->k;v->k=a->i*b->j-a->j*b->i; +} +static real magnitude3d(real_vector3d const *v){return sqrtf(v->i*v->i+v->j*v->j+v->k*v->k);} +static void normalize3d(real_vector3d *v){real l=magnitude3d(v);v->i/=l;v->j/=l;v->k/=l;} +static void scale_vector3d(real_vector3d const *v,real s,real_vector3d *o){o->i=v->i*s;o->j=v->j*s;o->k=v->k*s;} +static void point_from_line3d(real_point3d const *p,real_vector3d const *v,real s,real_point3d *o){ + o->x=p->x+v->i*s;o->y=p->y+v->j*s;o->z=p->z+v->k*s; +} +static int collision_test_pill_new(unsigned long f,real_point3d const *p,real_vector3d const *v,real r,long i,struct collision_result *c){ + (void)f;(void)p;(void)v;(void)i;c->t=r>.08f?MIN(wall,soft_wall):wall;return c->t<1; +} +static int collision_test_vector(unsigned long f,real_point3d const *p,real_vector3d const *v,long i,struct collision_result *c){ + (void)i;c->t=f==1024?.01f:prop;point_from_line3d(p,v,c->t,&c->point);return c->t<1; +} +static int render_camera_world_to_screen(struct render_camera const *c,int const *f,real_point3d const *p,real_point2d *s){ + (void)c;(void)f;s->x=350+p->y;s->y=260;return on_screen && p->x==10; +} +''' + checks = r''' +#define CHECK(c) do {if(!(c))return __LINE__;}while(0) +static struct render_camera fresh(void){struct render_camera c={{0,0,0},{1,0,0},{0,0,1},{0,0,640,480}};c.position=eye;return c;} +static struct render_camera settle(short player){int i;struct render_camera c;for(i=0;i<180;i++){c=fresh();third_person_camera(player,&c);}return c;} +int main(void){ + struct render_camera c=fresh();point2d p={320,240}; + int k,n,fps,a,b,d,h,o;real sides[3];struct shoulder_camera_state other; + real_euler_angles2d steep={0,DEGREES_TO_RADIANS(85)}; + third_person_camera(0,&c);CHECK(!third_person_active(0)&&c.position.x==0); + enabled=1;changes++;c=settle(0); + CHECK(third_person_active(0)&&c.position.x<-.8f&&c.position.y<-.2f&&c.position.z>.1f); + CHECK(body.unit.aiming_vector.i==1&&eye.x==0); + render.camera=c;CHECK(third_person_reticle(&p,.5f));CHECK(p.x==380&&p.y==280); + on_screen=0;CHECK(!third_person_reticle(&p,1));on_screen=1; + zoom=0;c=fresh();third_person_camera(0,&c);CHECK(!third_person_active(0)&&c.position.x==0);zoom=NONE; + body.unit.current_zoom_level=0;third_person_camera(0,&c);CHECK(!third_person_active(0));body.unit.current_zoom_level=NONE; + body.unit.desired_zoom_level=0;third_person_camera(0,&c);CHECK(!third_person_active(0));body.unit.desired_zoom_level=NONE; + body.object.parent_object_index=2;third_person_camera(0,&c);CHECK(!third_person_active(0));body.object.parent_object_index=NONE; + body.object.damage_flags=1;third_person_camera(0,&c);CHECK(!third_person_active(0));body.object.damage_flags=0; + cinematic=1;third_person_camera(0,&c);CHECK(!third_person_active(0));cinematic=0; + scripted=1;third_person_camera(0,&c);CHECK(!third_person_active(0));scripted=0; + perspective=1;third_person_camera(0,&c);CHECK(!third_person_active(0));perspective=0; + unit_id=NONE;third_person_camera(0,&c);CHECK(!third_person_active(0));unit_id=1; + c=settle(0);wall=.5f;c=fresh();third_person_camera(0,&c);CHECK(third_person_active(0)&&c.position.x>-.45f&&c.position.x<-.35f); + wall=.05f;c=fresh();third_person_camera(0,&c);CHECK(!third_person_active(0)&&c.position.x==0);wall=1; + prop=.5f;c=settle(0);CHECK(third_person_active(0)&&c.position.x>-.4f);prop=1; + c=settle(1);CHECK(third_person_active(1)); + left_shoulder=1;changes++;c=fresh();third_person_camera(1,&c);CHECK(c.position.y<0); + c=settle(1);CHECK(c.position.y>.23f); + setting_distance=1.5;setting_height=.3;setting_offset=.4;changes++;c=settle(1); + CHECK(c.position.x < -1.49f && c.position.y>.39f && c.position.z>.29f); + wall=.05;c=fresh();third_person_camera(1,&c);CHECK(!third_person_active(1));wall=1; + c=fresh();third_person_camera(1,&c);CHECK(!third_person_active(1)&&c.position.x==0); + c=settle(1);CHECK(third_person_active(1)); + setting_distance=NAN;setting_height=100;setting_offset=-1;changes++;c=settle(1); + CHECK(c.position.x>-.86f&&c.position.x<-.84f&&c.position.y>.23f&&c.position.y<.25f); + setting_distance=.3;setting_height=0;setting_offset=0;changes++;c=settle(1); + CHECK(third_person_active(1)&&c.position.x>-.301f&&c.position.x<-.299f); + soft_wall=0;c=settle(1);CHECK(third_person_active(1));soft_wall=1; + smooth=0;changes++;setting_distance=1.0;changes++;c=fresh();third_person_camera(1,&c); + CHECK(c.position.x < -.99f); + left_shoulder=0;setting_offset=.24;changes++;c=fresh();third_person_camera(1,&c);CHECK(c.position.y<-.23f); + third_person_reset();CHECK(!third_person_active(1));c=settle(1); + + c=settle(0);held=1UL<.7f&&c.forward.k>.1f); + CHECK(body.unit.aiming_vector.i==1&&body.unit.aiming_vector.j==0); + CHECK(!third_person_reticle(&p,1)); + wall=0;c=fresh();third_person_camera(0,&c); + CHECK(!third_person_active(0)&&c.forward.i==1&&c.forward.j==0&&c.up.k==1); + CHECK(third_person_free_look_input(0,.1f,0));wall=1;c=settle(0); + held=0;CHECK(!third_person_free_look_input(0,0,0));c=fresh();third_person_camera(0,&c); + CHECK(c.forward.i==1&&c.forward.j==0); /* sharp release */ + smooth=1;changes++;c=settle(0);held=1UL<0&&c.forward.j<.85f);c=settle(0);CHECK(c.forward.j==0); + held=1UL<=-.06f); + c=settle(0);CHECK(fabsf(cameras[0].vertical_lag)<.00001f); + for(k=0;k<20;k++){eye.z+=.01f;c=fresh();third_person_camera(0,&c);CHECK(cameras[0].vertical_lag>=-.06f);} + smooth=0;changes++;eye.z+=.1f;c=fresh();third_person_camera(0,&c);CHECK(cameras[0].vertical_lag==0); + smooth=1;changes++;eye.z+=3;c=fresh();third_person_camera(0,&c);CHECK(cameras[0].vertical_lag==0); + eye.z=0;c=settle(0); + /* Equal elapsed times give the same offset settling at 30/60/144 fps. */ + for(n=0;n<3;n++){ + fps=n==0?30:(n==1?60:144);frame_dt=1.0f/fps; + left_shoulder=0;changes++;c=settle(0);left_shoulder=1;changes++; + for(k=0;k.996f); + /* Every lifecycle exit clears orbit and requires a fresh press, even + when rendering observes the transition before gameplay input does. */ + held=0;third_person_reset();c=settle(0); + for(k=0;k<10;k++){ + held=1UL<local_player_index)", "1") + code = r''' +#include +#include +typedef int boolean; +typedef float real; +#define NONE -1 +#define FALSE 0 +#define TRUE 1 +#define MAXIMUM_LOCAL_PLAYERS 4 +#define _pi 3.14159265358979323846f +#define FLAG(b) (1u<<(b)) +#define TEST_FLAG(v,b) ((v)&FLAG(b)) +#define match_assert(a,b,c) ((void)0) +#define TAG_BLOCK_GET_ELEMENT(a,b,t) (&fake_seat) +enum {_effect_camera_mode_independent_of_camera_mode, _effect_camera_mode_first_person_only, +_effect_camera_mode_third_person_only, _effect_camera_mode_both, _effect_location_first_person_bit=15, +_director_perspective_first_person=0, _unit_seat_gunner_bit=1}; +struct effect_datum {short local_player_index;}; +struct effect_location_datum {long next_instance_location_index; int node_designator;}; +struct player_datum {long unit_index;}; +struct unit_datum {struct {long parent_object_index;} object;struct {int parent_seat_index;} unit;long definition_index;}; +struct unit_seat {unsigned flags;}; +static struct unit_seat fake_seat; +static struct unit_datum body={{NONE},{NONE},0}; +static struct player_datum player={1}; +static int active, players=1; +static real reticle_scales[4],authored_vertical[4]; +static struct effect_location_datum locations[2]={{1,0},{NONE,32768}}; +static boolean third_person_active(short p){return p==0&&active;} +static real render_fov_adjust(short p,real f){(void)p;return active?f:2.0f;} +static int local_player_count(void){return players;} +static struct effect_location_datum *effect_location_get(long n){return &locations[n];} +static int director_get_perspective(short p){return p==0&&active?1:0;} +static long local_player_get_player_index(short p){return p;} +static struct player_datum *player_get(long n){(void)n;return &player;} +static struct unit_datum *unit_get(long n){(void)n;return &body;} +''' + fov + effects + visibility + r''' +#define CHECK(c) do{if(!(c))return __LINE__;}while(0) +int main(void){ + struct effect_datum e={0};long index=0; + CHECK(render_fov_vertical(0,1.0f)==2.0f&&reticle_scales[0]<1&&authored_vertical[0]==1); + CHECK(local_player_is_first_person(0)); + CHECK(effect_location_get_next_instance(&e,&index,3)==&locations[1]); + active=1;index=0; + CHECK(render_fov_vertical(0,1.0f)==1.0f&&reticle_scales[0]==1&&authored_vertical[0]==0); + CHECK(!local_player_is_first_person(0)); + CHECK(effect_location_get_next_instance(&e,&index,3)==&locations[0]); + CHECK(effect_location_get_next_instance(&e,&index,3)==NULL); + index=0;CHECK(effect_location_get_next_instance(&e,&index,1)==&locations[1]); + index=0;CHECK(effect_location_get_next_instance(&e,&index,2)==&locations[0]); + active=0;index=0; + CHECK(render_fov_vertical(0,1.0f)==2.0f&&reticle_scales[0]<1); + CHECK(effect_location_get_next_instance(&e,&index,3)==&locations[1]); + players=2;index=0;CHECK(effect_location_get_next_instance(&e,&index,3)==&locations[0]); + return 0; +} +''' + source = tmp_path / "perspective.c" + source.write_text(code) + exe = tmp_path / ("perspective.exe" if sys.platform == "win32" else "perspective") + flags = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld"] if sys.platform == "win32" else ["-lm"] + compiled = subprocess.run([compiler, str(source), *flags, "-o", str(exe)], capture_output=True, text=True) + assert compiled.returncode == 0, compiled.stderr + ran = subprocess.run([str(exe)], timeout=10) + assert (ran.returncode != 0) == bool(fault), ran.returncode + + +def test_muzzle_origin_and_host_history(tmp_path): + compiler = shutil.which("clang") or shutil.which("cc") + if not compiler: + pytest.skip("a C compiler is required") + actual = (ROOT / "port/linux/game/third_person_weapon.c").read_text() + actual = re.sub(r'^#include[^\n]*', '', actual, flags=re.M) + code = r''' +#include +#include +#include +typedef float real; +typedef int boolean; +typedef struct {real x,y,z;} real_point3d; +typedef struct {real i,j,k;} real_vector3d; +#define TRUE 1 +#define FALSE 0 +#define NONE -1 +#define MAXIMUM_LOCAL_PLAYERS 4 +#define MAX(a,b) ((a)>(b)?(a):(b)) +#define TEST_FLAG(v,b) ((v)&(1u<<(b))) +enum {_game_connection_local=0,_object_dead_bit=0,_collision_test_for_projectiles_flags=1}; +enum {_game_connection_network_server=1}; +typedef short director_perspective; +static int authored_following; +static short director_desired_perspective(long u,director_perspective *p){(void)u;*p=0;return authored_following;} +enum {_weapon_trigger_uses_weapon_origin_bit=5,_weapon_trigger_projectiles_cannot_be_aimed_bit=11, +_unit_fires_from_camera_bit=0,_trigger_charging=2,_trigger_charged=3,_trigger_spewing=6}; +struct unit_datum {struct {long parent_object_index;unsigned damage_flags;} object;struct {short current_weapon_index;real_vector3d aiming_vector;long player_index;short current_zoom_level;unsigned control_flags;} unit;long definition_index;}; +#define THIRD_PERSON_INPUT_BIT 16 +#define _third_person_forced_off 2 +static int policy; +static short third_person_policy(void){return policy;} +#define DATUM_INDEX_TO_ABSOLUTE_INDEX(n) (n) +char const *config_string(char const *n){(void)n;return "";} +void platform_log(char const *n,...){(void)n;} +struct tag_block {long count;void *address;}; +struct weapon_trigger_definition {unsigned flags;real_point3d first_person_weapon_offset;struct tag_block firing_effects;real spew_time;}; +struct weapon_firing_effect_definition {struct {long index;} effects[3];}; +struct effect_definition {struct tag_block locations;}; +#define EFFECT_DEFINITION_TAG 1 +static char effect_marker[32]="primary trigger1"; +static struct effect_definition effect={{1,effect_marker}}; +static struct weapon_firing_effect_definition firing={{{0},{-1},{-1}}}; +static void *tag_get(int group,long n){(void)group;(void)n;return &effect;} +struct weapon_definition {struct {struct tag_block triggers;} weapon;}; +struct weapon_datum {long definition_index;struct {struct {int state;short firing_effect_index;} triggers[2];} weapon;}; +struct unit_definition {struct {unsigned flags;} unit;}; +static struct weapon_trigger_definition trigger_defs[2]; +static struct weapon_definition definition={{{2,trigger_defs}}}; +static struct weapon_datum weapon; +static struct unit_definition unit_def={{1}}; +#define TAG_BLOCK_GET_ELEMENT(block,n,type) ((type *)(block)->address+(n)) +static struct weapon_datum *weapon_get(long n){(void)n;return &weapon;} +static struct weapon_definition *weapon_definition_get(long n){(void)n;return &definition;} +static struct unit_definition *unit_definition_get(long n){(void)n;return &unit_def;} +static real_vector3d up_axis={0,0,1},left_axis={0,1,0}; +static real_vector3d const *global_up3d=&up_axis,*global_left3d=&left_axis; +static void cross_product3d(real_vector3d const *a,real_vector3d const *b,real_vector3d *v){*v=(real_vector3d){a->j*b->k-a->k*b->j,a->k*b->i-a->i*b->k,a->i*b->j-a->j*b->i};} +static real dot_product3d(real_vector3d const *a,real_vector3d const *b){return a->i*b->i+a->j*b->j+a->k*b->k;} +static void unit_adjust_projectile_ray(long u,real_point3d *p,real_vector3d *v,real *speed,int adjust,int aim){(void)u;(void)aim;(void)v;*speed=0;if(adjust){p->y=0;p->z=0;}} +struct object_marker {struct {real_point3d position;} matrix;}; +struct collision_result {real t;real_point3d point;}; +static struct unit_datum unit={{NONE,0},{0,{1,0,0}},0}; +static int connection,active=1,zoom=NONE,has_marker=1,blocked; +static real target_distance=10, muzzle_side; +static int mcc_ray_enabled, mcc_preview_calls; +static boolean mcc_projectile_ray(long w,long u,short t,boolean firing, + real_point3d *p,real_vector3d *v,real *speed,long *target){ + (void)w;(void)u;(void)t; + if(!mcc_ray_enabled)return FALSE; + if(firing)return FALSE; + mcc_preview_calls++;*p=(real_point3d){0,.2f,0};*v=(real_vector3d){1,0,0}; + *speed=0;*target=NONE;return TRUE; +} +static int scene; +static real_point3d last_long_origin; +static int marker_trigger; +static short game_connection(void){return connection;} +static boolean third_person_active(short p){return p==0&&active;} +static long player_control_get_unit_index(short p){return p==0?1:NONE;} +static short player_control_get_zoom_level(short p){(void)p;return zoom;} +static struct unit_datum *unit_try_and_get(long i){return i==1?&unit:NULL;} +static struct unit_datum *unit_get(long i){return unit_try_and_get(i);} +static long unit_inventory_get_weapon(long i,short n){(void)i;(void)n;return 2;} +static int object_get_marker_by_name(long w,char const *n,struct object_marker *m,short count){ + (void)w;(void)count;marker_trigger=strstr(n,"secondary")!=NULL;m->matrix.position=(real_point3d){1,muzzle_side,marker_trigger?-.4f:(!strcmp(n,"primary trigger1")?-.3f:-.2f)};return has_marker; +} +static void unit_get_camera_position(long u,real_point3d *p){(void)u;*p=(real_point3d){0,0,0};} +static void vector_from_points3d(real_point3d const *a,real_point3d const *b,real_vector3d *v){*v=(real_vector3d){b->x-a->x,b->y-a->y,b->z-a->z};} +static real magnitude3d(real_vector3d const *v){return sqrtf(v->i*v->i+v->j*v->j+v->k*v->k);} +static real normalize3d(real_vector3d *v){real l=magnitude3d(v);if(l){v->i/=l;v->j/=l;v->k/=l;}return l;} +static void scale_vector3d(real_vector3d const *v,real s,real_vector3d *o){*o=(real_vector3d){v->i*s,v->j*s,v->k*s};} +static void point_from_line3d(real_point3d const *p,real_vector3d const *v,real t,real_point3d *o){*o=(real_point3d){p->x+v->i*t,p->y+v->j*t,p->z+v->k*t};} +static int collision_test_vector(unsigned long f,real_point3d const *p,real_vector3d const *v,long u,struct collision_result *c){ + (void)f;(void)u; + if(scene && v->i>0){ + real plane=scene==2?.5f:1.5f; + real t=(plane-p->x)/v->i; + if(t>=0&&t<=1&&(scene==2||p->z+v->k*t<-.1f)){ + c->t=t;point_from_line3d(p,v,t,&c->point);return 1; + } + } + if(magnitude3d(v)>100){last_long_origin=*p; + if(v->i>0 && target_distance>p->x){c->t=(target_distance-p->x)/v->i;point_from_line3d(p,v,c->t,&c->point);return 1;} + return 0;} + if(blocked){c->t=.5f;point_from_line3d(p,v,.5f,&c->point);return 1;} + return 0; +} +''' + actual + r''' +#define CHECK(c) do{if(!(c))return __LINE__;}while(0) +int main(void){ + real_point3d origin={0,0,0},target={10,0,0};real_vector3d forward={1,0,0}; + third_person_muzzle_shot(2,1,0,&origin,&forward); + CHECK(origin.x==1&&origin.z==-.2f&&forward.k>0); + CHECK(fabsf(origin.z+forward.k*(9/forward.i))<.0001f); + connection=1;origin=(real_point3d){0,0,0};forward=(real_vector3d){1,0,0}; + third_person_muzzle_shot(2,1,0,&origin,&forward);CHECK(origin.x==0&&forward.k==0); + connection=2;third_person_muzzle_shot(2,1,0,&origin,&forward);CHECK(origin.x==0); + unit.unit.current_zoom_level=NONE;unit.unit.control_flags=1u<<16; + active=0;CHECK(third_person_muzzle_shot(2,1,0,&origin,&forward));CHECK(origin.x==1); + origin=(real_point3d){0,0,0};forward=(real_vector3d){1,0,0}; + policy=2;CHECK(!third_person_muzzle_shot(2,1,0,&origin,&forward));CHECK(origin.x==0); + policy=0;unit.unit.current_zoom_level=0;CHECK(!third_person_muzzle_shot(2,1,0,&origin,&forward)); + unit.unit.current_zoom_level=NONE;unit.unit.player_index=NONE;CHECK(!third_person_muzzle_shot(2,1,0,&origin,&forward)); + unit.unit.player_index=0;unit.object.parent_object_index=7;CHECK(!third_person_muzzle_shot(2,1,0,&origin,&forward)); + unit.object.parent_object_index=NONE;unit.unit.control_flags=0;CHECK(!third_person_muzzle_shot(2,1,0,&origin,&forward)); + connection=0;active=0;third_person_muzzle_shot(2,1,0,&origin,&forward);CHECK(origin.x==0); + active=1;zoom=0;third_person_muzzle_shot(2,1,0,&origin,&forward);CHECK(origin.x==0); + zoom=NONE;has_marker=0;third_person_muzzle_shot(2,1,0,&origin,&forward);CHECK(origin.x==0); + has_marker=1;third_person_muzzle_shot(2,1,5,&origin,&forward);CHECK(origin.x==0); + blocked=1;third_person_muzzle_shot(2,1,0,&origin,&forward);CHECK(origin.x>.48f&&origin.x<.5f); + blocked=0;third_person_muzzle_target(0,&target);CHECK(target.x==10); + CHECK(last_long_origin.z==-.2f&&marker_trigger==0); + mcc_ray_enabled=1;third_person_muzzle_target(0,&target); + CHECK(mcc_preview_calls==1&&fabsf(target.y-.2f)<.0001f); + mcc_ray_enabled=0;third_person_muzzle_target(0,&target);CHECK(fabsf(target.y)<.0001f); + weapon.weapon.triggers[0].state=_trigger_charged;third_person_muzzle_target(0,&target); + CHECK(last_long_origin.z==-.4f&&marker_trigger==1); + weapon.weapon.triggers[0].state=_trigger_charging;third_person_muzzle_target(0,&target);CHECK(marker_trigger==0); + weapon.weapon.triggers[0].state=0; + trigger_defs[0].first_person_weapon_offset.y=-.1f;third_person_muzzle_target(0,&target); + CHECK(fabsf(target.y+.1f)<.0001f);trigger_defs[0].first_person_weapon_offset.y=0; + target_distance=.5f;origin=(real_point3d){0,0,0};forward=(real_vector3d){1,0,0}; + CHECK(third_person_muzzle_shot(2,1,0,&origin,&forward));CHECK(forward.i==1&&forward.k==0); + target_distance=10; + trigger_defs[0].firing_effects=(struct tag_block){1,&firing}; + origin=(real_point3d){1,0,0};forward=(real_vector3d){1,0,0}; + CHECK(third_person_muzzle_shot(2,1,0,&origin,&forward));CHECK(origin.z==-.3f); + strcpy(effect_marker,"smoke");origin=(real_point3d){1,0,0};forward=(real_vector3d){1,0,0}; + CHECK(third_person_muzzle_shot(2,1,0,&origin,&forward));CHECK(origin.z==-.2f); + weapon.weapon.triggers[0].firing_effect_index=9; + third_person_muzzle_target(0,&target);CHECK(last_long_origin.z==-.2f); + weapon.weapon.triggers[0].firing_effect_index=0;trigger_defs[0].firing_effects.count=0; + scene=1;muzzle_side=.25f; + origin=(real_point3d){1,0,0};forward=(real_vector3d){1,0,0}; + CHECK(third_person_muzzle_shot(2,1,0,&origin,&forward)); + CHECK(origin.x==1&&origin.y==.25f); + third_person_muzzle_target(0,&target);CHECK(target.x==1.5f&&target.z<-.1f); + CHECK(fabsf((target.y-origin.y)*forward.i-(target.x-origin.x)*forward.j)<.0001f); + muzzle_side=-.25f;third_person_muzzle_target(0,&target);CHECK(target.x==1.5f&&target.y<0); + scene=2;origin=(real_point3d){1,0,0};forward=(real_vector3d){1,0,0}; + CHECK(third_person_muzzle_shot(2,1,0,&origin,&forward)); + CHECK(origin.x<.5f&&origin.x>.48f&&forward.i>0); + third_person_muzzle_target(0,&target);CHECK(fabsf(target.x-.5f)<.0001f); + scene=0;muzzle_side=0; + connection=1;target=(real_point3d){10,0,0};third_person_muzzle_target(0,&target);CHECK(target.x==10); + /* Host-owned history follows the same eligibility, barrels and cover clamp. */ + unit.unit.control_flags=1u<.48f&&target.x<.5f); + return 0; +} +''' + source = tmp_path / "muzzle.c" + source.write_text(code) + exe = tmp_path / ("muzzle.exe" if sys.platform == "win32" else "muzzle") + flags = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld"] if sys.platform == "win32" else ["-lm"] + compiled = subprocess.run([compiler, str(source), *flags, "-o", str(exe)], capture_output=True, text=True) + assert compiled.returncode == 0, compiled.stderr + assert subprocess.run([str(exe)], timeout=10).returncode == 0 + +@pytest.mark.parametrize("fault", [False, True]) +def test_muzzle_bsp_repair_excludes_shooter(tmp_path, fault): + from harness import function + compiler = shutil.which("clang") or shutil.which("cc") + if not compiler: + pytest.skip("a C compiler is required") + actual = function((ROOT / "source/objects/objects.c").read_text(), "object_force_inside_bsp_ignoring") + if fault: + actual = actual.replace("&object->object.position, ignore_object_index,", "&object->object.position, NONE,") + code = r''' +#include +typedef int boolean; +typedef struct {float x,y,z;} real_point3d; +#define TRUE 1 +#define FALSE 0 +#define NONE -1 +#define MAXIMUM_COLLISION_USER_STACK_DEPTH 8 +#define _collision_test_for_projectiles_flags 1 +#define match_assert(a,b,c) ((void)0) +struct location {short cluster_index;}; +struct object_datum {struct {real_point3d position;struct location location;} object;}; +struct collision_result {real_point3d point;struct location location;}; +static struct object_datum projectile={{{1,0,-.2f},{0}}}; +static int global_current_collision_user_depth=1,global_current_collision_users[8],wall,translated; +static struct object_datum *object_get(long i){(void)i;return &projectile;} +static int collision_test_line(int flags,real_point3d const *a,real_point3d const *b,long ignore,struct collision_result *c){ + (void)flags;(void)a;(void)b; + c->location.cluster_index=0;c->point=(real_point3d){.1f,0,0}; + if(ignore!=7)return 1; /* the eye-to-barrel line crosses the shooter */ + if(wall){c->point=(real_point3d){.5f,0,-.1f};return 1;}return 0; +} +static void object_translate(long i,real_point3d const *p,struct location const *l){(void)i;projectile.object.position=*p;projectile.object.location=*l;translated++;} +static void object_compute_node_matrices(long i){(void)i;} +''' + actual + r''' +#define CHECK(c) do{if(!(c))return __LINE__;}while(0) +int main(void){real_point3d eye={0,0,0}; + CHECK(object_force_inside_bsp_ignoring(2,&eye,7)); + CHECK(translated==0&&projectile.object.position.x==1); + wall=1;CHECK(object_force_inside_bsp_ignoring(2,&eye,7)); + CHECK(translated==1&&projectile.object.position.x==.5f); + wall=0;CHECK(object_force_inside_bsp_ignoring(2,&eye,NONE)); + CHECK(translated==2&&projectile.object.position.x==.1f); + CHECK(global_current_collision_user_depth==1);return 0; +} +''' + source = tmp_path / "repair.c" + source.write_text(code) + exe = tmp_path / ("repair.exe" if sys.platform == "win32" else "repair") + flags = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld"] if sys.platform == "win32" else ["-lm"] + compiled = subprocess.run([compiler, str(source), *flags, "-o", str(exe)], capture_output=True, text=True) + assert compiled.returncode == 0, compiled.stderr + assert (subprocess.run([str(exe)], timeout=10).returncode != 0) == fault diff --git a/tools/test_third_person_director.py b/tools/test_third_person_director.py new file mode 100644 index 0000000000..2274be48e3 --- /dev/null +++ b/tools/test_third_person_director.py @@ -0,0 +1,232 @@ +"""Exercise the real director selection and modifier-wheel routing.""" +import re +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest +from harness import function + +ROOT = Path(__file__).resolve().parents[1] + + +def run_c(tmp_path, code): + compiler = shutil.which("clang") or shutil.which("cc") + if not compiler: + pytest.skip("a C compiler is required") + source = tmp_path / "check.c" + source.write_text(code) + exe = tmp_path / ("check.exe" if sys.platform == "win32" else "check") + flags = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld"] if sys.platform == "win32" else ["-lm"] + built = subprocess.run([compiler, str(source), *flags, "-o", str(exe)], capture_output=True, text=True) + assert built.returncode == 0, built.stderr + result = subprocess.run([str(exe)], capture_output=True, text=True, timeout=10) + assert result.returncode == 0, result.stdout + result.stderr + + +def test_director_transitions(tmp_path): + actual = (ROOT / "source/camera/director.c").read_text() + feature = (ROOT / "port/linux/game/third_person_director.c").read_text() + code = r''' +#include +#include +typedef int boolean; +typedef short director_perspective; +#define FALSE 0 +#define TRUE 1 +#define MAXIMUM_NUMBER_OF_LOCAL_PLAYERS 4 +enum {_director_perspective_first_person, _director_perspective_third_person}; +typedef void (*director_camera_update_proc)(void *,void *,void *); +struct first_person_camera {float fov;}; +struct first_person_camera_action {short local_player;}; +struct first_person_camera_result {int sentinel;}; +struct following_camera {int unused;}; +struct director {director_camera_update_proc camera_proc;float camera_change_pause,debug_input_scale; + int perspective,seat_state,debug_controls;char camera_data[64];}; +static struct director directors[4]; +static int available[4],active[4],following,seat,passenger; +static int passenger_camera_enabled(short p){return p==0&&passenger;} +static struct director *director_get(short p){return &directors[p];} +static void sound_listener_motion_reset(short p){(void)p;} +static int third_person_available(short p){return available[p];} +static int third_person_active(short p){return active[p];} +static long player_control_get_unit_index(short p){return p;} +static short director_desired_perspective(long u,director_perspective *p){(void)u;*p=seat;return following;} +static void first_person_camera_new(struct first_person_camera *c){c->fov=1.2f;} +static void following_camera_new(struct following_camera *c){(void)c;} +static void first_person_camera_update(struct first_person_camera *c,struct first_person_camera_action const *a, + struct first_person_camera_result *r){(void)c;r->sentinel=123+a->local_player;} +static void following_camera_update(void *a,void *b,void *c){(void)a;(void)b;(void)c;} +static void scripted_camera_update(void *a,void *b,void *c){(void)a;(void)b;(void)c;} +static void other_camera(void *a,void *b,void *c){(void)a;(void)b;(void)c;} +void third_person_camera_update(void *,void *,void *); +''' + code += function(actual, "director_camera_is") + code += re.sub(r"^#include[^\n]*", "", feature, flags=re.M) + code += function(actual, "director_set_camera") + code += function(actual, "director_get_perspective") + code += function(actual, "director_choose_game_perspective") + code += r''' +#define CHECK(c) do{if(!(c)){printf("line %d: %s\n",__LINE__,#c);return 1;}}while(0) +int main(void){ + struct director *d=&directors[0];struct first_person_camera_action a={0};struct first_person_camera_result r={0}; + d->camera_proc=(director_camera_update_proc)first_person_camera_update; + director_choose_game_perspective(0,0);CHECK(!third_person_director_active(0)); + available[0]=1;d->camera_change_pause=1;director_choose_game_perspective(0,0); + CHECK(third_person_director_active(0)&&d->camera_change_pause==0); + d->camera_proc(d->camera_data,&a,&r);CHECK(r.sentinel==123); + active[0]=1;CHECK(director_get_perspective(0)==1); + active[0]=0;CHECK(director_get_perspective(0)==0); /* same-frame collision fallback */ + active[0]=1;CHECK(director_get_perspective(0)==1); + available[0]=0;CHECK(director_get_perspective(0)==0); /* scope/policy before next render */ + director_choose_game_perspective(0,0);CHECK(d->camera_proc==(director_camera_update_proc)first_person_camera_update); + available[0]=1;director_choose_game_perspective(0,0);CHECK(third_person_director_active(0)); + available[0]=0;following=1;seat=2;director_choose_game_perspective(0,0); + CHECK(d->camera_proc==following_camera_update); /* preserve the vehicle camera */ + following=0;seat=0;available[0]=1;director_choose_game_perspective(0,0); + director_choose_game_perspective(0,0);CHECK(third_person_director_active(0)); + /* Passenger override can change without changing the seat identity. */ + available[0]=0;passenger=1;director_choose_game_perspective(0,0); + CHECK(d->camera_proc==following_camera_update); + passenger=0;director_choose_game_perspective(0,0); + CHECK(d->camera_proc==(director_camera_update_proc)first_person_camera_update); + available[0]=1;director_choose_game_perspective(0,0);CHECK(third_person_director_active(0)); + d->camera_proc=other_camera;director_choose_game_perspective(0,0);CHECK(d->camera_proc==other_camera); + d->camera_proc=scripted_camera_update;director_choose_game_perspective(0,0);CHECK(d->camera_proc==scripted_camera_update); + director_choose_game_perspective(0,1);CHECK(third_person_director_active(0)); /* script release */ + directors[1].camera_proc=(director_camera_update_proc)first_person_camera_update; + director_choose_game_perspective(1,0);CHECK(!third_person_director_active(1)&&third_person_director_active(0)); + CHECK(!third_person_director_active(-1)&&!third_person_director_active(4)); + return 0; +} +''' + run_c(tmp_path, code) + + +def test_camera_scroll_input(tmp_path): + feature = (ROOT / "port/linux/game/third_person_input.c").read_text() + platform = (ROOT / "port/linux/src/xinput_sdl.c").read_text() + code = '#include "' + (ROOT / 'port/linux/include/halo_keyboard.h').as_posix() + '"\n' + code += r""" +#include +#include +#include +#include +#define FALSE 0 +#define TRUE 1 +#define PIN(v,a,b) ((v)<(a)?(a):((v)>(b)?(b):(v))) +#define DISTANCE (1UL<fence, GL_SYNC_FLUSH_COMMANDS_BIT, 0);", + "GLenum status = GL_ALREADY_SIGNALED;") + if negative_control == "wrong_offset": + read_code = mutated(read_code, "device.visibility_batch * VISIBILITY_TEST_SLOTS + i", "i") + if negative_control == "blocking_wait": + read_code = mutated(read_code, "glClientWaitSync(batch->fence, GL_SYNC_FLUSH_COMMANDS_BIT, 0)", "glClientWaitSync(batch->fence, GL_SYNC_FLUSH_COMMANDS_BIT, 1)") + if negative_control == "early_fence": + statement = "batch->fence = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);" + read_code = mutated(read_code, statement, "((void)0);") + loop = "for (i = 0; i < batch->count; i++)\n\t\t\tglGetQueryBufferObjectuiv" + read_code = mutated(read_code, loop, statement + "\n" + loop) + if negative_control == "unchecked_copy": + read_code = mutated(read_code, 'if (!batch->fence || (device.visibility_logging && !visibility_readback_gl_ok("query copies")))', "if (!batch->fence)") + if negative_control == "unchecked_wait": + read_code = mutated(read_code, "if (status != GL_ALREADY_SIGNALED && status != GL_CONDITION_SATISFIED)", + "if (FALSE)") + if negative_control == "untyped_pool": + code = mutated(code, "glCreateQueries(VISIBILITY_QUERY, (GLsizei)count, queries)", + "glGenQueries((GLsizei)count, queries)") + if negative_control == "invalid_pool": + code = mutated(code, "if (!success || zeros || duplicates || invalid)", "if (FALSE)") + if negative_control == "early_read": + read_code = mutated(read_code, "if (!available)", "if (FALSE)") + if negative_control == "wrong_scale": + read_code = mutated(read_code, "float area = batch->areas[test];", + "float area = device.query_area[batch->slots[test]];") + if negative_control == "wrong_query": + read_code = mutated(read_code, "glGetQueryObjectuiv(batch->queries[test], GL_QUERY_RESULT, &samples);", + "glGetQueryObjectuiv(batch->queries[(test + 1) % VISIBILITY_TEST_SLOTS], GL_QUERY_RESULT, &samples);") + if negative_control == "reuse_pending": + read_code = mutated(read_code, "&& !batch->sealed && !batch->failed)", ")") + code = mutated(code, "if (!batch->sealed && !batch->failed && batch->count < VISIBILITY_TEST_SLOTS)", + "if ((batch->count = 0) == 0)") + if negative_control == "no_flush": + read_code = mutated(read_code, "glClientWaitSync(batch->fence, GL_SYNC_FLUSH_COMMANDS_BIT, 0)", + "glClientWaitSync(batch->fence, 0, 0)") + if negative_control == "no_unbind": + read_code = mutated(read_code, "glBindBuffer(GL_QUERY_BUFFER, 0);", "((void)0);") + if negative_control == "ignore_error": + read_code = mutated(read_code, 'if (!visibility_readback_gl_ok("result"))', "if (FALSE)") + if negative_control == "wrong_order": + read_code = mutated(read_code, "batch->serial < device.visibility_batches[oldest].serial", + "batch->serial > device.visibility_batches[oldest].serial") + prefix = r""" +#include +#include +#include +#include +#include +typedef unsigned int GLuint, DWORD, UINT, GLenum; +typedef unsigned int GLbitfield; +typedef intptr_t GLintptr, GLsizeiptr; +typedef struct fake_fence { int complete; unsigned copies; } *GLsync; +typedef unsigned long long ULONGLONG; +typedef int BOOL, HRESULT, GLsizei, GLint; +#define WINAPI +#define TRUE 1 +#define FALSE 0 +#define S_OK 0 +#define VISIBILITY_TEST_SLOTS 8 +#define VISIBILITY_BATCH_COUNT 3 +#define VISIBILITY_ALL_SAMPLES 0x7fffffff +#define VISIBILITY_QUERY 1 +#define GL_QUERY_RESULT_AVAILABLE 2 +#define GL_QUERY_RESULT 3 +#define GL_NO_ERROR 0 +#define GL_QUERY_BUFFER 4 +#define GL_QUERY_BUFFER_BINDING 5 +#define GL_VENDOR 6 +#define GL_MAP_WRITE_BIT 8 +#define VISIBILITY_UNCOPIED 0xFFFFFFFFUL +#define GL_SYNC_FLUSH_COMMANDS_BIT 1 +#define GL_MAP_READ_BIT 1 +#define GL_MAP_PERSISTENT_BIT 2 +#define GL_MAP_COHERENT_BIT 4 +#define GL_SYNC_GPU_COMMANDS_COMPLETE 7 +#define GL_TIMEOUT_EXPIRED 8 +#define GL_ALREADY_SIGNALED 9 +#define GL_CONDITION_SATISFIED 10 +#define GL_WAIT_FAILED 11 +#define platform_log(...) ((void)0) +static BOOL config_boolean(const char *key) { return FALSE; } +/* BATCH_TYPE */ +static struct { + BOOL gl_ready, visibility_test_active; + GLuint active_query, visibility_known[8]; + BOOL query_pending[8]; + float query_area[8]; + struct visibility_batch visibility_batches[VISIBILITY_BATCH_COUNT]; + unsigned long visibility_batch, frame; + ULONGLONG visibility_serial, visibility_ended[8], visibility_counted[8]; + BOOL visibility_logging, visibility_unavailable; + GLuint visibility_buffer; + volatile GLuint *visibility_mapped; + struct { unsigned long submitted, completed, samples, nonzero, maximum, + unavailable, dropped, failures; } visibility_stats; +} device; +static float target_scale[2] = {2, 3}; +static int target_samples = 4; +static struct { + GLuint samples; + BOOL available, object, pending, flushed, checked; +} gpu[1024]; +static GLuint active, next_samples, next_query = 1, query_buffer; +static unsigned reads, polls, flushes; +static BOOL direct_error, availability_error, binding_error, unbind_error; +static int zero_at = -1, duplicate_at = -1; +static BOOL fail_object, fail_create, fail_all; +static GLenum gpu_error; +static BOOL visibility_readback_gl_ok(const char *phase); +static GLenum glGetError(void) { GLenum error = gpu_error; gpu_error = 0; return error; } +static void glGenQueries(GLsizei count, GLuint *queries) { + int i; + for (i = 0; i < count; i++) { + if (fail_all || i == zero_at) { queries[i] = 0; continue; } + if (i == duplicate_at && i) { queries[i] = queries[i - 1]; continue; } + assert(next_query < 1024); + queries[i] = next_query++; + } + zero_at = duplicate_at = -1; +} +static void glCreateQueries(GLenum target, GLsizei count, GLuint *queries) { + int i; + assert(target == VISIBILITY_QUERY); + glGenQueries(count, queries); + for (i = 0; i < count; i++) + if (queries[i]) gpu[queries[i]].object = !fail_object; + if (fail_create) gpu_error = 0x505; +} +static BOOL glIsQuery(GLuint query) { return query < 1024 && gpu[query].object; } +static void glBeginQuery(GLenum target, GLuint query) { + assert(target == VISIBILITY_QUERY && !active && query && query < 1024); + assert(gpu[query].object && !gpu[query].pending); + gpu[query].available = gpu[query].flushed = gpu[query].checked = FALSE; + active = query; +} +static void glEndQuery(GLenum target) { + assert(target == VISIBILITY_QUERY && active); + gpu[active].samples = next_samples; + gpu[active].pending = TRUE; + active = 0; +} +static void glGetQueryObjectuiv(GLuint query, GLenum pname, GLuint *value) { + assert(query && gpu[query].object && gpu[query].pending && !query_buffer); + if (pname == GL_QUERY_RESULT_AVAILABLE) { + polls++; + *value = gpu[query].available; + gpu[query].checked = *value; + if (availability_error) gpu_error = 0x502; + } else { + assert(pname == GL_QUERY_RESULT && gpu[query].available && gpu[query].checked); + reads++; + if (direct_error) { gpu_error = 0x502; return; } + *value = gpu[query].samples; + gpu[query].pending = FALSE; + } +} +static void glFlush(void) { + unsigned i; + flushes++; + for (i = 1; i < next_query; i++) + if (gpu[i].pending) gpu[i].flushed = TRUE; +} +static void ready(unsigned batch, unsigned test) { + GLuint query = device.visibility_batches[batch].queries[test]; + assert(gpu[query].pending && gpu[query].flushed); + gpu[query].available = TRUE; +} +static void finish_gpu(void) { + unsigned i; + for (i = 1; i < next_query; i++) if (gpu[i].pending) { + assert(gpu[i].flushed); + gpu[i].available = TRUE; + } +} +static void glBindBuffer(GLenum target, GLuint buffer) { + assert(target == GL_QUERY_BUFFER); + if (!buffer && unbind_error) { gpu_error = 0x502; return; } + query_buffer = buffer; +} +static void glGetIntegerv(GLenum pname, GLint *value) { + assert(pname == GL_QUERY_BUFFER_BINDING); + if (binding_error) { gpu_error = 0x502; return; } + *value = query_buffer; +} +static const char *vendor = "ATI Technologies Inc."; +static GLuint mapped[VISIBILITY_BATCH_COUNT * VISIBILITY_TEST_SLOTS]; +static GLintptr offsets[1024]; +static unsigned copy_serial[1024]; +static unsigned buffer_calls, fence_count, deletes, copies; +static struct fake_fence fences[128]; +static BOOL map_null, map_error, copy_error, fence_null, wait_error; +static const char *glGetString(GLenum name) { assert(name == GL_VENDOR); return vendor; } +static void glGenBuffers(GLsizei n, GLuint *buffer) { + assert(n == 1 && strcmp(vendor, "ATI Technologies Inc.")); + buffer_calls++; *buffer = 123; +} +static void glBufferStorage(GLenum target, GLsizeiptr size, void *data, GLbitfield flags) { + assert(target == GL_QUERY_BUFFER && query_buffer == 123 && size == sizeof(mapped)); + assert(!data && flags == 15); buffer_calls++; +} +static void *glMapBufferRange(GLenum target, GLintptr offset, GLsizeiptr size, GLbitfield flags) { + assert(target == GL_QUERY_BUFFER && !offset && size == sizeof(mapped) && flags == 15); + buffer_calls++; if (map_error) gpu_error = 0x502; + return map_null ? NULL : mapped; +} +static void glDeleteBuffers(GLsizei n, GLuint *buffer) { assert(n == 1); buffer_calls++; } +static void glGetQueryBufferObjectuiv(GLuint query, GLuint buffer, GLenum pname, GLintptr offset) { + assert(buffer == 123 && pname == GL_QUERY_RESULT && gpu[query].pending); + assert(offset >= 0 && offset < sizeof(mapped) && !(offset % sizeof(GLuint))); + offsets[query] = offset; copy_serial[query] = ++copies; + if (copy_error) gpu_error = 0x502; +} +static GLsync glFenceSync(GLenum condition, GLbitfield flags) { + assert(condition == GL_SYNC_GPU_COMMANDS_COMPLETE && !flags && fence_count < 128); + if (fence_null) return NULL; + fences[fence_count].copies = copies; + return &fences[fence_count++]; +} +static GLenum glClientWaitSync(GLsync fence, GLbitfield flags, ULONGLONG timeout) { + assert(fence && flags == GL_SYNC_FLUSH_COMMANDS_BIT && !timeout); /* Submit without waiting. */ + return wait_error ? GL_WAIT_FAILED : !fence->complete ? GL_TIMEOUT_EXPIRED : + (fence_count & 1) ? GL_ALREADY_SIGNALED : GL_CONDITION_SATISFIED; +} +static void glDeleteSync(GLsync fence) { assert(fence); deletes++; } +static void complete_buffer(unsigned b) { + struct visibility_batch *batch = &device.visibility_batches[b]; + unsigned i; + assert(batch->sealed && !batch->failed && batch->fence); + for (i = 0; i < batch->count; i++) { + GLuint q = batch->queries[i]; + assert(gpu[q].pending && gpu[q].flushed); + assert(copy_serial[q] && copy_serial[q] <= batch->fence->copies); + mapped[offsets[q] / sizeof(GLuint)] = gpu[q].samples; + gpu[q].pending = FALSE; + } + batch->fence->complete = TRUE; +} +""" + main = r""" +#define CHECK(x) do { if (!(x)) { fprintf(stderr, "%d: %s\n", __LINE__, #x); return 1; } } while (0) +static void submit(unsigned slot, unsigned samples) { + next_samples = samples; + D3DDevice_BeginVisibilityTest(); + D3DDevice_EndVisibilityTest(slot); +} +/* Swap submits the queued work between send and read. */ +static void present(void) { visibility_send_batch(); glFlush(); visibility_read_batch(); device.frame++; } +static UINT result(unsigned slot) { + UINT value = 999; + unsigned before = reads + polls; + D3DDevice_GetVisibilityTestResult(slot, &value, NULL); + assert(before == reads + polls); /* Game retrieval never polls or waits. */ + return value; +} +int main(void) { + UINT value = 99; + ULONGLONG stamp = 99; + unsigned i, before, batch, partial; + D3DDevice_GetVisibilityTestResult(0, &value, &stamp); + CHECK(value == 0 && stamp == 0 && !reads && !polls); + D3DDevice_GetVisibilityTestResult(0, NULL, NULL); + CHECK(visibility_queries_initialize()); + visibility_results_initialize(); + device.gl_ready = TRUE; + query_buffer = 91; /* Save/clear/restore an unrelated buffer binding. */ + submit(0, 240); submit(1, 0); + CHECK(result(0) == 0); + present(); + CHECK(!reads && !polls && flushes == 1 && query_buffer == 91); + target_samples = 1; + submit(0, 120); present(); + submit(0, 180); present(); + /* Delay beyond the whole ring without allowing query reuse. */ + for (i = 0; i < 12; i++) { + submit(0, 999); present(); + CHECK(result(0) == 0 && query_buffer == 91); + } + CHECK(!reads && device.visibility_stats.dropped == 12 && flushes >= 3); + ready(2, 0); /* Later availability cannot publish ahead of older work. */ + present(); CHECK(!reads && result(0) == 0); + ready(0, 0); present(); + CHECK(result(0) == 10 && reads == 1); /* Original scale was 24, now 6. */ + CHECK(device.visibility_batches[0].sealed && device.visibility_batches[0].read == 1); + CHECK(device.visibility_stats.completed == 0); + ready(0, 1); present(); + CHECK(result(0) == 10 && result(1) == 0 && device.visibility_stats.completed == 1); + /* Released batch records again while other batches remain pending. */ + submit(0, 240); present(); + ready(1, 0); present(); + CHECK(result(0) == 30 && device.visibility_stats.completed == 3); + ready(0, 0); present(); CHECK(result(0) == 40); + /* Real completed zero replaces the prior nonzero count, only when ready. */ + submit(0, 0); present(); + for (i = 0; i < 6; i++) { present(); CHECK(result(0) == 40); } + finish_gpu(); present(); CHECK(result(0) == 0); + /* Repeated slots, per-test scales, partial readiness and ring wrap. */ + for (i = 0; i < 20; i++) { + batch = device.visibility_batch; + target_samples = 4; submit(0, 240); + target_samples = 1; submit(0, 120); submit(7, 60); + present(); ready(batch, 0); present(); CHECK(result(0) == 10); + partial = reads; + present(); CHECK(reads == partial && result(0) == 10); + finish_gpu(); present(); CHECK(result(0) == 20 && result(7) == 10); + } + before = reads; + for (i = 0; i < VISIBILITY_TEST_SLOTS + 2; i++) submit(i, 6 * (i + 1)); + present(); finish_gpu(); present(); + CHECK(reads == before + VISIBILITY_TEST_SLOTS && result(0) == 1 && result(7) == 8); + /* GL errors cannot publish initialized zero or recycle uncertain queries. */ + batch = device.visibility_batch; + submit(0, 600); present(); finish_gpu(); + direct_error = TRUE; present(); direct_error = FALSE; + CHECK(device.visibility_batches[batch].failed && result(0) == 1); + batch = device.visibility_batch; + submit(0, 1200); present(); finish_gpu(); before = reads; + availability_error = TRUE; present(); availability_error = FALSE; + CHECK(device.visibility_batches[batch].failed && result(0) == 1 && reads == before); + CHECK(device.visibility_stats.failures == 2 && query_buffer == 91); + for (i = 0; i < 5; i++) { + submit(0, 180); present(); finish_gpu(); present(); CHECK(result(0) == 30); + } + /* Binding errors preserve pending results for a subsequent safe read. */ + submit(0, 240); present(); finish_gpu(); before = reads; + binding_error = TRUE; present(); binding_error = FALSE; + CHECK(reads == before && result(0) == 30 && query_buffer == 91); + unbind_error = TRUE; present(); unbind_error = FALSE; + CHECK(reads == before && result(0) == 30 && query_buffer == 91); + present(); CHECK(result(0) == 40); + /* All batches quarantined: retain the cache and stay nonblocking. */ + submit(0, 600); present(); finish_gpu(); + direct_error = TRUE; present(); direct_error = FALSE; + before = reads; + for (i = 0; i < 10; i++) { submit(0, 900); present(); } + CHECK(reads == before && result(0) == 40 && device.visibility_stats.failures == 5); + /* Reject every kind of invalid pool before publishing any objects. */ + memset(&device, 0, sizeof(device)); + zero_at = 0; CHECK(!visibility_queries_initialize()); + for (i = 0; i < VISIBILITY_BATCH_COUNT; i++) { + duplicate_at = VISIBILITY_TEST_SLOTS * i + 1; + CHECK(!visibility_queries_initialize() && !device.visibility_batches[i].queries[0]); + } + fail_object = TRUE; CHECK(!visibility_queries_initialize()); + fail_object = FALSE; fail_create = TRUE; CHECK(!visibility_queries_initialize()); + fail_create = FALSE; fail_all = TRUE; CHECK(!visibility_queries_initialize()); + for (i = 0; i < VISIBILITY_BATCH_COUNT; i++) CHECK(!device.visibility_batches[i].queries[0]); + CHECK(!buffer_calls && !copies && !fence_count); /* AMD never uses mapped delivery. */ + return 0; +} +""" + if buffered: + main = main[:main.index("int main(void)")] + r""" +int main(void) { + unsigned i, b, before; + /* Only the proprietary AMD driver uses direct CPU delivery. */ + visibility_results_initialize(); CHECK(!buffer_calls && !device.visibility_mapped); + vendor = "NVIDIA Corporation"; + map_null = TRUE; visibility_results_initialize(); + CHECK(!device.visibility_mapped && !device.visibility_buffer); + CHECK(visibility_queries_initialize()); device.gl_ready = TRUE; + submit(0, 240); present(); ready(0, 0); present(); + CHECK(result(0) == 10 && reads == 1 && !copies && !fence_count); + memset(&device, 0, sizeof(device)); reads = polls = flushes = 0; + map_null = FALSE; map_error = TRUE; visibility_results_initialize(); + CHECK(!device.visibility_mapped && !device.visibility_buffer); + map_error = FALSE; + CHECK(visibility_queries_initialize()); visibility_results_initialize(); + CHECK(device.visibility_mapped == mapped && !query_buffer); + device.gl_ready = TRUE; + query_buffer = 91; + submit(0, 240); submit(1, 0); present(); + CHECK(copies == 2 && !reads && !polls && result(0) == 0 && query_buffer == 91); + target_samples = 1; + submit(0, 120); present(); submit(0, 180); present(); + for (i = 0; i < 12; i++) { submit(0, 999); present(); CHECK(result(0) == 0); } + CHECK(device.visibility_stats.dropped == 12 && flushes >= 3); + complete_buffer(2); present(); CHECK(result(0) == 0); + complete_buffer(0); present(); CHECK(result(0) == 10 && result(1) == 0); + CHECK(device.visibility_stats.completed == 1); + submit(0, 240); present(); complete_buffer(1); present(); + CHECK(result(0) == 30 && device.visibility_stats.completed == 3); + complete_buffer(0); present(); CHECK(result(0) == 40); + b = device.visibility_batch; submit(0, 0); present(); + for (i = 0; i < 6; i++) { present(); CHECK(result(0) == 40); } + complete_buffer(b); present(); CHECK(result(0) == 0); + for (i = 0; i < 20; i++) { + b = device.visibility_batch; + target_samples = 4; submit(0, 240); + target_samples = 1; submit(0, 120); submit(7, 60); present(); + /* Query completion alone is insufficient: wait for buffer copies too. */ + ready(b, 0); present(); CHECK(device.visibility_batches[b].sealed); + complete_buffer(b); present(); CHECK(result(0) == 20 && result(7) == 10); + } + b = device.visibility_batch; before = copies; + for (i = 0; i < VISIBILITY_TEST_SLOTS + 2; i++) submit(i, 6 * (i + 1)); + present(); complete_buffer(b); present(); + CHECK(copies == before + VISIBILITY_TEST_SLOTS && result(0) == 1 && result(7) == 8); + b = device.visibility_batch; submit(0, 600); + device.visibility_logging = TRUE; + copy_error = TRUE; present(); copy_error = FALSE; + CHECK(device.visibility_batches[b].failed && result(0) == 1); + CHECK(!device.visibility_mapped); + /* Re-enable mapped delivery only to inject the next independent fault. */ + device.visibility_mapped = mapped; + b = device.visibility_batch; submit(0, 1200); present(); + complete_buffer(b); /* A failed wait must reject even plausible copied data. */ + wait_error = TRUE; present(); wait_error = FALSE; + CHECK(device.visibility_batches[b].failed && result(0) == 1); + CHECK(!device.visibility_mapped); device.visibility_mapped = mapped; + b = device.visibility_batch; submit(0, 240); present(); complete_buffer(b); present(); + CHECK(result(0) == 40); + b = device.visibility_batch; submit(0, 600); + fence_null = TRUE; present(); fence_null = FALSE; + CHECK(device.visibility_batches[b].failed && result(0) == 40); + before = copies; + for (i = 0; i < 10; i++) { submit(0, 900); present(); } + CHECK(copies == before && result(0) == 40); + CHECK(!reads && !polls && deletes == fence_count && query_buffer == 91); + return 0; +} +""" + path = tmp_path / "visibility.c" + path.write_text(prefix.replace("/* BATCH_TYPE */", batch_type) + code + read_code + main, encoding="utf-8") + binary = tmp_path / ("visibility.exe" if os.name == "nt" else "visibility") + target = ["--target=i686-pc-windows-msvc", "-fuse-ld=lld"] if os.name == "nt" else ["-m32"] + build = subprocess.run([compiler, *target, "-std=gnu89", str(path), "-o", str(binary)], + capture_output=True, text=True) + assert build.returncode == 0, build.stderr + run = subprocess.run([str(binary)], capture_output=True, text=True) + if negative_control and negative_control != "buffered": + assert run.returncode != 0, "negative control unexpectedly passed" + else: + assert run.returncode == 0, run.stderr diff --git a/tools/test_web_build.py b/tools/test_web_build.py index 96030018f0..cf31d8647d 100644 --- a/tools/test_web_build.py +++ b/tools/test_web_build.py @@ -13,6 +13,7 @@ import json import re import shutil +import shlex import subprocess import sys from pathlib import Path @@ -40,6 +41,7 @@ def graph(release=False, emcc="/opt/emsdk/upstream/emscripten/emcc"): sln = SimpleNamespace(build_dir=Path("build"), web_emcc=emcc, port_release=release, port_profile=False, compiler_launcher=None) web_build.generate_web_build(ninja_syntax.Writer(out), sln) + # Path emits native separators; these graph assertions use portable paths. return re.sub(r" \$\n +", " ", out.getvalue()).replace("\\", "/") @@ -55,6 +57,19 @@ def link_flags(text): return re.search(r"^build build/web/site/halo\.js.*?\n ldflags = ([^\n]*)", text, re.M | re.S).group(1) +def test_link_response_paths_survive_emscripten_parsing(): + out = io.StringIO() + sln = SimpleNamespace(build_dir=Path("build directory"), web_emcc="emcc", + port_release=True, port_profile=False, compiler_launcher=None) + web_build.generate_web_build(ninja_syntax.Writer(out), sln) + text = re.sub(r" \$\n +", " ", out.getvalue()) + response = re.search(r"^ rspfile_content = (.*)$", text, re.M).group(1) + paths = shlex.split(response) + assert len(paths) > 100 + assert all(path.startswith("build directory/web/obj/") and "\\" not in path for path in paths) + assert "build directory/web/obj/source/ai/action_alert.o" in paths + + def test_without_emscripten_the_graph_says_so(): import tools.web_build as module @@ -68,6 +83,15 @@ def test_without_emscripten_the_graph_says_so(): assert "\nbuild web:" not in text +def test_sdk_discovery_uses_native_launcher(tmp_path, monkeypatch): + launcher = tmp_path / "upstream/emscripten" / ("emcc.exe" if sys.platform == "win32" else "emcc") + launcher.parent.mkdir(parents=True) + launcher.write_text("SDK launcher", encoding="ascii") + monkeypatch.setenv("EMSDK", str(tmp_path)) + monkeypatch.setattr(web_build.shutil, "which", lambda name: None) + assert web_build.find_emcc(SimpleNamespace()) == str(launcher) + + def test_the_game_is_compiled_as_the_web_port(): text = graph() flags = compile_flags(text, "source/main/main.c") @@ -100,6 +124,7 @@ def test_the_link_makes_the_memory_the_window_needs(): flags = link_flags(graph()).split() for flag in ("-sPROXY_TO_PTHREAD=1", "-sOFFSCREENCANVASES_TO_PTHREAD=#canvas", "-sMIN_WEBGL_VERSION=2", "-sMAX_WEBGL_VERSION=2", "-sWASMFS=1", "-lopfs.js", "-sALLOW_MEMORY_GROWTH=0", + "-sABORTING_MALLOC=0", "-Wl,--fatal-warnings", "-sASSERTIONS=1", "--profiling-funcs"): assert flag in flags, flag assert f"-sINITIAL_MEMORY={0x88000000}" in flags @@ -108,6 +133,59 @@ def test_the_link_makes_the_memory_the_window_needs(): assert "-sASSERTIONS=0" in link_flags(release).split() +def test_web_staging_uses_portable_file_operations(): + text = graph() + assert "tools/web_build_support.py sdl --emcc" in text + assert "tools/web_build_support.py copy $in $out" in text + assert "rm -f" not in text and "cp $in" not in text + + +@pytest.mark.parametrize("fail", [False, True]) +def test_sdl_bootstrap_preserves_arguments_and_cleans_failed_compile(tmp_path, fail): + from tools import web_build_support + + sdk = tmp_path / "SDK with spaces" + sdk.mkdir() + cache = tmp_path / "cache with spaces" + license_source = cache / "ports/halo_sdl3/SDL-release-test/LICENSE.txt" + license_source.parent.mkdir(parents=True) + license_source.write_text("SDL licence", encoding="ascii") + trace = sdk / "arguments.json" + compiler = sdk / "emcc.py" + compiler.write_text( + "import json, pathlib, sys\n" + f"pathlib.Path({str(trace)!r}).write_text(json.dumps(sys.argv[1:]))\n" + "source = pathlib.Path(sys.argv[sys.argv.index('-c') + 1])\n" + "assert source.read_text() == '#include \\n'\n" + "pathlib.Path(sys.argv[sys.argv.index('-o') + 1]).write_bytes(b'object')\n" + f"sys.exit({1 if fail else 0})\n", encoding="utf-8") + (sdk / "em-config.py").write_text(f"print({str(cache)!r})\n", encoding="utf-8") + stamp = tmp_path / "output folder/sdl.stamp" + license_output = stamp.parent / "SDL-LICENSE.txt" + port = "port with spaces/halo_sdl3.py" + if fail: + with pytest.raises(subprocess.CalledProcessError): + web_build_support.sdl(compiler, port, stamp, license_output, "release-test") + else: + web_build_support.sdl(compiler, port, stamp, license_output, "release-test") + assert json.loads(trace.read_text())[0] == f"--use-port={port}" + assert stamp.exists() is not fail + assert license_output.exists() is not fail + if not fail: + assert license_output.read_text() == "SDL licence" + assert not Path(str(stamp) + ".c").exists() + assert not Path(str(stamp) + ".o").exists() + + +def test_web_copy_creates_destination_directories(tmp_path): + source = tmp_path / "source file" + destination = tmp_path / "nested folder/file" + source.write_bytes(b"\x00\xffweb asset") + subprocess.run([sys.executable, str(ROOT / "tools/web_build_support.py"), "copy", str(source), + str(destination)], check=True) + assert destination.read_bytes() == source.read_bytes() + + def test_the_link_exports_what_the_page_calls(): """every function the page's scripts call on the game's module (game._x, module._x) is exported: KEEPALIVE alone leaves it off the module, and the @@ -184,6 +262,7 @@ def test_licenses_txt_has_every_notice(): @pytest.mark.skipif(not (shutil.which("cc") or shutil.which("clang")), reason="no C compiler") +@pytest.mark.skipif(sys.platform == "win32", reason="native socket harness requires POSIX pthreads") def test_the_sockets_inside_the_page(tmp_path): compiler = shutil.which("cc") or shutil.which("clang") program = tmp_path / "web_net_test" diff --git a/tools/test_web_map_memory.py b/tools/test_web_map_memory.py new file mode 100644 index 0000000000..0c51819dec --- /dev/null +++ b/tools/test_web_map_memory.py @@ -0,0 +1,34 @@ +"""Run the production map-window code with the real Wasm allocator and threads.""" +import os +from pathlib import Path +import shutil +import subprocess + +import pytest + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.mark.parametrize("memory", [0x01000000, 0x88000000]) +def test_wasm_map_memory_and_heap_exhaustion(tmp_path, memory): + emcc = os.environ.get("WEB_EMCC") or shutil.which("emcc") + node = os.environ.get("EMSDK_NODE") or shutil.which("node") + if not emcc or not node: + pytest.skip("requires Emscripten and Node for the actual Wasm allocator") + output = tmp_path / "map_memory.js" + subprocess.run([ + emcc, str(ROOT / "port/web/tests/map_memory_test.c"), + str(ROOT / "port/web/src/web_memory.c"), + "-I" + str(ROOT / "port/web/src"), + "-I" + str(ROOT / "port/linux/src"), + "-DHALO_WEB=1", "-std=gnu89", "-O2", "-pthread", + "-sPROXY_TO_PTHREAD=1", "-sPTHREAD_POOL_SIZE=5", + "-sALLOW_MEMORY_GROWTH=0", "-sABORTING_MALLOC=0", + "-sEXIT_RUNTIME=1", "-sENVIRONMENT=node", + f"-sINITIAL_MEMORY={memory}", "-o", str(output), + ], check=True, cwd=ROOT, capture_output=True, text=True, timeout=120) + result = subprocess.run([node, str(output)], cwd=ROOT, capture_output=True, + text=True, timeout=90) + assert result.returncode == 0, result.stdout + result.stderr + expected = "map windows preserved" if memory == 0x88000000 else "insufficient map-window memory refused" + assert expected in result.stdout, result.stdout + result.stderr diff --git a/tools/test_windows_mcc_startup.py b/tools/test_windows_mcc_startup.py new file mode 100644 index 0000000000..cb3cb4f905 --- /dev/null +++ b/tools/test_windows_mcc_startup.py @@ -0,0 +1,171 @@ +"""Windows loader ordering and deferred MCC reservation diagnostics, without maps.""" +import io +import re +import shutil +import subprocess +import sys +from pathlib import Path +from types import SimpleNamespace + +import pytest +from harness import function +from test_mcc_memory import implementation + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +from tools import ninja_syntax, windows_build + + +def link_flags(monkeypatch, release): + output = io.StringIO() + settings = SimpleNamespace(build_dir=Path("build"), compiler_launcher=None, + port_release=release, port_profile=False, + port_lto="off", port_pgo="off") + with monkeypatch.context() as setup: + setup.chdir(ROOT) + setup.setattr(windows_build.sys, "platform", "win32") + setup.setattr(windows_build, "fetch_sdl", lambda: None) + setup.setattr(windows_build, "inline_export_wrapper", lambda source: source) + windows_build.generate_windows_build(ninja_syntax.Writer(output), settings) + graph = re.sub(r" \$\n *", " ", output.getvalue()) + return re.search(r"\n ldflags = ([^\n]+)", graph).group(1).split() + + +@pytest.mark.parametrize("release", [False, True]) +def test_windows_graph_delays_sdl_without_disabling_aslr(monkeypatch, release): + flags = link_flags(monkeypatch, release) + assert "-Wl,/DELAYLOAD:SDL3.dll" in flags + assert "-ldelayimp" in flags + assert not any("dynamicbase:no" in flag.lower() for flag in flags) + + +@pytest.mark.skipif(sys.platform != "win32", reason="Windows DLL loader") +@pytest.mark.parametrize("mode", ["delayed", "eager", "late-reservation"]) +def test_reservation_precedes_the_first_sdl_call(tmp_path, monkeypatch, mode): + compiler = shutil.which("clang") + if not compiler: + pytest.skip("clang required") + + def build(arguments): + result = subprocess.run([compiler, "--target=i686-pc-windows-msvc", "-fuse-ld=lld", + *map(str, arguments)], capture_output=True, text=True) + assert result.returncode == 0, result.stderr + + # The disposable DLL tries to occupy the MCC window when it is loaded. + # A preferred image base is insufficient: Windows may relocate an image + # even with /DYNAMICBASE:NO. Keep ASLR and claim a known owned allocation. + dll_source = tmp_path / "sdl.c" + dll_source.write_text(r''' +#include +static unsigned char *reservation; +BOOL WINAPI DllMain(HINSTANCE instance, DWORD reason, LPVOID reserved) { + (void)instance;(void)reserved; + if(reason==DLL_PROCESS_ATTACH) { + reservation=VirtualAlloc((void *)0x50000000u,0x10000u, + MEM_RESERVE|MEM_COMMIT,PAGE_READWRITE); + if(reservation) reservation[0]=42; + } else if(reason==DLL_PROCESS_DETACH && reservation) { + VirtualFree(reservation,0,MEM_RELEASE); + } + return TRUE; +} +__declspec(dllexport) int SDL_GetVersion(void) { return 3004016; } +__declspec(dllexport) unsigned char *SDL_TestReservation(void) { return reservation; } +''') + library = tmp_path / "SDL3.lib" + build(["-shared", dll_source, "-o", tmp_path / "SDL3.dll", + f"-Wl,/IMPLIB:{library}"]) + + posix = (ROOT / "port/windows/src/win32_posix.c").read_text() + memory = implementation() + if mode == "late-reservation": + memory = memory.replace("constructor(101)", "constructor(103)") + source = r''' +#include +#include +#include +#include +#include +#include +#include +#include +#include +#define HALO_WINDOWS 1 +static int log_calls; +static void platform_log(const char *format, ...) { + va_list args; + log_calls++; + va_start(args,format);vfprintf(stderr,format,args);va_end(args); + fputc('\n',stderr); +} +''' + '#include "' + (ROOT / "port/windows/include/posix/sys/mman.h").as_posix() + '"\n' + source += "\n".join(function(posix, name) for name in + ["errno_from_windows_error", "windows_protection", "address_reserved", "mmap", "munmap"]) + source += memory + r''' +__declspec(dllimport) int SDL_GetVersion(void); +__declspec(dllimport) unsigned char *SDL_TestReservation(void); +static int held_before_sdl, version, loaded_before_call; +/* Same priority as CE's config read; the real settings path uses SDL. */ +__attribute__((constructor(102))) static void read_settings(void) { + MEMORY_BASIC_INFORMATION info; + loaded_before_call=GetModuleHandleA("SDL3.dll")!=NULL; + held_before_sdl=mcc_window==(void *)(uintptr_t)0x50000000u && + VirtualQuery(mcc_window,&info,sizeof(info)) && info.State==MEM_RESERVE; + version=SDL_GetVersion(); +} +int crash_reporter_process(void) {return 0;} +/* Exercise the actual no-console log setup even under pytest's pipes. */ +#define _fileno(stream) (-2) +''' + function(posix, "windows_startup") + r''' +#define CHECK(c) do{if(!(c)){printf("line %d: %s (window=%p, SDL=%p, held=%d)\n",\ + __LINE__,#c,mcc_window,module,held_before_sdl);return __LINE__;}}while(0) +int main(void) { + MEMORY_BASIC_INFORMATION info; + unsigned char *p; + HMODULE module=GetModuleHandleA("SDL3.dll"); + CHECK(version==3004016 && module); + CHECK(loaded_before_call==EXPECT_EAGER); + CHECK(log_calls==0); + errno=EDOM; + windows_startup(); +#if EXPECT_SUCCESS + CHECK(held_before_sdl && !loaded_before_call); + CHECK(!SDL_TestReservation()); + CHECK((uintptr_t)module<0x50000000u || (uintptr_t)module>=0x54000000u); + CHECK(log_calls==0); + p=mcc_memory_reserve(0x50000000u,0x4000000u);CHECK(p); + p[0]=42;p[0x3ffffff]=43; + mcc_memory_release(p,0x4000000u); + CHECK(mcc_memory_reserve(0x50000000u,0x4000000u)==p); + CHECK(p[0]==0 && p[0x3ffffff]==0); + mcc_memory_release(p,0x4000000u); +#else + CHECK(!held_before_sdl && !mcc_window); + p=SDL_TestReservation();CHECK((uintptr_t)p==0x50000000u); + CHECK(VirtualQuery(p,&info,sizeof(info)) && info.Type==MEM_PRIVATE && info.State==MEM_COMMIT); + CHECK(log_calls==1); + mcc_memory_log_startup();CHECK(log_calls==1); + CHECK(!mcc_memory_reserve(0x50000000u,0x4000000u)); + CHECK(p[0]==42 && SDL_GetVersion()==3004016); /* conflict was not overwritten */ +#endif + return 0; +} +''' + probe = tmp_path / "startup.c" + probe.write_text(source) + flags = link_flags(monkeypatch, True) + if mode == "eager": + flags.remove("-Wl,/DELAYLOAD:SDL3.dll") + binary = tmp_path / "startup.exe" + build([*flags, "-std=gnu89", "-D_CRT_SECURE_NO_WARNINGS", + f"-DEXPECT_SUCCESS={int(mode == 'delayed')}", f"-DEXPECT_EAGER={int(mode == 'eager')}", + probe, library, "-lwinmm", "-o", binary]) + result = subprocess.run([str(binary)], capture_output=True, text=True, timeout=10, + creationflags=subprocess.CREATE_NO_WINDOW) + assert result.returncode == 0, (mode, result.returncode, result.stdout, result.stderr) + log = (tmp_path / "halo.log").read_text() + if mode == "delayed": + assert not log + else: + assert "early reservation at 50000000 (64 MiB) failed (Invalid argument)" in log + assert "will retry at map load" in log diff --git a/tools/test_windows_memory_watch.py b/tools/test_windows_memory_watch.py new file mode 100644 index 0000000000..621946a33a --- /dev/null +++ b/tools/test_windows_memory_watch.py @@ -0,0 +1,70 @@ +"""Exercise the real Windows page watch, including cross-reservation fallback.""" +import os +from pathlib import Path +import shutil +import subprocess + +import pytest + +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.mark.skipif(os.name != 'nt', reason='Windows virtual memory API') +def test_batched_page_protection(tmp_path): + compiler = shutil.which('clang') + if not compiler: + pytest.skip('clang required') + source = r''' +#include +#include +#include +static unsigned protection_calls; +static BOOL counted_protect(void *p, SIZE_T bytes, DWORD flags, DWORD *previous) { + protection_calls++; + return VirtualProtect(p, bytes, flags, previous); +} +void platform_log(char const *format, ...) { (void)format; } +#define VirtualProtect counted_protect +''' + source += (ROOT/'port/windows/src/win32_memory_watch.c').read_text() + source += r''' +int main(void) { + unsigned long base=PLATFORM_CONTIGUOUS_BASE, before, calls; + unsigned i; + volatile unsigned char *bytes=(void *)base; + assert(VirtualAlloc((void *)base,0x10000,MEM_RESERVE|MEM_COMMIT,PAGE_READWRITE)==(void *)base); + assert(VirtualAlloc((void *)(base+0x10000),0x10000,MEM_RESERVE|MEM_COMMIT,PAGE_READWRITE)==(void *)(base+0x10000)); + memory_watch_initialize();assert(watch_active); + memory_watch_protect(base+3,0x8000-3);assert(protection_calls==1); + calls=protection_calls;memory_watch_protect(base,0x8000);assert(protection_calls==calls); + for(i=0;i<8;i++) { + before=memory_watch_generation(base+i*0x1000,0x1000); + bytes[i*0x1000]=7; + assert(memory_watch_generation(base+i*0x1000,0x1000)>before); + } + calls=protection_calls; + memory_watch_protect(base,0x20000); + assert(protection_calls==calls+33); /* combined request plus 32 page fallback */ + for(i=0;i<32;i++) { + before=memory_watch_generation(base+i*0x1000,0x1000); + bytes[i*0x1000]=8; + assert(memory_watch_generation(base+i*0x1000,0x1000)>before); + } + memory_watch_protect(base,0x10000); + before=memory_watch_serial();memory_watch_prepare_write((void *)(base+0x2000),0x2000); + assert(memory_watch_generation(base+0x2000,0x2000)>before); + calls=protection_calls;memory_watch_protect(base,0x10000);assert(protection_calls==calls+1); + before=memory_watch_serial();memory_watch_forget((void *)base,0x20000); + assert(memory_watch_generation(base,0x20000)>before); + VirtualFree((void *)base,0,MEM_RELEASE);VirtualFree((void *)(base+0x10000),0,MEM_RELEASE); + return 0; +} +''' + path = tmp_path/'watch.c' + path.write_text(source) + binary = tmp_path/'watch.exe' + result = subprocess.run([compiler, '--target=i686-pc-windows-msvc', '-fuse-ld=lld', + '-std=gnu89', str(path), '-o', str(binary), + '-Wl,/largeaddressaware'], capture_output=True, text=True) + assert result.returncode == 0, result.stderr + subprocess.run([str(binary)], check=True) diff --git a/tools/tests/MccPackageImporterTest.java b/tools/tests/MccPackageImporterTest.java new file mode 100644 index 0000000000..290b17c51f --- /dev/null +++ b/tools/tests/MccPackageImporterTest.java @@ -0,0 +1,162 @@ +package com.halo.decomp; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Arrays; +import java.util.Base64; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +public final class MccPackageImporterTest { + private static int checks; + interface Checked { void run() throws Exception; } + static void check(boolean value) { checks++; if (!value) throw new AssertionError("check " + checks); } + static void refuses(Checked action) throws Exception { + checks++; + try { action.run(); } catch (IOException expected) { return; } + throw new AssertionError("Expected refusal at " + checks); + } + static byte[] bytes(String text) { return text.getBytes(StandardCharsets.UTF_8); } + static byte[] map(int type) { + byte[] bytes = new byte[2088]; + ByteBuffer h = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN); + h.putInt(0, 0x68656164); h.putInt(4, 13); h.putInt(8, bytes.length); + h.putInt(16, 2048); h.putInt(20, 40); h.putShort(0x60, (short)type); h.putInt(0x7fc, 0x666f6f74); + return bytes; + } + static Map campaign() { + Map entries = new LinkedHashMap<>(); + entries.put("2915693904/ModInfo.json", bytes("{\"Engine\":\"Halo1\",\"Title\":{\"Neutral\":\"Example\"},\"ModIdentifier\":{\"HostedModIds\":{\"SteamWorkshopId\":2915693904}},\"GameModContents\":{\"HasCampaign\":true}}")); + entries.put("2915693904/CampaignInfo.json", bytes("{\"CampaignMaps\":[\"Campaign/Z10.json\",\"campaign/a10.json\"]}")); + entries.put("2915693904/campaign/z10.json", bytes("{\"ScenarioFile\":\"levels/test/z10\",\"CampaignMapKind\":\"Default\"}")); + entries.put("2915693904/campaign/a10.json", bytes("{\"ScenarioFile\":\"a10\",\"Images\":{\"Large\":\"Assets/Level Large.PNG\",\"Thumbnail\":\"Thumb.PNG\"}}")); + entries.put("2915693904/Assets/Level Large.PNG", preview()); + entries.put("2915693904/Thumb.PNG", preview()); + entries.put("2915693904/Maps/z10.map", map(0)); + entries.put("2915693904/Maps/a10.map", map(0)); + return entries; + } + static byte[] preview() { + // Generated one-pixel PNG; no game or Workshop artwork in the tests. + return Base64.getDecoder().decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGPgNgitAgAB5QELSSf/aQAAAABJRU5ErkJggg=="); + } + static MccPackageImporter.Source source(Map entries) { + return receiver -> { for (Map.Entry entry : entries.entrySet()) receiver.file(entry.getKey(), new ByteArrayInputStream(entry.getValue())); }; + } + static MccPackageImporter.Source zip(Map entries) throws IOException { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (ZipOutputStream zip = new ZipOutputStream(bytes)) { + for (Map.Entry entry : entries.entrySet()) { + zip.putNextEntry(new ZipEntry(entry.getKey())); zip.write(entry.getValue()); zip.closeEntry(); + } + } + return MccPackageImporter.zip(new ByteArrayInputStream(bytes.toByteArray())); + } + static void noStaging(Path root) throws IOException { + try (java.util.stream.Stream children = Files.list(root)) { check(children.noneMatch(p -> p.getFileName().toString().startsWith(".mcc-import-"))); } + } + public static void main(String[] args) throws Exception { + Path root = Files.createTempDirectory(Path.of(args[0]), "importer-"); + try { + Files.createDirectories(root.resolve("maps")); Files.writeString(root.resolve("maps/ui.map"), "Xbox stays"); + Files.createDirectories(root.resolve("custom_maps")); Files.writeString(root.resolve("custom_maps/example.map"), "CE stays"); + Files.createDirectories(root.resolve("saves")); Files.writeString(root.resolve("saves/savegame.bin"), "save stays"); + try (MccPackageImporter.Prepared prepared = MccPackageImporter.prepare(root.toFile(), source(campaign()), "", 0)) { + check(prepared.maps == 2 && prepared.destination.equals("2915693904")); + check(!prepared.exists(root.toFile())); + refuses(() -> MccPackageImporter.prepare(root.toFile(), source(campaign()), "Another", 0)); + prepared.install(root.toFile(), false); + } + Path installed = root.resolve("mcc_maps/2915693904"); + check(Files.readString(installed.resolve("workshop_id.txt")).startsWith("2915693904\nExample\n")); + check(Files.exists(installed.resolve("campaign/z10.json")) && Files.exists(installed.resolve("z10.map"))); + check(Arrays.equals(preview(), Files.readAllBytes(installed.resolve("assets/level large.png")))); + check(Arrays.equals(preview(), Files.readAllBytes(installed.resolve("thumb.png")))); + check(Files.readString(installed.resolve("campaign/a10.json")).contains("Assets/Level Large.PNG")); + noStaging(root); + try (MccPackageImporter.Prepared prepared = MccPackageImporter.prepare(root.toFile(), zip(campaign()), "Mobile copy", 0)) { + prepared.install(root.toFile(), false); + } + check(Files.exists(root.resolve("mcc_maps/Mobile copy/a10.map"))); + check(Arrays.equals(preview(), Files.readAllBytes(root.resolve("mcc_maps/Mobile copy/assets/level large.png")))); + check(Arrays.equals(preview(), Files.readAllBytes(root.resolve("mcc_maps/Mobile copy/thumb.png")))); + Files.writeString(installed.resolve("old-marker"), "previous"); + try (MccPackageImporter.Prepared prepared = MccPackageImporter.prepare(root.toFile(), source(campaign()), "", 0)) { + refuses(() -> prepared.install(root.toFile(), false)); + check(Files.exists(installed.resolve("old-marker"))); + prepared.install(root.toFile(), true); + } + check(!Files.exists(installed.resolve("old-marker"))); + // Cancel after preparation leaves installed content unchanged. + try (MccPackageImporter.Prepared prepared = MccPackageImporter.prepare(root.toFile(), source(campaign()), "", 0)) { check(prepared.exists(root.toFile())); } + noStaging(root); + // A failed publish restores the previous directory. + Files.writeString(installed.resolve("old-marker"), "previous"); + try (MccPackageImporter.Prepared prepared = MccPackageImporter.prepare(root.toFile(), source(campaign()), "", 0)) { + delete(prepared.content); + refuses(() -> prepared.install(root.toFile(), true)); + check(Files.readString(installed.resolve("old-marker")).equals("previous")); + } + noStaging(root); + // Recover an interrupted replacement before accepting another import. + try (MccPackageImporter.Prepared prepared = MccPackageImporter.prepare(root.toFile(), source(campaign()), "", 0)) { + Files.writeString(prepared.staging.resolve("destination"), prepared.destination); + Files.move(installed, prepared.staging.resolve("previous")); + } + check(!Files.exists(installed)); + try (MccPackageImporter.Prepared prepared = MccPackageImporter.prepare(root.toFile(), source(campaign()), "", 0)) { + check(prepared.exists(root.toFile())); + check(Files.readString(installed.resolve("old-marker")).equals("previous")); + } + noStaging(root); + for (String bad : new String[]{"../escape.map", "/escape.map", "C:/escape.map", "a/../escape.map", "a\\..\\escape.map", "a//file.map", "a/file.map:stream"}) { + Map input = campaign(); input.put(bad, map(0)); + refuses(() -> MccPackageImporter.prepare(root.toFile(), zip(input), "", 0)); noStaging(root); + } + for (String fault : new String[]{"duplicate", "missing", "type", "kind", "null-kind", "malformed", "oversized", "engine", "header", "duplicate-mission"}) { + Map input = campaign(); + if (fault.equals("duplicate")) input.put("2915693904/maps/A10.MAP", map(0)); + if (fault.equals("missing")) input.remove("2915693904/Maps/a10.map"); + if (fault.equals("type")) input.put("2915693904/Maps/a10.map", map(1)); + if (fault.equals("kind")) input.put("2915693904/campaign/a10.json", bytes("{\"ScenarioFile\":\"a10\",\"CampaignMapKind\":\"Hub\"}")); + if (fault.equals("null-kind")) input.put("2915693904/campaign/a10.json", bytes("{\"ScenarioFile\":\"a10\",\"CampaignMapKind\":null}")); + if (fault.equals("malformed")) input.put("2915693904/ModInfo.json", bytes("{broken}")); + if (fault.equals("oversized")) input.put("2915693904/ModInfo.json", new byte[262145]); + if (fault.equals("engine")) input.put("2915693904/ModInfo.json", bytes("{\"Engine\":\"Halo2\"}")); + if (fault.equals("header")) input.put("2915693904/Maps/a10.map", new byte[2088]); + if (fault.equals("duplicate-mission")) input.put("2915693904/campaign/a10.json", bytes("{\"ScenarioFile\":\"z10\"}")); + refuses(() -> MccPackageImporter.prepare(root.toFile(), source(input), "", 0)); noStaging(root); + } + refuses(() -> MccPackageImporter.prepare(root.toFile(), receiver -> { receiver.file("partial.map", new ByteArrayInputStream(map(0))); throw new IOException("provider disconnected"); }, "", 0)); + noStaging(root); + Map resources = new LinkedHashMap<>(); resources.put("bitmaps.map", new byte[32]); + try (MccPackageImporter.Prepared prepared = MccPackageImporter.prepare(root.toFile(), source(resources), "", 1)) { prepared.install(root.toFile(), false); } + check(Files.exists(root.resolve("mcc_maps/_shared/singleplayer/bitmaps.map"))); + refuses(() -> MccPackageImporter.prepare(root.toFile(), source(resources), "", 2)); + resources.put("sounds.map", new byte[32]); + try (MccPackageImporter.Prepared prepared = MccPackageImporter.prepare(root.toFile(), source(resources), "", 2)) { prepared.install(root.toFile(), false); } + check(Files.exists(root.resolve("mcc_maps/_shared/multiplayer/sounds.map"))); + check(Files.readString(root.resolve("maps/ui.map")).equals("Xbox stays")); + check(Files.readString(root.resolve("custom_maps/example.map")).equals("CE stays")); + check(Files.readString(root.resolve("saves/savegame.bin")).equals("save stays")); + for (String bad : new String[]{"{} trailing", "{\"x\":1,\"x\":2}", "[1,]", "[01]", "\"\\u0000\"", "[".repeat(18) + "0" + "]".repeat(18)}) refuses(() -> MccJson.parse(bad)); + Object largeId = MccJson.member(MccJson.parse("{\"id\":18446744073709551615}"), "id"); + check(((MccJson.Number)largeId).text.equals("18446744073709551615")); + noStaging(root); + System.out.println("MCC importer: " + checks + " checks passed"); + } finally { delete(root); } + } + static void delete(Path path) throws IOException { + if (!Files.exists(path)) return; + if (Files.isDirectory(path)) try (java.nio.file.DirectoryStream entries = Files.newDirectoryStream(path)) { for (Path entry : entries) delete(entry); } + Files.delete(path); + } +} diff --git a/tools/tests/TouchLayoutTest.java b/tools/tests/TouchLayoutTest.java index 939561b1cd..5b6d9cda2e 100644 --- a/tools/tests/TouchLayoutTest.java +++ b/tools/tests/TouchLayoutTest.java @@ -133,8 +133,12 @@ public static void main(String[] args) { reject(movedOptions.replaceAll("(?m)^options\\.x=.*", "options.x=5000")); sized.layout.resetDefaults(); check(!sized.layout.optionsMoved(), "Reset puts Options back in its place"); - String version3 = buttonsStill.replace("version=4", "version=3").replaceAll("(?m)^buttons-aim=.*\\R", ""); - check(TouchLayout.importConfiguration(version3).layout.buttonsAim, "Version 3 layouts' held buttons aim"); + String oldButtons = buttonsStill.replace("version=4", "version=3").replaceAll("(?m)^buttons-aim=.*\\R", ""); + check(TouchLayout.importConfiguration(oldButtons).layout.buttonsAim, "Version 3 layouts' held buttons aim"); + String upstreamLayout = movedOptions.replaceAll("(?m)^menu-fingers=.*\\R", ""); + TouchLayout upstream = TouchLayout.importConfiguration(upstreamLayout).layout; + check(upstream.menuFingers == 3 && upstream.optionsMoved() && upstream.buttonsAim, + "OpenCE version 4 layouts retain their controls and default to the three-finger gesture"); try { sized.layout.setOpacity(1.5f); throw new AssertionError("Out-of-range opacity was accepted"); @@ -161,7 +165,34 @@ public static void main(String[] args) { } fingers.setMinimumRadius(Float.NaN); check(fingers.radius(12) == 25, "An invalid minimum radius is none"); + check(!wide.optionsMoved() && wide.buttonsAim && wide.menuFingers == 3, + "New layouts preserve the toolbar position and held-button aiming"); + wide.moveOptions(600, 270); + wide.buttonsAim = false; + wide.menuFingers = 4; + String editorText = wide.exportConfiguration(2.25f); + TouchLayout editor = TouchLayout.importConfiguration(editorText).layout; + editor.bounds(1200, 540); + check(editor.optionsX() == 600 && editor.optionsY() == 270 && !editor.buttonsAim && editor.menuFingers == 4, + "Options placement and gesture settings must survive export/import across aspect ratios"); + editor.moveOptions(Float.NaN, 0); + check(editor.optionsX() == 600, "Invalid Options drag must leave the last position intact"); + editor.moveOptions(9999, -10); + check(editor.optionsX() == 1200 - editor.optionsRadius() && editor.optionsY() == editor.optionsRadius(), + "The full Options button must stay reachable at screen edges"); + reject(editorText.replace("menu-fingers=4", "menu-fingers=5")); + reject(editorText.replace("buttons-aim=false", "buttons-aim=maybe")); + reject(editorText.replace("options.x=480.0", "options.x=NaN")); + reject(editorText.replaceAll("(?m)^options.y=.*\\R", "")); + String version3 = editorText.replace("version=4", "version=3") + .replaceAll("(?m)^(options\\.[xy]|menu-fingers|buttons-aim)=.*\\R", ""); + TouchLayout migrated = TouchLayout.importConfiguration(version3).layout; + check(!migrated.optionsMoved() && migrated.buttonsAim && migrated.menuFingers == 3 + && migrated.gyroscopeEnabled && !migrated.rumbleEnabled, + "Version 3 migration must preserve gyro/rumble and use the original toolbar/aim defaults"); wide.resetDefaults(); + check(!wide.optionsMoved() && !wide.buttonsAim && wide.menuFingers == 4, + "Reset restores the Options position without discarding General preferences"); check(wide.size() == 18 && wide.shown(4) && wide.x(4) == 915*1200f/960, "Reset restores defaults on the current display and removes all copies"); check(wide.sizeScale(4) == 1f && !wide.rumbleEnabled && wide.gyroscopeEnabled, diff --git a/tools/tests/mcc_share_game.c b/tools/tests/mcc_share_game.c new file mode 100644 index 0000000000..074b0885fc --- /dev/null +++ b/tools/tests/mcc_share_game.c @@ -0,0 +1,947 @@ +/* The game side of MCC package sharing (mcc_share.c) against stub engine headers: two copies of + * the real file, one playing the host and one the joiner, each in a folder of its own, exchange + * the real distributed messages through a queue. The real source planner, session and stage + * run against synthetic files. The engine identity probe hashes the map and available resources + * through mcc_package.c's paths, exercising the staging redirect. Metadata schema/decoder stubs + * isolate adapter behavior; their production implementation has its own suite. + * No game, no sockets, no game data. argv[1] is a case, argv[2] an + * empty folder. */ +#define _POSIX_C_SOURCE 200809L +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#include +#include +#define chdir _chdir +#define getcwd _getcwd +#define rmdir _rmdir +#define unlink _unlink +#define mkdir(p,m) _mkdir(p) +#define S_ISDIR(m) (((m)&_S_IFMT)==_S_IFDIR) +#else +#include +#include +#endif +#include +#include "mcc_package.h" +#include "mcc_sha256.h" +#include "mcc_share_session.h" +#include "mcc_workshop.h" +#include "mcc_share_metadata.h" +#include "mcc_share_storage.h" +#include "mcc_validation.h" +#include "cseries.h" +#include "networking/network_client_manager.h" +#include "network_distributed.h" + +/* Match the engine allocator contract without reading a libc pointer's absent + * debug header. A mismatched allocation fails deterministically under ASan too. */ +#undef malloc +#undef free +static void *engine_allocations[32]; +static int engine_allocation_count; +void *fixture_engine_malloc(size_t bytes) +{ + void *pointer=malloc(bytes); + if (pointer) { + if (engine_allocation_count==32) { fprintf(stderr,"engine allocation fixture full\n"); exit(85); } + memset(pointer,0xca,bytes); + engine_allocations[engine_allocation_count++]=pointer; + } + return pointer; +} +void fixture_engine_free(void *pointer) +{ + int i; + for (i=0;iopen_native_read=mcc_share_open_native; } +int mcc_share_storage_find_resource(char const *maps,struct mcc_share_io const *io, + struct mcc_share_file const *expected,char path[1024]) +{ (void)maps;(void)io;(void)expected;(void)path;return 0; } + +/* Storage receipt/attribution security has its own real-filesystem suite. */ +int mcc_share_storage_record(struct mcc_share_stage *stage,char const *source,char const *maker, + struct mcc_workshop_item const *item) +{ + (void)item; + return stage->verified && stage->state==MCC_SHARE_STAGE_STAGED && source[0] && maker[0]; +} + +struct message { unsigned bytes; unsigned char data[4200]; long machine; }; +static struct message to_host[400],to_join[400]; +static int to_host_count,to_join_count; + +/* ---------- the stubs the game side calls */ + +int config_boolean(char const *name) +{ + if (!strcmp(name,"network.mcc_map_share")) return map_share_on; + if (!strcmp(name,"network.map_download")) return map_download_on; + return 0; +} +static long upload_kb=64; +long config_integer(char const *name) { return strcmp(name,"network.map_share_upload")==0 ? upload_kb : 0; } +unsigned long system_milliseconds(void) { return clock_ms; } +void error(short level, char const *format, ...) { (void)level;(void)format; } +int csstrcasecmp(char const *a, char const *b) +{ + for (;*a && *b;a++,b++) { + int x=*a,y=*b; + if (x>='A' && x<='Z') x+='a'-'A'; + if (y>='A' && y<='Z') y+='a'-'A'; + if (x!=y) return x-y; + } + return *a-*b; +} +void offset_rectangle2d(void *r, short x, short y) { (void)r;(void)x;(void)y; } +void build_message_header(word *header, word size, int type, int flags) { *header=(word)(size<<4|type<<2|flags); } +int game_in_progress(void) { return 0; } +long game_time_get(void) { return 0; } +long interface_get_tag_index(int tag) { (void)tag; return 1; } +void draw_string_set_draw_mode(long a, long b, short c, short d, void const *e) { (void)a;(void)b;(void)c;(void)d;(void)e; } +void rasterizer_draw_string(void *a, void *b, void *c, short d, char const *e) { (void)a;(void)b;(void)c;(void)d;if (!e || !*e) exit(2);overlay_draws++;snprintf(overlay_text,sizeof(overlay_text),"%s",e); } +struct { struct { rectangle2d window_bounds,viewport_bounds; } camera; } render; + +void mcc_maps_rescan(void) {} +int mcc_maps_workshop_title(char const *item, char *title, size_t size) { (void)item;(void)title;(void)size; return 0; } + +/* the engine's file calls, on the folder the copy runs in */ +static int exists_any(char const *path) { struct stat s; return stat(path,&s)==0; } +unsigned long GetFileAttributesA(char const *path) +{ + struct stat s; + if (stat(path,&s)) return (unsigned long)-1; + return S_ISDIR(s.st_mode) ? 0x10 : 0x80; +} +int CreateDirectoryA(char const *path, void *security) { (void)security; return mkdir(path,0755)==0; } +int RemoveDirectoryA(char const *path) { return rmdir(path)==0; } +static unsigned long long disk_free=1ull<<40; +typedef union { struct { unsigned int LowPart, HighPart; }; unsigned long long QuadPart; } ULARGE_INTEGER; +int GetDiskFreeSpaceExA(char const *path, ULARGE_INTEGER *available, ULARGE_INTEGER *total, ULARGE_INTEGER *free_total) +{ + (void)path;(void)total;(void)free_total; + available->QuadPart=disk_free; + return 1; +} +int MoveFileA(char const *from, char const *to) { return !exists_any(to) && rename(from,to)==0; } +int DeleteFileA(char const *path) { return remove(path)==0; } + +/* the identity of the package at its paths: the map and its two resource maps, in order */ +static int package_digest(char const *level, unsigned char digest[32]) +{ + struct mcc_sha256 hash; + char path[1024]; + unsigned i; + mcc_sha256_begin(&hash); + for (i=0;i<3;i++) { + FILE *f; + unsigned char block[4096]; + size_t got; + char *p; + if (i && !(resource_mask&(1u<<(i-1)))) continue; + if (i==0) { + if (!mcc_package_map_path(level,path)) return 0; + memmove(path,path+3,strlen(path+3)+1); + for (p=path;*p;p++) if (*p=='\\') *p='/'; + } else if (!mcc_package_resource_path(level,i,path)) return 0; + f=fixture_fopen(path,"rb"); + if (!f) { if (i) continue; return 0; } + while ((got=fread(block,1,sizeof(block),f))>0) mcc_sha256_add(&hash,block,(int)got); + fclose(f); + } + mcc_sha256_end(&hash,digest); + return 1; +} +/* The real incremental backend has its own reader/stamp tests. This fixture + * makes completion take several frames and requires proof promotion before + * admission, so adapter ordering cannot hide a second synchronous probe. */ +struct mcc_validation_check {char name[64],directory[128];int remaining;}; +struct mcc_validation_check *mcc_validation_check_begin(char const *name,char const *directory) +{ + struct mcc_validation_check *check=calloc(1,sizeof(*check)); + if (!check) return NULL; + strcpy(check->name,name);strcpy(check->directory,directory);check->remaining=validation_delay; + validation_live++;return check; +} +int mcc_validation_check_step(struct mcc_validation_check *check,struct mcc_validation_proof *proof, + char *reason,size_t reason_size) +{ + int ok; + (void)reason;(void)reason_size;validation_steps++; + if (--check->remaining>0) return 0; + memset(proof,0,sizeof(*proof));strcpy(proof->name,check->name);strcpy(proof->directory,check->directory); + mcc_package_stage_redirect(check->name,check->directory); + ok=package_digest(check->name,proof->digest); + mcc_package_stage_redirect(NULL,NULL); + return ok ? 1 : -1; +} +void mcc_validation_check_end(struct mcc_validation_check *check) +{if(check){validation_live--;free(check);}} +int mcc_validation_publish(char const *name,struct mcc_validation_proof const *proof) +{ + published++;strcpy(published_name,name);memcpy(published_digest,proof->digest,32);return 1; +} +int j_mcc_identity_host_package(char const *level, unsigned char digest[32]) { (void)level;(void)digest;return 0; } +int h_mcc_identity_host_package(char const *level, unsigned char digest[32]) +{ + if (csstrcasecmp(level,LEVEL)) return 0; + memcpy(digest,host_digest,32); + return 1; +} + +static void find_snapshot(void) +{ +#ifdef _WIN32 + struct _finddata_t info; + intptr_t search=_findfirst("mcc_maps/dl_*",&info); + if (search!=-1) { + do { if (info.attrib&_A_SUBDIR) snprintf(snapshot,sizeof(snapshot),"%s",info.name); } + while (!_findnext(search,&info)); + _findclose(search); + } +#else + DIR *dir=opendir("mcc_maps"); + struct dirent *entry; + if (!dir) return; + while ((entry=readdir(dir))) if (!strncmp(entry->d_name,"dl_",3)) + snprintf(snapshot,sizeof(snapshot),"%s",entry->d_name); + closedir(dir); +#endif +} +void h_mcc_identity_set_missing(int (*handler)(char const[128],unsigned char const[32],unsigned char const[32])) { host_missing=handler; } +void j_mcc_identity_set_missing(int (*handler)(char const[128],unsigned char const[32],unsigned char const[32])) { join_missing=handler; } +int j_mcc_identity_accept_installed(char const name[128], unsigned char const digest[32],unsigned char const metadata[32],char const *installed) +{ + (void)name;(void)metadata; + accepts++; + find_snapshot(); + accept_result=published && !strcmp(installed,published_name) && !memcmp(published_digest,digest,32); + return accept_result; +} +int h_mcc_identity_accept_installed(char const name[128],unsigned char const digest[32],unsigned char const metadata[32],char const *installed) +{ (void)name;(void)digest;(void)metadata;return 1; } +unsigned long h_mcc_identity_host_revision(void) { return host_revision; } +unsigned long j_mcc_identity_host_revision(void) { return 0; } +void h_display_error_text_when_main_menu_loaded(wchar_t const *t) { (void)t; } +void j_display_error_text_when_main_menu_loaded(wchar_t const *text) +{ + unsigned i; + errors_shown++; + for (i=0;text[i] && ivalid; } +struct network_game *h_network_game_client_get_game(struct network_game_client *c) { return &host_game; } +struct network_game *j_network_game_client_get_game(struct network_game_client *c) { return &join_game; } +struct network_game *h_network_game_get_game(void) { return &host_game; } +struct network_game *j_network_game_get_game(void) { return join_in_game ? &join_game : NULL; } +struct network_game_server *h_global_network_game_server_get(void) { return &server; } +struct network_game_server *j_global_network_game_server_get(void) { return NULL; } +struct network_game_client *h_global_network_game_client_get(void) { return &client; } +struct network_game_client *j_global_network_game_client_get(void) { return join_in_game ? &client : NULL; } +struct network_game_server_client_machine *network_game_server_get_client_machine_at_index(struct network_game_server *s,long index) +{ return index==MACHINE ? &peer : NULL; } +int network_game_server_client_machine_is_joined_to_game(struct network_game_server *s,struct network_game_server_client_machine *p) +{ return p==&peer && peer_joined; } +int mcc_level_name(char const *name) { return !strncmp(name,"mcc_maps",8); } +int network_connection_last_read_was_unreliable(void) { return 0; } +static int joiner_replies; +void platform_translate_path(char const *input,char *output,unsigned long size) +{ + char path[2048],cwd[1024],*p; + if (!strncmp(input,"d:",2)) { + input+=2; + while (*input=='/' || *input=='\\') input++; + } + snprintf(path,sizeof(path),"%s",input); + for (p=path;*p;p++) if (*p=='\\') *p='/'; + if (role_host && workshop_fallback && (!strcmp(path,"mcc_maps/solar_flare/bitmaps.map") || + !strcmp(path,"mcc_maps/solar_flare/sounds.map"))) { + snprintf(output,size,"%s/halo1/maps/%s",host_dir,strrchr(path,'/')+1);return; + } + if (path[0]=='/' || (path[0] && path[1]==':')) snprintf(output,size,"%s",path); + else { getcwd(cwd,sizeof(cwd)); snprintf(output,size,"%s/%s",cwd,path); } +} +FILE *fixture_fopen(char const *path,char const *mode) +{ char native[2048]; platform_translate_path(path,native,sizeof(native)); return fopen(native,mode); } +int posix_find_entry_case_insensitive(char const *directory,char const *name,char *result,unsigned long size) +{ + char path[2048]; + snprintf(path,sizeof(path),"%s/%s",directory,name); + if (!exists_any(path)) return 0; + snprintf(result,size,"%s",name); return 1; +} +int mcc_validation_resources(char const *name,char paths[2][128]) +{ + unsigned i; + memset(paths,0,256); + if (resource_invalid) return 0; + for (i=1;i<=2;i++) if (resource_mask&(1u<<(i-1))) + if (!mcc_package_resource_path(resource_shared ? "mcc_maps/root" : name,i,paths[i-1])) return 0; + return 1; +} +int mcc_manifest_package_root(char const *level,char root[1024]) +{ + char path[128],*p; + if (!mcc_package_map_path(level,path)) return 0; + platform_translate_path(path,root,1024); + p=strrchr(root,'/'); if (!p) return 0; *p=0; return 1; +} +/* Metadata parsing/PNG decoding have independent production-source tests. These deterministic + * fixture planners isolate adapter consent, file selection, hashing and publication. */ +int mcc_share_metadata_plan(char const *root,int campaign,char const *level, + struct mcc_share_metadata_plan *plan,char reason[128]) +{ + static char const *paths[]={"ModInfo.json","assets/menu.png","workshop_id.txt"}; + unsigned i; + memset(plan,0,sizeof(*plan)); + for (i=0;i<3;i++) { + char path[2048]; struct stat st; + snprintf(path,sizeof(path),"%s/%s",root,paths[i]); + if (!stat(path,&st)) { + struct mcc_share_metadata_entry *e=&plan->files[plan->count++]; + if (i==2) { + char text[128]; struct mcc_workshop_item item; FILE *f=fopen(path,"rb"); size_t n; + if (!f) return 0; n=fread(text,1,sizeof(text)-1,f); fclose(f); text[n]=0; + if (!mcc_workshop_parse_sidecar(text,&item)) return 0; + } + snprintf(e->path,sizeof(e->path),"%s",paths[i]); e->kind=i+1; e->size=(unsigned)st.st_size; + } + } + return 1; +} +int mcc_share_metadata_digest(char const *root,int campaign,char const *level,unsigned char digest[32],char reason[128]) +{ + char path[2048]; FILE *file; struct mcc_sha256 hash; unsigned char bytes[256]; size_t n; + memset(digest,0,32); snprintf(path,sizeof(path),"%s/ModInfo.json",root); file=fopen(path,"rb"); + if (!file) return 1; + mcc_sha256_begin(&hash); + while ((n=fread(bytes,1,sizeof(bytes),file))) mcc_sha256_add(&hash,bytes,(int)n); + fclose(file); mcc_sha256_end(&hash,digest); return 1; +} +int mcc_share_metadata_validate(char const *root,int campaign,char const *level, + struct mcc_share_metadata_entry const *received,int count,unsigned char keep[160],char reason[128]) +{ + struct mcc_share_metadata_plan plan; int i,j; + if (!mcc_share_metadata_plan(root,campaign,level,&plan,reason) || plan.count!=count) return 0; + for (i=0;i>24); + } + return data; +} + +static int write_text(char const *path, unsigned char const *data, unsigned size) +{ + FILE *f=fopen(path,"wb"); + if (!f) return 0; + if (fwrite(data,1,size,f)!=size) {fclose(f);return 0;} + return fclose(f)==0; +} + +static int read_file(char const *path, unsigned char **data, unsigned *size) +{ + FILE *f=fopen(path,"rb"); + long n; + if (!f) return 0; + fseek(f,0,SEEK_END);n=ftell(f);fseek(f,0,SEEK_SET); + *data=malloc((size_t)n+1); + if (fread(*data,1,(size_t)n,f)!=(size_t)n) {fclose(f);return 0;} + fclose(f); + *size=(unsigned)n; + return 1; +} + +static int same_file(char const *a, char const *b) +{ + unsigned char *da=NULL,*db=NULL; + unsigned sa=0,sb=0; + int same=read_file(a,&da,&sa) && read_file(b,&db,&sb) && sa==sb && !memcmp(da,db,sa); + free(da);free(db); + return same; +} + +static int exists(char const *path) { struct stat s; return stat(path,&s)==0; } + +static int host_make(char const *leaf, unsigned size, unsigned seed) +{ + char path[2048]; + unsigned char *data=make_bytes(size,seed); + int ok; + snprintf(path,sizeof(path),"%s/mcc_maps/solar_flare/%s",host_dir,leaf); + ok=write_text(path,data,size); + free(data); + return ok; +} + +static void as_host(void) { role_host=1; if (chdir(host_dir)) abort(); } +static void as_join(void) { role_host=0; if (chdir(join_dir)) abort(); } + +static int setup(char const *base) +{ + char path[2048]; + unsigned char list[200]; + char hex[65]; + unsigned i; + snprintf(host_dir,sizeof(host_dir),"%s/host",base); + snprintf(join_dir,sizeof(join_dir),"%s/join",base); + if (mkdir(host_dir,0755) || mkdir(join_dir,0755)) return 0; + snprintf(path,sizeof(path),"%s/mcc_maps",host_dir);if (mkdir(path,0755)) return 0; + snprintf(path,sizeof(path),"%s/mcc_maps/solar_flare",host_dir);if (mkdir(path,0755)) return 0; + if (!host_make("m0.map",15483,1) || !host_make("bitmaps.map",7000,2) || !host_make("sounds.map",6144,3)) return 0; + snprintf(path,sizeof(path),"%s/mcc_maps/solar_flare/assets",host_dir); if (mkdir(path,0755)) return 0; + if (!host_make("ModInfo.json",120,4) || !host_make("assets/menu.png",80,6) || !host_make("readme.txt",300,5)) return 0; + as_host(); + if (!package_digest(LEVEL,host_digest)) return 0; + { char reason[128]; if (!mcc_share_metadata_digest("mcc_maps/solar_flare",-1,"m0",host_metadata,reason)) return 0; } + for (i=0;i<32;i++) snprintf(hex+i*2,3,"%02x",host_digest[i]); + snprintf((char *)list,sizeof(list),"# the host's own list\n%s Example Maker\n",hex); + if (!write_text("mcc_share.txt",list,(unsigned)strlen((char *)list))) return 0; + map_share_on=1;map_download_on=1; + return 1; +} + +static void pump_once(void) +{ + static struct message batch[400]; + int i,count; + count=to_host_count;memcpy(batch,to_host,(size_t)count*sizeof(batch[0]));to_host_count=0; + as_host(); + for (i=0;ibefore; +} +static int pump_until_done(int limit) +{ + int i; + for (i=0;i1) return 0; + } + return accepts>0; +} +static void wire_name(char name[128],char const *level) +{ memset(name,0,128); snprintf(name,64,"%s",level); } +static int joiner_asks(char const *level,unsigned char const digest[32]) +{ + char name[128]; wire_name(name,level); memcpy(join_game.mcc_content_sha256,digest,32); + memcpy(join_game.mcc_metadata_sha256,host_metadata,32);as_join(); return join_missing(name,digest,host_metadata); +} +static int workshop_asks(void) +{ + char name[128]; struct mcc_workshop_item item; + wire_name(name,LEVEL); memset(&item,0,sizeof(item)); strcpy(item.id,"2915693904"); strcpy(item.title,"Fixture package"); + mcc_workshop_wire_pack(name,&item); memcpy(join_game.map.name,name,128); + memcpy(join_game.mcc_content_sha256,host_digest,32);memcpy(join_game.mcc_metadata_sha256,host_metadata,32); + as_join(); return join_missing(name,host_digest,host_metadata); +} +static int write_list(unsigned char const digest[32],char const *maker) +{ + char text[200],hex[65]; unsigned i; + for (i=0;i<32;i++) snprintf(hex+i*2,3,"%02x",digest[i]); + snprintf(text,sizeof(text),"%s %s\n",hex,maker); as_host(); + return write_text("mcc_share.txt",(unsigned char *)text,(unsigned)strlen(text)); +} +static int transfer_started(void) +{ + int i; + if (!joiner_asks(LEVEL,host_digest) || !pump_prompt() || !j_mcc_share_game_can_download()) return 0; + as_join(); j_mcc_share_game_prompt_action(0); + for (i=0;i<3;i++) pump_once(); + return h_mcc_share_game_machine_active(MACHINE) && j_mcc_share_game_holds_players(); +} + +int main(int argc,char **argv) +{ + char a[2048],b[2048]; unsigned i; + if (argc!=3) return 2; + if (!setup(argv[2])) { fprintf(stderr,"setup failed\n"); return 2; } + snprintf(host_game.map.name,sizeof(host_game.map.name),"%s",LEVEL); + snprintf(join_game.map.name,sizeof(join_game.map.name),"%s",LEVEL); + as_join();j_mcc_share_game_update(); as_host();h_mcc_share_game_update(); + CHECK(host_missing && join_missing); + + if (!strncmp(argv[1],"manual_",7)) { + map_share_on=0; + if (!strcmp(argv[1],"manual_client_off")) {map_share_on=1;map_download_on=0;} + if (!strcmp(argv[1],"manual_wait_menu")) menu_loaded=0; + if (!strcmp(argv[1],"manual_local")) CHECK(joiner_asks(LEVEL,host_digest)); + else CHECK(workshop_asks()); + for (i=0;i<10;i++) pump_once(); + CHECK(aborts==1 && !join_in_game && !j_mcc_share_game_holds_players()); + CHECK(!j_mcc_share_game_downloading(LEVEL) && !j_mcc_share_game_can_download()); + if (!strcmp(argv[1],"manual_wait_menu")) { + CHECK(!prompts);menu_loaded=1;CHECK(pump_prompt()); + } + CHECK(prompts==1 && manual_return && !menu_returns); + clock_ms+=20000;for (i=0;i<5;i++) pump_once(); + CHECK(prompts==1 && !accepts && aborts==1); + as_join(); + if (!strcmp(argv[1],"manual_closed")) j_mcc_share_game_prompt_closed(); + else if (!strcmp(argv[1],"manual_cancel")) j_mcc_share_game_prompt_action(2); + else if (!strcmp(argv[1],"manual_disconnect")) j_mcc_share_game_disconnect(); + else if (!strcmp(argv[1],"manual_stale_workshop")) { + join_in_game=1;j_mcc_share_game_prompt_action(1);CHECK(!opened_url[0]); + } + else if (!strcmp(argv[1],"manual_new_join")) { + join_in_game=1;strcpy(join_game.map.name,"custom_maps\\bloodgulch"); + j_mcc_share_game_update(); + } else if (!strcmp(argv[1],"manual_map_load")) { + menu_loaded=0;j_mcc_share_game_update(); + } else if (!strcmp(argv[1],"manual_stale_accept")) j_mcc_share_game_prompt_action(0); + else { + CHECK(j_mcc_share_game_has_workshop()==(strcmp(argv[1],"manual_local")!=0)); + j_mcc_share_game_prompt_action(1); + CHECK(menu_returns==1); + CHECK(!strcmp(argv[1],"manual_local") ? !opened_url[0] : + !strcmp(opened_url,"https://steamcommunity.com/sharedfiles/filedetails/?id=2915693904")); + } + CHECK(!j_mcc_share_game_has_workshop() && !accepts && aborts==1); + for (i=0;i<5;i++) pump_once();CHECK(prompts==1); + snprintf(b,sizeof(b),"%s/mcc_maps",join_dir);CHECK(!exists(b)); + snprintf(b,sizeof(b),"%s/mcc_staging",join_dir);CHECK(!exists(b));return 0; + } + + if(!strcmp(argv[1],"validation_handoff") || !strcmp(argv[1],"validation_stale_handoff")) { + admission_pending=1;block_request=1; + CHECK(joiner_asks(LEVEL,host_digest)); + for(i=0;i<10;i++)pump_once(); + CHECK(admission_pending && j_mcc_share_game_holds_players() && !prompts); + if(!strcmp(argv[1],"validation_stale_handoff"))admission_token++; + block_request=0;CHECK(pump_prompt()); + CHECK(admission_pending==!strcmp(argv[1],"validation_stale_handoff")); + as_join();j_mcc_share_game_disconnect();return 0; + } + + CASE("local_validation_hold") { + map_share_on=map_download_on=0; + validation_pending=admission_pending=1; + as_join();CHECK(j_mcc_share_game_holds_players() && j_mcc_share_game_downloading(LEVEL)); + CHECK(!j_mcc_share_game_downloading("maps\\bloodgulch")); + as_host();CHECK(h_mcc_share_game_machine_active(MACHINE) && h_mcc_share_game_machine_needs_map(MACHINE)); + CHECK(!h_mcc_share_game_machine_active(-1)); + h_mcc_share_game_peer_left(&peer); + CHECK(!admission_pending); + as_join();validation_pending=0;CHECK(!j_mcc_share_game_holds_players());return 0; + } + CASE("validation_pending_cancel") { + validation_delay=1000; + CHECK(joiner_asks(LEVEL,host_digest));CHECK(pump_prompt());as_join();j_mcc_share_game_prompt_action(0); + for(i=0;i<500 && !validation_live;i++)pump_once(); + CHECK(validation_live==1 && !accepts && !published); + for(i=0;i<10;i++)pump_once(); + CHECK(validation_steps>0 && validation_live==1 && !accepts); + as_join();j_mcc_share_game_render();CHECK(strstr(overlay_text,"Verifying the downloaded map")); + as_join();j_mcc_share_game_disconnect();CHECK(!validation_live && !accepts && !published);return 0; + } + + CASE("prompt_overlay") { + as_join();j_mcc_share_game_render();CHECK(!overlay_draws); + CHECK(joiner_asks(LEVEL,host_digest));j_mcc_share_game_render();CHECK(overlay_draws==1); + allow_prompt=0; + for (i=0;i<300 && !j_mcc_share_game_can_download();i++) pump_once(); + CHECK(j_mcc_share_game_can_download() && !prompts); + j_mcc_share_game_render();CHECK(overlay_draws==1); + allow_prompt=1;CHECK(pump_prompt());as_join();j_mcc_share_game_render();CHECK(overlay_draws==1); + j_mcc_share_game_prompt_action(0);j_mcc_share_game_render();CHECK(overlay_draws==2); + j_mcc_share_game_disconnect();j_mcc_share_game_render();CHECK(overlay_draws==2);return 0; + } + CASE("host_revision") { + CHECK(transfer_started());as_host();host_revision++;h_mcc_share_game_update(); + CHECK(!h_mcc_share_game_machine_active(MACHINE));as_join();j_mcc_share_game_disconnect();return 0; + } + if (!strcmp(argv[1],"shared_resource") || !strcmp(argv[1],"invalid_resource")) { + resource_shared=!strcmp(argv[1],"shared_resource");resource_invalid=!strcmp(argv[1],"invalid_resource"); + if (resource_shared) { + unsigned char *data=NULL;unsigned bytes=0; + as_host();CHECK(read_file("mcc_maps/solar_flare/bitmaps.map",&data,&bytes)); + CHECK(write_text("mcc_maps/bitmaps.map",data,bytes));free(data); + CHECK(read_file("mcc_maps/solar_flare/sounds.map",&data,&bytes)); + CHECK(write_text("mcc_maps/sounds.map",data,bytes));free(data); + } + CHECK(joiner_asks(LEVEL,host_digest));CHECK(pump_prompt() && !j_mcc_share_game_can_download()); + CHECK(accepts==0);as_join();j_mcc_share_game_prompt_action(2);return 0; + } + if (!strcmp(argv[1],"unused_resources") || !strcmp(argv[1],"bitmap_only")) { + resource_mask=!strcmp(argv[1],"unused_resources") ? 0 : 1;as_host(); + CHECK(write_text("mcc_maps/solar_flare/sounds.map",(unsigned char *)"unrelated invalid",17)); + if (!resource_mask) CHECK(write_text("mcc_maps/solar_flare/bitmaps.map",(unsigned char *)"also unrelated",14)); + CHECK(package_digest(LEVEL,host_digest));CHECK(write_list(host_digest,"Example Maker")); + } + CASE("workshop_resource_fallback") { + as_host();CHECK(!mkdir("halo1",0755));CHECK(!mkdir("halo1/maps",0755)); + CHECK(!rename("mcc_maps/solar_flare/bitmaps.map","halo1/maps/bitmaps.map")); + CHECK(!rename("mcc_maps/solar_flare/sounds.map","halo1/maps/sounds.map"));workshop_fallback=1; + } + CASE("gate") { + char name[128]; map_download_on=0; + CHECK(joiner_asks(LEVEL,host_digest)); CHECK(to_host_count==0); + CHECK(pump_prompt() && !j_mcc_share_game_can_download()); + CHECK(strstr(shown,"OFF")); + as_join();j_mcc_share_game_disconnect(); map_download_on=1; + CHECK(!joiner_asks("maps\\bloodgulch",host_digest)); + CHECK(!joiner_asks("custom_maps\\bloodgulch",host_digest)); + CHECK(!joiner_asks("mcc_maps\\loose",host_digest)); + as_host();wire_name(name,LEVEL);CHECK(!host_missing(name,host_digest,host_metadata)); + CHECK(to_host_count==0); return 0; + } + CASE("consent") { + CHECK(joiner_asks(LEVEL,host_digest));CHECK(pump_prompt()); + CHECK(j_mcc_share_game_can_download() && j_mcc_share_game_holds_players()); + for (i=0;i<50;i++) pump_once(); + CHECK(accepts==0); snprintf(b,sizeof(b),"%s/mcc_staging",join_dir);CHECK(!exists(b)); + snprintf(b,sizeof(b),"%s/mcc_maps",join_dir);CHECK(!exists(b)); + CHECK(strstr(shown,"Example Maker") && strstr(shown,"kept")); + CHECK(pump_until_done(2000) && accept_result);return 0; + } + if (!strcmp(argv[1],"prompt_map_change") || !strcmp(argv[1],"prompt_disconnect") || + !strcmp(argv[1],"prompt_content_change") || !strcmp(argv[1],"prompt_metadata_change") || + !strcmp(argv[1],"stale_accept")) { + CHECK(joiner_asks(LEVEL,host_digest));CHECK(pump_prompt());CHECK(j_mcc_share_game_can_download()); + if (!strcmp(argv[1],"prompt_disconnect")) join_in_game=0; + else if (!strcmp(argv[1],"prompt_content_change")) join_game.mcc_content_sha256[0]^=1; + else if (!strcmp(argv[1],"prompt_metadata_change")) join_game.mcc_metadata_sha256[0]^=1; + else strcpy(join_game.map.name,"maps\\bloodgulch"); + as_join(); + if (!strcmp(argv[1],"stale_accept")) j_mcc_share_game_prompt_action(0); + else j_mcc_share_game_update(); + CHECK(!j_mcc_share_game_holds_players() && !j_mcc_share_game_can_download()); + CHECK(accepts==0);snprintf(b,sizeof(b),"%s/mcc_staging",join_dir);CHECK(!exists(b));return 0; + } + CASE("cancel") { + CHECK(joiner_asks(LEVEL,host_digest));CHECK(pump_prompt()); + as_join();j_mcc_share_game_prompt_action(2); CHECK(aborts==1 && !j_mcc_share_game_holds_players()); + snprintf(b,sizeof(b),"%s/mcc_staging",join_dir);CHECK(!exists(b)); return 0; + } + CASE("workshop_off") { map_share_on=0; } + CASE("workshop_client_off") { map_download_on=0; } + if (!strcmp(argv[1],"workshop_off") || !strcmp(argv[1],"workshop_client_off")) { + CHECK(workshop_asks()); if (!map_download_on) CHECK(to_host_count==0); + CHECK(pump_prompt() && j_mcc_share_game_has_workshop() && !j_mcc_share_game_can_download()); + as_join();j_mcc_share_game_prompt_action(1); + CHECK(!strcmp(opened_url,"https://steamcommunity.com/sharedfiles/filedetails/?id=2915693904")); + CHECK(aborts==1 && accepts==0); snprintf(b,sizeof(b),"%s/mcc_maps",join_dir);CHECK(!exists(b));return 0; + } + CASE("off") { map_share_on=0; } + CASE("unlisted") { as_host();CHECK(!unlink("mcc_share.txt")); } + CASE("listed_without_maker") { CHECK(write_list(host_digest,"")); } + CASE("another_package_listed") { unsigned char d[32];memcpy(d,host_digest,32);d[0]^=1;CHECK(write_list(d,"Other")); } + CASE("unreadable_sidecar") { as_host();CHECK(write_text("mcc_maps/solar_flare/workshop_id.txt",(unsigned char *)"bad id",6)); } + if (!strcmp(argv[1],"off") || !strcmp(argv[1],"unlisted") || !strcmp(argv[1],"listed_without_maker") || + !strcmp(argv[1],"another_package_listed") || !strcmp(argv[1],"unreadable_sidecar")) { + CHECK(joiner_asks(LEVEL,host_digest));CHECK(pump_prompt()); CHECK(!j_mcc_share_game_can_download() && accepts==0); + snprintf(b,sizeof(b),"%s/mcc_staging",join_dir);CHECK(!exists(b)); + as_join();j_mcc_share_game_prompt_action(2);CHECK(aborts==1);return 0; + } + CASE("disk_space") { + disk_free=20ull<<20;CHECK(joiner_asks(LEVEL,host_digest));CHECK(pump_prompt()); + if (j_mcc_share_game_can_download()) {as_join();j_mcc_share_game_prompt_action(0);CHECK(pump_prompt());} + CHECK(strstr(shown,"disk space") && accepts==0);snprintf(b,sizeof(b),"%s/mcc_staging",join_dir);CHECK(!exists(b));return 0; + } + CASE("identity_mismatch") { host_digest[3]^=0x40; } + CASE("metadata_mismatch") { host_metadata[3]^=0x40; } + if (!strcmp(argv[1],"identity_mismatch") || !strcmp(argv[1],"metadata_mismatch")) { + /* Identity on the wire differs from the actual staged bytes. The host list still represents original bytes. */ + if (!strcmp(argv[1],"identity_mismatch")) CHECK(write_list(host_digest,"Example Maker")); + CHECK(joiner_asks(LEVEL,host_digest));CHECK(pump_prompt()); CHECK(j_mcc_share_game_can_download()); + as_join();j_mcc_share_game_prompt_action(0);CHECK(pump_prompt()); + CHECK(!j_mcc_share_game_can_download() && accepts==0);as_join();find_snapshot();CHECK(!snapshot[0]);return 0; + } + if (!strcmp(argv[1],"leave") || !strcmp(argv[1],"map_changes") || !strcmp(argv[1],"client_toggle")) { + CHECK(transfer_started()); + if (!strcmp(argv[1],"leave")) join_in_game=0; + else if (!strcmp(argv[1],"client_toggle")) map_download_on=0; + else strcpy(join_game.map.name,"custom_maps\\bloodgulch"); + as_join();j_mcc_share_game_update(); + if (!strcmp(argv[1],"client_toggle")) { + CHECK(!j_mcc_share_game_can_download()); + CHECK(pump_prompt()); + CHECK(strstr(shown,"OFF")); + j_mcc_share_game_prompt_action(2);CHECK(aborts==1);aborts=0; + } + CHECK(!j_mcc_share_game_holds_players()); + CHECK(!j_mcc_share_game_downloading(LEVEL));find_snapshot();CHECK(!snapshot[0]);CHECK(!aborts);return 0; + } + if (!strcmp(argv[1],"host_toggle") || !strcmp(argv[1],"peer_left")) { + CHECK(transfer_started()); as_host(); + if (!strcmp(argv[1],"host_toggle")) {map_share_on=0;h_mcc_share_game_update();} + else {peer_joined=0;h_mcc_share_game_peer_left(&peer);} + CHECK(!h_mcc_share_game_machine_active(MACHINE));as_join();j_mcc_share_game_disconnect();CHECK(!j_mcc_share_game_holds_players());return 0; + } + if (!strcmp(argv[1],"handlers") || !strcmp(argv[1],"not_the_games_package")) { + struct {struct distributed_message_header h;struct mcc_share_request r;} m; + memset(&m,0,sizeof(m));m.h.type=103;m.h.count=1;build_message_header(&m.h.header,sizeof(m),2,0); + m.r.op=MCC_SHARE_OP_MANIFEST;strcpy(m.r.level,LEVEL); + CHECK(h_mcc_share_game_handles_message((word *)&m,sizeof(m))); + m.h.type=104;CHECK(h_mcc_share_game_handles_message((word *)&m,sizeof(m))); + m.h.type=101;CHECK(!h_mcc_share_game_handles_message((word *)&m,sizeof(m))); + m.h.type=83;CHECK(!h_mcc_share_game_handles_message((word *)&m,sizeof(m)));m.h.type=103; + CHECK(!h_mcc_share_game_handles_message((word *)&m,4));as_host(); + if (!strcmp(argv[1],"not_the_games_package")) { + struct mcc_share_response response; + strcpy(m.r.level,"mcc_maps\\solar_flare\\m1"); + h_mcc_share_game_handle_message(MACHINE,(word *)&m,sizeof(m),1);h_mcc_share_game_update(); + CHECK(to_join_count==1);memcpy(&response,to_join[0].data+sizeof(m.h),sizeof(response)); + CHECK(response.result==MCC_SHARE_RESULT_NOT_SHAREABLE);return 0; + } + h_mcc_share_game_handle_message(MACHINE,(word *)&m,sizeof(m),0); + h_mcc_share_game_update();CHECK(to_join_count==0 && !h_mcc_share_game_machine_active(MACHINE)); + h_mcc_share_game_handle_message(-1,(word *)&m,sizeof(m),1); + h_mcc_share_game_handle_message(MACHINE+1,(word *)&m,sizeof(m),1); + h_mcc_share_game_handle_message(MACHINE,(word *)&m,sizeof(m)-1,1); + peer_joined=0;h_mcc_share_game_handle_message(MACHINE,(word *)&m,sizeof(m),1);peer_joined=1; + m.h.count=2;h_mcc_share_game_handle_message(MACHINE,(word *)&m,sizeof(m),1);m.h.count=1; + m.h.header|=1;h_mcc_share_game_handle_message(MACHINE,(word *)&m,sizeof(m),1);m.h.header&=~1; + h_mcc_share_game_update();CHECK(to_join_count==0 && !h_mcc_share_game_machine_active(MACHINE)); + as_join();j_mcc_share_game_handle_message(MACHINE,(word *)&m,sizeof(m),1);CHECK(joiner_replies==0 && to_host_count==0); + /* An otherwise valid offer from a peer rather than our host must not open consent. */ + CHECK(joiner_asks(LEVEL,host_digest));CHECK(to_host_count==1);as_host(); + h_mcc_share_game_handle_message(MACHINE,(word *)to_host[0].data,(word)to_host[0].bytes,1); + to_host_count=0; + for (i=0;i<100 && !to_join_count;i++) {h_mcc_share_game_update();clock_ms+=20;} + CHECK(to_join_count==1);as_join(); + j_mcc_share_game_handle_message(MACHINE,(word *)to_join[0].data,(word)to_join[0].bytes,1); + j_mcc_share_game_update();CHECK(prompts==0); + CHECK(pump_prompt() && j_mcc_share_game_can_download()); + as_join();j_mcc_share_game_prompt_action(2);CHECK(aborts==1); + return 0; + } + CASE("existing_version") { + as_join();CHECK(!mkdir("mcc_maps",0755));CHECK(!mkdir("mcc_maps/solar_flare",0755)); + CHECK(write_text("mcc_maps/solar_flare/m0.map",(unsigned char *)"original",8)); + } + CASE("map_only") { + resource_mask=0;as_host();CHECK(!unlink("mcc_maps/solar_flare/ModInfo.json"));CHECK(!unlink("mcc_maps/solar_flare/assets/menu.png")); + CHECK(!unlink("mcc_maps/solar_flare/bitmaps.map"));CHECK(!unlink("mcc_maps/solar_flare/sounds.map")); + memset(host_metadata,0,32);CHECK(package_digest(LEVEL,host_digest));CHECK(write_list(host_digest,"Example Maker")); + } + CASE("workshop_sidecar") { + as_host();CHECK(write_text("mcc_maps/solar_flare/workshop_id.txt",(unsigned char *)"2915693904\nFixture\n",19)); + } + CASE("only_listed_files") { CHECK(host_make("evil.dll",50,8));CHECK(host_make("notes.txt",50,9)); } + CASE("admission_wrap") {clock_ms=0xffffb000u;} + CHECK(joiner_asks(LEVEL,host_digest)); + if(!strncmp(argv[1],"admission_",10))clock_ms+=16000; /* Past the original playerless deadline. */ + CHECK(pump_until_done(2000));CHECK(accept_result && accepts==1 && !aborts && !errors_shown); + CHECK(lobby_restores==1); + CHECK(!j_mcc_share_game_holds_players()); + snprintf(a,sizeof(a),"%s/mcc_maps/solar_flare/m0.map",host_dir); + snprintf(b,sizeof(b),"%s/mcc_maps/%s/m0.map",join_dir,snapshot);CHECK(same_file(a,b)); + if (strcmp(argv[1],"map_only")) { + static char const *files[]={"bitmaps.map","sounds.map","ModInfo.json","assets/menu.png","readme.txt"}; + for (i=0;i<5;i++) { + if (i<2 && !(resource_mask&(1u< +#include +#include +typedef unsigned long DWORD,D3DCOLOR; +typedef unsigned GLuint,GLenum; +typedef int BOOL,GLint,GLsizei; +#define TRUE 1 +#define FALSE 0 +#define GL_NO_ERROR 0 +#define GL_TEXTURE_2D 1 +#define GL_TEXTURE_3D 2 +#define GL_TEXTURE_CUBE_MAP 3 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 10 +#define GL_MAX_TEXTURE_SIZE 20 +#define GL_MAX_3D_TEXTURE_SIZE 21 +#define GL_MAX_CUBE_MAP_TEXTURE_SIZE 22 +#define GL_TEXTURE_SWIZZLE_R 30 +#define GL_TEXTURE_SWIZZLE_G 31 +#define GL_TEXTURE_SWIZZLE_B 32 +#define GL_TEXTURE_SWIZZLE_A 33 +#define GL_RED 40 +#define GL_GREEN 41 +#define GL_BLUE 42 +#define GL_ALPHA 43 +#define GL_UNPACK_ALIGNMENT 50 +#define GL_TEXTURE_BASE_LEVEL 51 +#define GL_TEXTURE_MAX_LEVEL 52 +#define GL_RGBA8 60 +#define GL_RGBA 61 +#ifdef HALO_GLES +#define GL_BGRA GL_RGBA +#else +#define GL_BGRA 62 +#endif +#define GL_UNSIGNED_BYTE 63 +#define _texel_unknown 0 +/* DESCRIPTION */ +struct format_information {unsigned char kind;}; +struct {int s3tc;} xgpu_capabilities; +static unsigned uploaded,compressed,swizzled,decoded,wrong; +static int expected_decode; +static GLenum error; +static struct format_information format_information(DWORD f) { + struct format_information i;i.kind=(unsigned char)f;return i; +} +static unsigned long level_dimension(unsigned long n,unsigned long l) {n>>=l;return n?n:1;} +static unsigned long level_bytes(const struct xgpu_texture_description *d,unsigned long l) {(void)d;(void)l;return 16;} +static unsigned long xgpu_texture_level_offset(const struct xgpu_texture_description *d,unsigned long l) {(void)d;return l*16;} +static unsigned long xgpu_texture_face_size(const struct xgpu_texture_description *d) {return d->levels*16;} +static GLenum compressed_format(unsigned char k) {(void)k;return 70;} +static void platform_log(const char *fmt,...) {(void)fmt;} +static void texture_dump(GLenum t,const struct xgpu_texture_description *d) {(void)t;(void)d;} +static void xgpu_gl_state_invalidate(void) {} +static void glGetIntegerv(GLenum p,GLint *v) {(void)p;*v=16384;} +static GLenum glGetError(void) {GLenum e=error;error=0;return e;} +static void glBindTexture(GLenum t,GLuint n) {(void)t;(void)n;} +static void glPixelStorei(GLenum p,GLint v) {(void)p;(void)v;} +static void glTexParameteri(GLenum t,GLenum p,GLint v) { + (void)t; + if(p>=GL_TEXTURE_SWIZZLE_R && p<=GL_TEXTURE_SWIZZLE_A) { + swizzled++; +#ifdef HALO_WEB + error=0x500; +#endif +#ifdef HALO_GLES + if(v!=(GLint)((expected_decode && p==GL_TEXTURE_SWIZZLE_R)?GL_BLUE: + (expected_decode && p==GL_TEXTURE_SWIZZLE_B)?GL_RED: + GL_RED+p-GL_TEXTURE_SWIZZLE_R))wrong++; +#else + if(v!=(GLint)(GL_RED+p-GL_TEXTURE_SWIZZLE_R))wrong++; +#endif + } +} +static void fill(unsigned long *p,unsigned long n) {while(n--)*p++=0x7f123456UL;decoded++;} +static BOOL decode_level(const struct xgpu_texture_description *d,unsigned long l,const unsigned char *s,const D3DCOLOR *p,unsigned long *o) { + (void)s;(void)p;fill(o,level_dimension(d->width,l)*level_dimension(d->height,l)*level_dimension(d->depth,l));return TRUE; +} +#ifdef HALO_GLES +static void dxt_decode_level(unsigned char k,const unsigned char *s,unsigned long w,unsigned long h,unsigned long d,unsigned long *o) {(void)k;(void)s;fill(o,w*h*d);} +#endif +static void glTexImage3D(GLenum t,GLint l,GLint i,GLsizei w,GLsizei h,GLsizei d,GLint b,GLenum f,GLenum type,const void *p) { + const unsigned long *words=p;unsigned long n=(unsigned long)w*h*d; + (void)t;(void)l;(void)i;(void)b;(void)type;uploaded++; + if(f!=GL_BGRA)wrong++; + while(n--) { +#ifdef HALO_WEB + if(*words++!=0x7f563412UL)wrong++; +#else + if(*words++!=0x7f123456UL)wrong++; +#endif + } +} +static void glTexImage2D(GLenum t,GLint l,GLint i,GLsizei w,GLsizei h,GLint b,GLenum f,GLenum type,const void *p) {glTexImage3D(t,l,i,w,h,1,b,f,type,p);} +static void glCompressedTexImage3D(GLenum t,GLint l,GLenum f,GLsizei w,GLsizei h,GLsizei d,GLint b,GLsizei n,const void *p) { + (void)t;(void)l;(void)f;(void)w;(void)h;(void)d;(void)b;(void)n;(void)p;compressed++; +#ifdef HALO_WEB + if(t==GL_TEXTURE_3D || ((w< +#include +#include +#include +#ifdef _WIN32 +#include +typedef CRITICAL_SECTION test_mutex; +static void mutex_init(test_mutex *m) { InitializeCriticalSection(m); } +static void mutex_lock(test_mutex *m) { EnterCriticalSection(m); } +static void mutex_unlock(test_mutex *m) { LeaveCriticalSection(m); } +#define TLS __declspec(thread) +#else +#include +#include +typedef pthread_mutex_t test_mutex; +typedef unsigned long DWORD; +typedef struct native_thread *HANDLE; +#define WINAPI +#define INFINITE 0xffffffffu +static void Sleep(unsigned n) { usleep(n*1000); } +static void mutex_init(test_mutex *m) { pthread_mutex_init(m,NULL); } +static void mutex_lock(test_mutex *m) { pthread_mutex_lock(m); } +static void mutex_unlock(test_mutex *m) { pthread_mutex_unlock(m); } +#define TLS _Thread_local +#endif +static test_mutex p2p_lock; +static TLS int lock_depth; +static void lock(test_mutex *m) { mutex_lock(m); lock_depth++; } +static void unlock(test_mutex *m) { lock_depth--; mutex_unlock(m); } +#define pthread_mutex_lock lock +#define pthread_mutex_unlock unlock +static int cancelled, allow_poll, polling, allow_router, routing; +static int calls, closes, waits, fail_create, failed_creates, fail_hook, online=1, upnp_allowed; +static int lobby_quits, router_releases, work_after_stop, renewed, flowing, passes; +static struct { HANDLE handle;int joined; } handles[16]; +static void (*exit_hook)(void); +static int load(int *p) { return __atomic_load_n(p,__ATOMIC_SEQ_CST); } +static void set(int *p,int n) { __atomic_store_n(p,n,__ATOMIC_SEQ_CST); } +static void until(int *p) { int i; for(i=0;i<5000&&!load(p);i++)Sleep(1); assert(load(p)); } +#ifndef _WIN32 +struct native_thread { pthread_t id; DWORD (*start)(void*); void *arg; }; +static void *native_start(void *v) { struct native_thread *t=v; t->start(t->arg);return NULL; } +#endif +static HANDLE create_thread(void *a,DWORD size,DWORD (WINAPI *start)(void*),void *arg,DWORD flags,void *id) { + HANDLE h; + (void)a;(void)size;(void)flags;(void)id;calls++; + if(fail_create){failed_creates++;return NULL;} +#ifdef _WIN32 + h=CreateThread(NULL,0,start,arg,0,NULL); +#else + h=calloc(1,sizeof(*h));h->start=start;h->arg=arg; + assert(!pthread_create(&h->id,NULL,native_start,h)); +#endif + assert(h);handles[calls-1].handle=h;return h; +} +static void wait_thread(HANDLE h,DWORD timeout) { + int i; + assert(!lock_depth && (timeout==INFINITE || timeout==P2P_STOP_WAIT || timeout==UPNP_RELEASE_WAIT));__atomic_fetch_add(&waits,1,__ATOMIC_SEQ_CST); +#ifdef _WIN32 + assert(WaitForSingleObject(h,timeout)==WAIT_OBJECT_0); +#else + assert(!pthread_join(h->id,NULL)); +#endif + for(i=0;i +#include +#include +#include +#include +typedef unsigned long posix_ulong; +enum { DISCOVERY_DELAY=2000,PORT_ATTEMPTS=8,MAXIMUM_CHECKED_FORWARDINGS=64, + UPNPCOMMAND_SUCCESS=0,UPNP_CONNECTED_IGD=1,UPNP_PRIVATEIP_IGD=2,UPNP_DISCONNECTED_IGD=3 }; +#define FORWARDING_DESCRIPTION "Halo internet play" +#define LEASE_SECONDS "3600" +struct UPNPDev {int unused;}; +static struct {int found;struct {char *controlURL;} urls;struct {struct {char *servicetype;} first;} data; + char lan_address[64];int permanent_only;} upnp; +static int upnp_cancel_requested; +void posix_upnp_cancel(void); +static char const *test_case; +static int discoveries,igds,scans,addresses,adds,deletes,freed; +static struct UPNPDev dev; +static struct UPNPDev *upnpDiscover(int d,void *a,void *b,int c,int e,int f,int *err) { + (void)d;(void)a;(void)b;(void)c;(void)e;(void)f;(void)err;discoveries++; + if(!strcmp(test_case,"discovery"))posix_upnp_cancel();return &dev; +} +static void freeUPNPDevlist(struct UPNPDev *d) {assert(d==&dev);freed++;} +static int UPNP_GetValidIGD(struct UPNPDev *d,void *u,void *v,char *lan,size_t n,char *wan,size_t m) { + (void)d;(void)u;(void)v;(void)n;(void)wan;(void)m;strcpy(lan,"local");igds++;return UPNP_CONNECTED_IGD; +} +static void FreeUPNPUrls(void *u) {(void)u;} +static int UPNP_GetGenericPortMappingEntry(char *u,char *t,char *i,char *ext,char *client,char *in, + char *proto,char *desc,char *en,char *remote,char *duration) { + (void)u;(void)t;(void)i;(void)ext;(void)en;(void)remote;(void)duration;scans++; + if(!strcmp(test_case,"scan")) { + strcpy(client,"local");strcpy(in,"42");strcpy(proto,"UDP");strcpy(desc,FORWARDING_DESCRIPTION); + posix_upnp_cancel();return 0; + } + return -1; +} +static int port_unused(unsigned short p) {(void)p;return 1;} +static int UPNP_DeletePortMapping(char *u,char *t,char *p,char *proto,void *remote) { + (void)u;(void)t;(void)p;(void)proto;(void)remote;deletes++;return 0; +} +static int UPNP_GetExternalIPAddress(char *u,char *t,char *address) { + (void)u;(void)t;strcpy(address,"1.2.3.4");addresses++; + if(!strcmp(test_case,"address"))posix_upnp_cancel();return 0; +} +static int UPNP_AddPortMapping(char *u,char *t,const char *ext,const char *in,char *lan,const char *desc, + const char *proto,void *remote,const char *lease) { + (void)u;(void)t;(void)ext;(void)in;(void)lan;(void)desc;(void)proto;(void)remote;(void)lease;adds++; + if(!strcmp(test_case,"retry")) {posix_upnp_cancel();return 718;} + if(!strcmp(test_case,"permanent")) {posix_upnp_cancel();return 725;} + if(!strcmp(test_case,"success"))posix_upnp_cancel(); + if(!strcmp(test_case,"normal")&&adds==1)return 718; + if(!strcmp(test_case,"normal")&&adds==2)return 725; + return 0; +} +static char const *strupnperror(int r) {(void)r;return "router error";} +static void posix_random_bytes(void *v,size_t n) {memset(v,42,n);} +/* ACTUAL FUNCTIONS */ +int main(int argc,char **argv) { + posix_ulong address=0;unsigned short port=0;char error[160]="";int result; + assert(argc==2);test_case=argv[1]; + if(!strcmp(test_case,"before"))posix_upnp_cancel(); + result=posix_upnp_forward_udp(10,10,&address,&port,error,sizeof(error)); + if(!strcmp(test_case,"before"))assert(!result&&!discoveries); + else if(!strcmp(test_case,"discovery"))assert(!result&&freed==1&&!igds); + else if(!strcmp(test_case,"scan"))assert(!result&&scans==1&&!deletes&&!addresses); + else if(!strcmp(test_case,"address"))assert(!result&&addresses==1&&!adds); + else if(!strcmp(test_case,"retry")||!strcmp(test_case,"permanent"))assert(!result&&adds==1); + else { + assert(result&&address&&port); + assert(adds==(!strcmp(test_case,"normal")?3:1)); + /* A mapping made just as cancellation arrives remains owned and + * must be removable, even with the cancellation latch set. */ + posix_upnp_stop_forwarding_udp(port);assert(deletes==1); + } + return 0; +} diff --git a/tools/web_build.py b/tools/web_build.py index 9f6647f761..85d0542a71 100644 --- a/tools/web_build.py +++ b/tools/web_build.py @@ -251,7 +251,11 @@ def add_object(source: Path, cflags: str) -> None: cflags += " -Dmain=halo_game_main" add_object(source, cflags) for source in sorted(Path(config["game_sources"]).glob("*.c")): - add_object(source, game_cflags) + cflags = game_cflags + # The main menu labels the executable with its release number. + if source.as_posix() == "port/linux/game/menu_functions.c": + cflags += " " + updater_defines(release) + add_object(source, cflags) add_object(STB_VORBIS_SOURCE, game_cflags) # ---------- the platform layer and the web runtime @@ -378,7 +382,8 @@ def add_object(source: Path, cflags: str) -> None: description="WEB LICENSES $out", ) n.build(outputs=licenses, rule="web_licenses", implicit=[PORT_DIR / "licenses.py", Path("LICENSE"), sdl_license, - Path("port/third_party/bcdec/LICENSE")]) + Path("port/third_party/dualsense/TriggerEffectGenerator-LICENSE.txt"), + Path("port/third_party/bcdec/LICENSE"), Path("LICENSES/GPL-3.0-only.txt"), Path("docs/reading/bots_and_android_features.md")]) site_files.append(licenses) n.rule( name="web_version", diff --git a/tools/windows_build.py b/tools/windows_build.py index 1aea9d8c55..b01ed099ba 100644 --- a/tools/windows_build.py +++ b/tools/windows_build.py @@ -426,7 +426,11 @@ def add_object(source: Path, cflags: str) -> None: flags += " " + updater_defines(getattr(sln, "port_release", False)) add_object(source, flags) for source in sorted(Path(linux_config["game_sources"]).glob("*.c")): - add_object(source, game_cflags) + flags = game_cflags + # The main menu labels the executable with its release number. + if source.as_posix() == "port/linux/game/menu_functions.c": + flags += " " + updater_defines(getattr(sln, "port_release", False)) + add_object(source, flags) add_object(STB_VORBIS_SOURCE, game_cflags) linux_platform = Path(linux_config["platform_sources"])